Codebase list golang-gopkg-eapache-queue.v1 / f0262ae
Merge pull request #11 from gammazero/bitmath Bitwise math for speed Evan Huus authored 7 years ago GitHub committed 7 years ago
1 changed file(s) with 11 addition(s) and 5 deletion(s). Raw diff Collapse all Expand all
66 */
77 package queue
88
9 // minQueueLen is smallest capacity that queue may have.
10 // Must be power of 2 for bitwise modulus: x % n == x & (n - 1).
911 const minQueueLen = 16
1012
1113 // Queue represents a single instance of the queue data structure.
2931 // resizes the queue to fit exactly twice its current contents
3032 // this can result in shrinking if the queue is less than half-full
3133 func (q *Queue) resize() {
32 newBuf := make([]interface{}, q.count*2)
34 newBuf := make([]interface{}, q.count<<1)
3335
3436 if q.tail > q.head {
3537 copy(newBuf, q.buf[q.head:q.tail])
5052 }
5153
5254 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)
5457 q.count++
5558 }
5659
7578 if i < 0 || i >= q.count {
7679 panic("queue: Get() called with index out of range")
7780 }
78 return q.buf[(q.head+i)%len(q.buf)]
81 // bitwise modulus
82 return q.buf[(q.head+i)&(len(q.buf)-1)]
7983 }
8084
8185 // Remove removes the element from the front of the queue. If you actually
8589 panic("queue: Remove() called on empty queue")
8690 }
8791 q.buf[q.head] = nil
88 q.head = (q.head + 1) % len(q.buf)
92 // bitwise modulus
93 q.head = (q.head + 1) & (len(q.buf) - 1)
8994 q.count--
90 if len(q.buf) > minQueueLen && q.count*4 == len(q.buf) {
95 // Resize down if buffer 1/4 full.
96 if len(q.buf) > minQueueLen && (q.count<<2) == len(q.buf) {
9197 q.resize()
9298 }
9399 }