-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcircular_buffer.go
52 lines (44 loc) · 1.04 KB
/
circular_buffer.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
package main
import (
"log"
"sync"
)
type circularBuffer struct {
mux sync.Mutex
buf []latencyDataPoint
count int
currentOffset int
}
func newCircularBuffer(size int) *circularBuffer {
return &circularBuffer{
buf: make([]latencyDataPoint, size, size),
}
}
func (b *circularBuffer) snapshot() []latencyDataPoint {
snap := make([]latencyDataPoint, len(b.buf))
b.mux.Lock()
n := copy(snap[0:b.count-b.currentOffset], b.buf[b.count-(b.count-b.currentOffset):])
if n != (b.count - b.currentOffset) {
log.Fatalf("unexpected short copy: %d bytes", n)
}
n = copy(snap[n:], b.buf[0:b.currentOffset])
if n != b.currentOffset {
log.Fatalf("unexpected short copy: %d bytes", n)
}
b.mux.Unlock()
return snap
}
func (b *circularBuffer) insert(value latencyDataPoint) {
b.mux.Lock()
b.buf[b.currentOffset] = value
if b.count < len(b.buf) {
b.count++
}
b.currentOffset = (b.currentOffset + 1) % len(b.buf)
b.mux.Unlock()
}
func (b *circularBuffer) size() int {
b.mux.Lock()
defer b.mux.Unlock()
return len(b.buf)
}