queue.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. Package queue provides a fast, ring-buffer queue based on the version suggested by Dariusz Górecki.
  3. Using this instead of other, simpler, queue implementations (slice+append or linked list) provides
  4. substantial memory and time benefits, and fewer GC pauses.
  5. The queue implemented here is as fast as it is for an additional reason: it is *not* thread-safe.
  6. */
  7. package queue
  8. const minQueueLen = 16
  9. // Queue represents a single instance of the queue data structure.
  10. type Queue struct {
  11. buf []interface{}
  12. head, tail, count int
  13. }
  14. // New constructs and returns a new Queue.
  15. func New() *Queue {
  16. return &Queue{
  17. buf: make([]interface{}, minQueueLen),
  18. }
  19. }
  20. // Length returns the number of elements currently stored in the queue.
  21. func (q *Queue) Length() int {
  22. return q.count
  23. }
  24. func (q *Queue) resize() {
  25. newBuf := make([]interface{}, q.count*2)
  26. if q.tail > q.head {
  27. copy(newBuf, q.buf[q.head:q.tail])
  28. } else {
  29. copy(newBuf, q.buf[q.head:len(q.buf)])
  30. copy(newBuf[len(q.buf)-q.head:], q.buf[:q.tail])
  31. }
  32. q.head = 0
  33. q.tail = q.count
  34. q.buf = newBuf
  35. }
  36. // Add puts an element on the end of the queue.
  37. func (q *Queue) Add(elem interface{}) {
  38. if q.count == len(q.buf) {
  39. q.resize()
  40. }
  41. q.buf[q.tail] = elem
  42. q.tail = (q.tail + 1) % len(q.buf)
  43. q.count++
  44. }
  45. // Peek returns the element at the head of the queue. This call panics
  46. // if the queue is empty.
  47. func (q *Queue) Peek() interface{} {
  48. if q.count <= 0 {
  49. panic("queue: Peek() called on empty queue")
  50. }
  51. return q.buf[q.head]
  52. }
  53. // Get returns the element at index i in the queue. If the index is
  54. // invalid, the call will panic.
  55. func (q *Queue) Get(i int) interface{} {
  56. if i >= q.count || i < 0 {
  57. panic("queue: Get() called with index out of range")
  58. }
  59. return q.buf[(q.head+i)%len(q.buf)]
  60. }
  61. // Remove removes the element from the front of the queue. If you actually
  62. // want the element, call Peek first. This call panics if the queue is empty.
  63. func (q *Queue) Remove() {
  64. if q.count <= 0 {
  65. panic("queue: Remove() called on empty queue")
  66. }
  67. q.buf[q.head] = nil
  68. q.head = (q.head + 1) % len(q.buf)
  69. q.count--
  70. if len(q.buf) > minQueueLen && q.count*4 <= len(q.buf) {
  71. q.resize()
  72. }
  73. }