-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple.go
92 lines (81 loc) · 1.66 KB
/
simple.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
package ringbuffer
import (
"sync"
)
var _ RingBuffer[int] = (*SimpleRingBuffer[int])(nil)
type SimpleRingBuffer[T any] struct {
data []T
size int
curSize int
frontIndex int
backIndex int
mutex sync.RWMutex
}
func NewSimpleRingBuffer[T any](size int) *SimpleRingBuffer[T] {
return &SimpleRingBuffer[T]{
data: make([]T, size),
size: size,
curSize: 0,
frontIndex: 0,
backIndex: 0,
mutex: sync.RWMutex{},
}
}
func (r *SimpleRingBuffer[T]) Push(value T) T {
r.mutex.Lock()
defer r.mutex.Unlock()
// assign nil to oldValue
var oldValue T
if r.curSize == r.size {
oldValue = r.popNoLock()
}
r.data[r.backIndex] = value
r.backIndex = (r.backIndex + 1) % r.size
r.curSize++
return oldValue
}
func (r *SimpleRingBuffer[T]) popNoLock() T {
var value T
if r.curSize == 0 {
return value
}
value = r.data[r.frontIndex]
r.frontIndex = (r.frontIndex + 1) % r.size
r.curSize--
return value
}
func (r *SimpleRingBuffer[T]) Pop() T {
r.mutex.Lock()
defer r.mutex.Unlock()
return r.popNoLock()
}
func (r *SimpleRingBuffer[T]) Front() T {
r.mutex.RLock()
defer r.mutex.RUnlock()
if r.curSize == 0 {
var value T
return value
}
return r.data[r.frontIndex]
}
func (r *SimpleRingBuffer[T]) Back() T {
r.mutex.RLock()
defer r.mutex.RUnlock()
if r.curSize == 0 {
var value T
return value
}
return r.data[(r.backIndex-1+r.size)%r.size]
}
func (r *SimpleRingBuffer[T]) Size() int {
r.mutex.RLock()
defer r.mutex.RUnlock()
return r.curSize
}
func (r *SimpleRingBuffer[T]) Iterate(f func(T)) {
r.mutex.RLock()
defer r.mutex.RUnlock()
for i := 0; i < r.curSize; i++ {
f(r.data[(r.frontIndex+i)%r.size])
}
}