-
Notifications
You must be signed in to change notification settings - Fork 14
/
ring.go
103 lines (89 loc) · 1.85 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
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package datadash
type float64RingBuffer struct {
buffer []float64
length int
capacity int
tail int
}
func newFloat64RingBuffer(capacity int) *float64RingBuffer {
return &float64RingBuffer{
buffer: make([]float64, capacity, capacity),
length: 0,
capacity: capacity,
tail: 0,
}
}
func (r *float64RingBuffer) Len() int {
return r.length
}
func (r *float64RingBuffer) Capacity() int {
return r.capacity
}
func (r *float64RingBuffer) Add(v float64) {
if r.length < r.capacity {
r.length += 1
}
r.buffer[r.tail] = v
r.tail = (r.tail + 1) % r.capacity
}
func (r *float64RingBuffer) Slice(i, j int) []float64 {
if r.length < r.capacity {
if r.length < j {
j = r.length
}
return r.buffer[i:j]
}
s := append(r.buffer[r.tail:r.capacity], r.buffer[:r.tail]...)
return s[i:j]
}
func (r *float64RingBuffer) Last(n int) []float64 {
start := r.length - n
if start < 0 {
start = 0
}
return r.Slice(start, r.length)
}
type stringRingBuffer struct {
buffer []string
length int
capacity int
tail int
}
func newStringRingBuffer(capacity int) *stringRingBuffer {
return &stringRingBuffer{
buffer: make([]string, capacity, capacity),
length: 0,
capacity: capacity,
tail: 0,
}
}
func (r *stringRingBuffer) Len() int {
return r.length
}
func (r *stringRingBuffer) Capacity() int {
return r.capacity
}
func (r *stringRingBuffer) Add(v string) {
if r.length < r.capacity {
r.length += 1
}
r.buffer[r.tail] = v
r.tail = (r.tail + 1) % r.capacity
}
func (r *stringRingBuffer) Slice(i, j int) []string {
if r.length < r.capacity {
if r.length < j {
j = r.length
}
return r.buffer[i:j]
}
s := append(r.buffer[r.tail:r.capacity], r.buffer[:r.tail]...)
return s[i:j]
}
func (r *stringRingBuffer) Last(n int) []string {
start := r.length - n
if start < 0 {
start = 0
}
return r.Slice(start, r.length)
}