allocator.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package amqp
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math/big"
  6. )
  7. const (
  8. free = 0
  9. allocated = 1
  10. )
  11. // allocator maintains a bitset of allocated numbers.
  12. type allocator struct {
  13. pool *big.Int
  14. last int
  15. low int
  16. high int
  17. }
  18. // NewAllocator reserves and frees integers out of a range between low and
  19. // high.
  20. //
  21. // O(N) worst case space used, where N is maximum allocated, divided by
  22. // sizeof(big.Word)
  23. func newAllocator(low, high int) *allocator {
  24. return &allocator{
  25. pool: big.NewInt(0),
  26. last: low,
  27. low: low,
  28. high: high,
  29. }
  30. }
  31. // String returns a string describing the contents of the allocator like
  32. // "allocator[low..high] reserved..until"
  33. //
  34. // O(N) where N is high-low
  35. func (a allocator) String() string {
  36. b := &bytes.Buffer{}
  37. fmt.Fprintf(b, "allocator[%d..%d]", a.low, a.high)
  38. for low := a.low; low <= a.high; low++ {
  39. high := low
  40. for a.reserved(high) && high <= a.high {
  41. high++
  42. }
  43. if high > low+1 {
  44. fmt.Fprintf(b, " %d..%d", low, high-1)
  45. } else if high > low {
  46. fmt.Fprintf(b, " %d", high-1)
  47. }
  48. low = high
  49. }
  50. return b.String()
  51. }
  52. // Next reserves and returns the next available number out of the range between
  53. // low and high. If no number is available, false is returned.
  54. //
  55. // O(N) worst case runtime where N is allocated, but usually O(1) due to a
  56. // rolling index into the oldest allocation.
  57. func (a *allocator) next() (int, bool) {
  58. wrapped := a.last
  59. // Find trailing bit
  60. for ; a.last <= a.high; a.last++ {
  61. if a.reserve(a.last) {
  62. return a.last, true
  63. }
  64. }
  65. // Find preceeding free'd pool
  66. a.last = a.low
  67. for ; a.last < wrapped; a.last++ {
  68. if a.reserve(a.last) {
  69. return a.last, true
  70. }
  71. }
  72. return 0, false
  73. }
  74. // reserve claims the bit if it is not already claimed, returning true if
  75. // succesfully claimed.
  76. func (a *allocator) reserve(n int) bool {
  77. if a.reserved(n) {
  78. return false
  79. }
  80. a.pool.SetBit(a.pool, n-a.low, allocated)
  81. return true
  82. }
  83. // reserved returns true if the integer has been allocated
  84. func (a *allocator) reserved(n int) bool {
  85. return a.pool.Bit(n-a.low) == allocated
  86. }
  87. // release frees the use of the number for another allocation
  88. func (a *allocator) release(n int) {
  89. a.pool.SetBit(a.pool, n-a.low, free)
  90. }