@@ -7,6 +7,8 @@ The queue implemented here is as fast as it is for an additional reason: it is *
7
7
*/
8
8
package queue
9
9
10
+ // minQueueLen is smallest capacity that queue may have.
11
+ // Must be power of 2 for bitwise modulus: x % n == x & (n - 1).
10
12
const minQueueLen = 16
11
13
12
14
// Queue represents a single instance of the queue data structure.
@@ -30,7 +32,7 @@ func (q *Queue) Length() int {
30
32
// resizes the queue to fit exactly twice its current contents
31
33
// this can result in shrinking if the queue is less than half-full
32
34
func (q * Queue ) resize () {
33
- newBuf := make ([]interface {}, q .count * 2 )
35
+ newBuf := make ([]interface {}, q .count << 1 )
34
36
35
37
if q .tail > q .head {
36
38
copy (newBuf , q .buf [q .head :q .tail ])
@@ -51,7 +53,8 @@ func (q *Queue) Add(elem interface{}) {
51
53
}
52
54
53
55
q .buf [q .tail ] = elem
54
- q .tail = (q .tail + 1 ) % len (q .buf )
56
+ // bitwise modulus
57
+ q .tail = (q .tail + 1 ) & (len (q .buf ) - 1 )
55
58
q .count ++
56
59
}
57
60
@@ -76,7 +79,8 @@ func (q *Queue) Get(i int) interface{} {
76
79
if i < 0 || i >= q .count {
77
80
panic ("queue: Get() called with index out of range" )
78
81
}
79
- return q .buf [(q .head + i )% len (q .buf )]
82
+ // bitwise modulus
83
+ return q .buf [(q .head + i )& (len (q .buf )- 1 )]
80
84
}
81
85
82
86
// Remove removes the element from the front of the queue. If you actually
@@ -86,9 +90,11 @@ func (q *Queue) Remove() {
86
90
panic ("queue: Remove() called on empty queue" )
87
91
}
88
92
q .buf [q .head ] = nil
89
- q .head = (q .head + 1 ) % len (q .buf )
93
+ // bitwise modulus
94
+ q .head = (q .head + 1 ) & (len (q .buf ) - 1 )
90
95
q .count --
91
- 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 ) {
92
98
q .resize ()
93
99
}
94
100
}
0 commit comments