6 | 6 |
*/
|
7 | 7 |
package queue
|
8 | 8 |
|
|
9 |
// minQueueLen is smallest capacity that queue may have.
|
|
10 |
// Must be power of 2 for bitwise modulus: x % n == x & (n - 1).
|
9 | 11 |
const minQueueLen = 16
|
10 | 12 |
|
11 | 13 |
// Queue represents a single instance of the queue data structure.
|
|
29 | 31 |
// resizes the queue to fit exactly twice its current contents
|
30 | 32 |
// this can result in shrinking if the queue is less than half-full
|
31 | 33 |
func (q *Queue) resize() {
|
32 | |
newBuf := make([]interface{}, q.count*2)
|
|
34 |
newBuf := make([]interface{}, q.count<<1)
|
33 | 35 |
|
34 | 36 |
if q.tail > q.head {
|
35 | 37 |
copy(newBuf, q.buf[q.head:q.tail])
|
|
50 | 52 |
}
|
51 | 53 |
|
52 | 54 |
q.buf[q.tail] = elem
|
53 | |
q.tail = (q.tail + 1) % len(q.buf)
|
|
55 |
// bitwise modulus
|
|
56 |
q.tail = (q.tail + 1) & (len(q.buf) - 1)
|
54 | 57 |
q.count++
|
55 | 58 |
}
|
56 | 59 |
|
|
64 | 67 |
}
|
65 | 68 |
|
66 | 69 |
// Get returns the element at index i in the queue. If the index is
|
67 | |
// invalid, the call will panic.
|
|
70 |
// invalid, the call will panic. This method accepts both positive and
|
|
71 |
// negative index values. Index 0 refers to the first element, and
|
|
72 |
// index -1 refers to the last.
|
68 | 73 |
func (q *Queue) Get(i int) interface{} {
|
|
74 |
// If indexing backwards, convert to positive index.
|
|
75 |
if i < 0 {
|
|
76 |
i += q.count
|
|
77 |
}
|
69 | 78 |
if i < 0 || i >= q.count {
|
70 | 79 |
panic("queue: Get() called with index out of range")
|
71 | 80 |
}
|
72 | |
return q.buf[(q.head+i)%len(q.buf)]
|
|
81 |
// bitwise modulus
|
|
82 |
return q.buf[(q.head+i)&(len(q.buf)-1)]
|
73 | 83 |
}
|
74 | 84 |
|
75 | |
// Remove removes the element from the front of the queue. If you actually
|
76 | |
// want the element, call Peek first. This call panics if the queue is empty.
|
77 | |
func (q *Queue) Remove() {
|
|
85 |
// Remove removes and returns the element from the front of the queue. If the
|
|
86 |
// queue is empty, the call will panic.
|
|
87 |
func (q *Queue) Remove() interface{} {
|
78 | 88 |
if q.count <= 0 {
|
79 | 89 |
panic("queue: Remove() called on empty queue")
|
80 | 90 |
}
|
|
91 |
ret := q.buf[q.head]
|
81 | 92 |
q.buf[q.head] = nil
|
82 | |
q.head = (q.head + 1) % len(q.buf)
|
|
93 |
// bitwise modulus
|
|
94 |
q.head = (q.head + 1) & (len(q.buf) - 1)
|
83 | 95 |
q.count--
|
84 | |
if len(q.buf) > minQueueLen && q.count*4 == len(q.buf) {
|
|
96 |
// Resize down if buffer 1/4 full.
|
|
97 |
if len(q.buf) > minQueueLen && (q.count<<2) == len(q.buf) {
|
85 | 98 |
q.resize()
|
86 | 99 |
}
|
|
100 |
return ret
|
87 | 101 |
}
|