forked from gerty-monit/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcircular_buffer.go
45 lines (36 loc) · 961 Bytes
/
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
package gerty
import "time"
type ValueWithTimestamp struct {
Value Result
Timestamp int64
}
type CircularBuffer struct {
values []ValueWithTimestamp
next int
capacity int
}
func NewCircularBuffer(capacity int) CircularBuffer {
sl := make([]ValueWithTimestamp, 0, capacity)
return CircularBuffer{sl, 0, capacity}
}
func (buf *CircularBuffer) Append(val Result) {
// hit the last value, start from zero.
if buf.next == cap(buf.values) {
buf.next = 0
}
// extend length if necesary.
if buf.next == len(buf.values) {
extended := make([]ValueWithTimestamp, len(buf.values)+1, buf.capacity)
for i := range buf.values {
extended[i] = buf.values[i]
}
buf.values = extended
}
buf.values[buf.next] = ValueWithTimestamp{val, time.Now().Unix()}
buf.next++
}
func (buf *CircularBuffer) GetValues() []ValueWithTimestamp {
ret := make([]ValueWithTimestamp, len(buf.values), cap(buf.values))
copy(ret, buf.values)
return ret
}