-
Notifications
You must be signed in to change notification settings - Fork 58
/
ringqueue.go
73 lines (57 loc) · 972 Bytes
/
ringqueue.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package netflow
import (
"errors"
"sync"
)
var (
ErrQueueFull = errors.New("queue is full")
)
type ringQueue struct {
sync.RWMutex
buf []interface{}
head, tail, count int
}
func newRingQueue(size int) *ringQueue {
return &ringQueue{
buf: make([]interface{}, size),
}
}
func (q *ringQueue) Length() int {
return q.count
}
func (q *ringQueue) Add(elem interface{}) error {
q.Lock()
defer q.Unlock()
if q.count == len(q.buf) {
return ErrQueueFull
}
q.count++
q.buf[q.tail] = elem
if q.tail+1 < len(q.buf) {
q.tail++
}
if len(q.buf) == q.count {
q.tail = 0
}
return nil
}
func (q *ringQueue) Peek() interface{} {
q.RLock()
defer q.RUnlock()
if q.count <= 0 {
return nil
}
return q.buf[q.head]
}
func (q *ringQueue) Remove() interface{} {
q.Lock()
defer q.Unlock()
if q.count <= 0 {
return nil
}
ret := q.buf[q.head]
q.buf[q.head] = nil
q.head = (q.head + 1) & (len(q.buf) - 1)
q.count--
return ret
}