-
Notifications
You must be signed in to change notification settings - Fork 0
/
ringbuffer.go
56 lines (47 loc) · 933 Bytes
/
ringbuffer.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
package main
import "sync"
type RingBuffer struct {
mu sync.RWMutex
buf []ServiceMap
size int
read int
write int
}
func NewBuffer(size int) *RingBuffer {
return &RingBuffer{
buf: make([]ServiceMap, size),
size: size,
}
}
func (b *RingBuffer) Len() int {
return b.write % b.size
}
func (b *RingBuffer) Size() int {
return b.size
}
func (b *RingBuffer) Write(s ServiceMap) {
b.mu.Lock()
b.buf[b.write] = s
b.write = (b.write + 1) % b.size
b.mu.Unlock()
}
func (b *RingBuffer) WriteAt(index int, s ServiceMap) {
b.mu.Lock()
b.buf[(index+b.size)%b.size] = s
b.write = (b.write + 1) % b.size
b.mu.Unlock()
}
func (b *RingBuffer) Read() ServiceMap {
b.mu.Lock()
s := b.buf[b.read]
b.read = (b.read + 1) % b.size
b.mu.Unlock()
return s
}
func (b *RingBuffer) ReadAt(index int) ServiceMap {
b.mu.Lock()
s := b.buf[(index+b.size)%b.size]
b.read = (b.read + 1) % b.size
b.mu.Unlock()
return s
}