-
Notifications
You must be signed in to change notification settings - Fork 22
/
queue.go
94 lines (74 loc) · 2.06 KB
/
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
package queue
import "sync"
// Queue represents a ring buffer.
type Queue[T any] struct {
ringBuffer []T
read int
write int
capacity int
size int
mutex sync.Mutex
}
// New creates a new queue with the specified capacity.
func New[T any](capacity int) *Queue[T] {
return &Queue[T]{
ringBuffer: make([]T, capacity),
capacity: capacity,
}
}
// Size returns the size of the queue.
func (queue *Queue[T]) Size() int {
queue.mutex.Lock()
defer queue.mutex.Unlock()
return queue.size
}
// Capacity returns the capacity of the queue.
func (queue *Queue[T]) Capacity() int {
queue.mutex.Lock()
defer queue.mutex.Unlock()
return queue.capacity
}
func (queue *Queue[T]) ForceOffer(element T) (removedElement T, wasRemoved bool) {
queue.mutex.Lock()
defer queue.mutex.Unlock()
if queue.size == queue.capacity {
removedElement, wasRemoved = queue.poll()
}
queue.ringBuffer[queue.write] = element
queue.write = (queue.write + 1) % queue.capacity
queue.size++
return removedElement, wasRemoved
}
// Offer adds an element to the queue and returns true.
// If the queue is full, it drops it and returns false.
func (queue *Queue[T]) Offer(element T) bool {
queue.mutex.Lock()
defer queue.mutex.Unlock()
if queue.size == queue.capacity {
return false
}
queue.ringBuffer[queue.write] = element
queue.write = (queue.write + 1) % queue.capacity
queue.size++
return true
}
// Poll returns and removes the oldest element in the queue and true if successful.
// If returns false if the queue is empty.
func (queue *Queue[T]) Poll() (element T, success bool) {
queue.mutex.Lock()
defer queue.mutex.Unlock()
return queue.poll()
}
// poll returns and removes the oldest element in the queue and true if successful.
// If returns false if the queue is empty.
func (queue *Queue[T]) poll() (element T, success bool) {
if success = queue.size != 0; !success {
return
}
element = queue.ringBuffer[queue.read]
var emptyElement T
queue.ringBuffer[queue.read] = emptyElement
queue.read = (queue.read + 1) % queue.capacity
queue.size--
return
}