-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrolling_buf.go
More file actions
60 lines (52 loc) · 1.07 KB
/
Copy pathrolling_buf.go
File metadata and controls
60 lines (52 loc) · 1.07 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
package main
import (
"io"
)
type rollingBuf struct {
arr [][]byte
numAppends int
}
func NewRollingBuf(capacity int) rollingBuf {
return rollingBuf{
arr: make([][]byte, 0 /* size */, capacity),
numAppends: 0,
}
}
func (ba *rollingBuf) Len() int {
if ba.numAppends < cap(ba.arr) {
return ba.numAppends
} else {
return cap(ba.arr)
}
}
func (ba *rollingBuf) AddBuff(buff []byte) {
overWrite := ba.numAppends >= cap(ba.arr)
if !overWrite {
ba.arr = append(ba.arr, buff)
} else {
writeIdx := ba.numAppends % cap(ba.arr)
ba.arr[writeIdx] = buff
}
ba.numAppends++
}
func (ba *rollingBuf) ForEachBuf(fn func([]byte)) {
startIdx := ba.numAppends % cap(ba.arr)
for ii := startIdx; ii < ba.Len(); ii++ {
fn(ba.arr[ii])
}
for ii := 0; ii < startIdx; ii++ {
fn(ba.arr[ii])
}
}
// Reader interface.
func (ba *rollingBuf) Read(buff []byte) (n int, err error) {
readBytes := 0
ba.ForEachBuf(func(b []byte) {
readBytes += copy(buff[readBytes:], b)
})
return readBytes, io.EOF
}
// Closer interface.
func (ba *rollingBuf) Close() error {
return nil
}