queue.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 two additional reasons: it is *not* thread-safe, and it
  6. intentionally does not follow go best-practices regarding errors - if you make a mistake with this
  7. queue (such as trying to remove an element from an empty queue) then who knows what will happen.
  8. */
  9. package queue
  10. const minQueueLen = 16
  11. // Queue represents a single instance of the queue data structure.
  12. type Queue struct {
  13. buf []interface{}
  14. head, tail, count int
  15. }
  16. // New constructs and returns a new Queue.
  17. func New() *Queue {
  18. return &Queue{buf: make([]interface{}, minQueueLen)}
  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. If the queue is empty (Length == 0),
  46. // Peek does not panic, it simply returns garbage.
  47. func (q *Queue) Peek() interface{} {
  48. return q.buf[q.head]
  49. }
  50. // Remove removes the element from the front of the queue. If you actually want the element,
  51. // call Peek first. If the queue is empty (Length == 0), Remove will put the queue in a bad
  52. // state and all further operations will be undefined.
  53. func (q *Queue) Remove() {
  54. q.buf[q.head] = nil
  55. q.head = (q.head + 1) % len(q.buf)
  56. q.count--
  57. if len(q.buf) > minQueueLen && q.count*4 <= len(q.buf) {
  58. q.resize()
  59. }
  60. }