-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathringbuffer.go
More file actions
64 lines (50 loc) · 1.05 KB
/
ringbuffer.go
File metadata and controls
64 lines (50 loc) · 1.05 KB
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
package ringbuffer
import (
"fmt"
)
type StringBuffer interface {
Append(string)
Slice() []string
Length() int
}
type stringBuffer struct {
capacity int
position int
buffer []string
}
func NewStringBuffer(capacity int) StringBuffer {
if capacity < 1 {
panic(fmt.Sprintf("capacity must be >= 1 but was %v", capacity))
}
return &stringBuffer{capacity: capacity}
}
func (b *stringBuffer) Append(value string) {
if len(b.buffer) < b.capacity {
b.buffer = append(b.buffer, value)
} else {
b.buffer[b.position] = value
}
b.position = (b.position + 1) % b.capacity
}
func (b *stringBuffer) Slice() []string {
if len(b.buffer) == 0 {
return []string{}
}
if len(b.buffer) < b.capacity {
return b.buffer[0:len(b.buffer)]
}
buffer := make([]string, b.capacity, b.capacity)
position := 0
for i := b.position; i < b.capacity; i++ {
buffer[position] = b.buffer[i]
position++
}
for i := 0; i < b.position; i++ {
buffer[position] = b.buffer[i]
position++
}
return buffer
}
func (b *stringBuffer) Length() int {
return len(b.buffer)
}