-
Notifications
You must be signed in to change notification settings - Fork 0
/
ring.go
55 lines (47 loc) · 1.08 KB
/
ring.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
package tchart
// RingBuffer ring buffer
type RingBuffer struct {
buffer []interface{}
length int
capacity int
tail int
}
// NewRingBuffer new ring buffer
func NewRingBuffer(capacity int) *RingBuffer {
return &RingBuffer{
buffer: make([]interface{}, capacity, capacity),
length: 0,
capacity: capacity,
tail: 0,
}
}
// Len length of ring buffer
func (r *RingBuffer) Len() int {
return r.length
}
// Capacity capacity of ring buffer
func (r *RingBuffer) Capacity() int {
return r.capacity
}
// Add add new element
func (r *RingBuffer) Add(v interface{}) {
if r.length < r.capacity {
r.length++
}
r.buffer[r.tail] = v
r.tail = (r.tail + 1) % r.capacity
}
// Slice return slice of ring buffer
func (r *RingBuffer) Slice(i, j int) []interface{} {
if r.length < r.capacity {
j = Min(j, r.length)
return r.buffer[i:j]
}
s := append(r.buffer[r.tail:r.capacity], r.buffer[:r.tail]...)
return s[i:j]
}
// Tail return last n elements of ring buffer
func (r *RingBuffer) Tail(n int) []interface{} {
start := Max(0, r.length-n)
return r.Slice(start, r.length)
}