-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathringbuffer.go
More file actions
84 lines (63 loc) · 1.54 KB
/
ringbuffer.go
File metadata and controls
84 lines (63 loc) · 1.54 KB
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
package atomicringbuffer
import (
"sync/atomic"
)
// RingBuffer
type RingBuffer[T any] struct {
capacity uint64
start, end atomic.Uint64
buffer []T
}
func NewRingBuffer[T any](capacity uint64) *RingBuffer[T] {
return &RingBuffer[T]{
capacity: capacity + 1,
buffer: make([]T, capacity+1),
}
}
func (r *RingBuffer[T]) IsFull() bool {
return r.incrementIndex(r.end.Load()) == r.start.Load()
}
func (r *RingBuffer[T]) IsEmpty() bool {
return r.start.Load() == r.end.Load()
}
func (r *RingBuffer[T]) Capacity() uint64 {
return r.capacity - 1
}
func (r *RingBuffer[T]) Size() uint64 {
return r.end.Load() - r.start.Load()
}
func (r *RingBuffer[T]) StartIndex() uint64 {
return r.start.Load()
}
// incrementIndex use modulus to calculate when the index should wrap to the beginning
// in a circular way
func (r *RingBuffer[T]) incrementIndex(index uint64) uint64 {
return (index + 1) % r.capacity
}
func (r *RingBuffer[T]) PushBack(value T) error {
currEnd := r.end.Load()
newEnd := r.incrementIndex(currEnd)
if newEnd == r.start.Load() {
return ErrIsFull
}
r.buffer[currEnd] = value
r.end.Store(newEnd)
return nil
}
func (r *RingBuffer[T]) PopFront() (T, error) {
currStart := r.start.Load()
if currStart == r.end.Load() {
return *new(T), ErrIsEmpty
}
value := r.buffer[currStart]
r.start.Store(r.incrementIndex(currStart))
return value, nil
}
func (r *RingBuffer[T]) PeekFront() (T, error) {
start := r.start.Load()
if start == r.end.Load() {
return *new(T), ErrIsEmpty
}
value := r.buffer[start]
return value, nil
}