-
Notifications
You must be signed in to change notification settings - Fork 0
/
ring_queue.go
102 lines (85 loc) · 1.49 KB
/
ring_queue.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package ringqueue
type RingQueue[T any] struct {
head, tail int
len int
buf []T
zero T
}
func New[T any](capacity int) *RingQueue[T] {
nodes := make([]T, capacity)
return &RingQueue[T]{
head: -1,
tail: -1,
buf: nodes,
}
}
func (q *RingQueue[T]) Length() int {
return q.len
}
func (q *RingQueue[T]) Capacity() int {
return len(q.buf)
}
func (q *RingQueue[T]) Front() (T, bool) {
if q.len == 0 {
return q.zero, false
}
return q.buf[q.head], true
}
func (q *RingQueue[T]) Tail() (T, bool) {
if q.len == 0 {
return q.zero, false
}
return q.buf[q.tail], true
}
func (q *RingQueue[T]) Enqueue(value T) bool {
if q.IsFull() || value == nil {
return false
}
q.tail++
if q.tail == len(q.buf) {
q.tail = 0
}
q.buf[q.tail] = value
q.len++
if q.len == 1 {
q.head = q.tail
}
return true
}
func (q *RingQueue[T]) Dequeue() (T, bool) {
if q.len == 0 {
return q.zero, false
}
result := q.buf[q.head]
q.buf[q.head] = q.zero
q.head++
q.len--
if q.head == len(q.buf) {
q.head = 0
}
return result, true
}
// IsFull checks if the ring buffer is full
func (q *RingQueue[T]) IsFull() bool {
return q.len == len(q.buf)
}
// LookAll reads all elements from ring buffer
// this method doesn't consume all elements
func (q *RingQueue[T]) LookAll() []T {
all := make([]T, q.len)
if q.len == 0 {
return all
}
j := 0
for i := q.head; ; i++ {
if i == len(q.buf) {
i = 0
}
all[j] = q.buf[i]
if i == q.tail {
break
}
j++
}
return all
}