@@ -7,6 +7,8 @@ The queue implemented here is as fast as it is for an additional reason: it is *
77*/
88package queue
99
10+ // minQueueLen is smallest capacity that queue may have.
11+ // Must be power of 2 for bitwise modulus: x % n == x & (n - 1).
1012const minQueueLen = 16
1113
1214// Queue represents a single instance of the queue data structure.
@@ -30,7 +32,7 @@ func (q *Queue) Length() int {
3032// resizes the queue to fit exactly twice its current contents
3133// this can result in shrinking if the queue is less than half-full
3234func (q * Queue ) resize () {
33- newBuf := make ([]interface {}, q .count * 2 )
35+ newBuf := make ([]interface {}, q .count << 1 )
3436
3537if q .tail > q .head {
3638copy (newBuf , q .buf [q .head :q .tail ])
@@ -51,7 +53,8 @@ func (q *Queue) Add(elem interface{}) {
5153}
5254
5355q .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 )
5558q .count ++
5659}
5760
@@ -76,7 +79,8 @@ func (q *Queue) Get(i int) interface{} {
7679if i < 0 || i >= q .count {
7780panic ("queue: Get() called with index out of range" )
7881}
79- return q .buf [(q .head + i )% len (q .buf )]
82+ // bitwise modulus
83+ return q .buf [(q .head + i )& (len (q .buf )- 1 )]
8084}
8185
8286// Remove removes the element from the front of the queue. If you actually
@@ -86,9 +90,11 @@ func (q *Queue) Remove() {
8690panic ("queue: Remove() called on empty queue" )
8791}
8892q .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 )
9095q .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 ) {
9298q .resize ()
9399}
94100}
0 commit comments