forked from djherbis/buffer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ring.go
58 lines (49 loc) · 1.2 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
package buffer
import (
"io"
"math"
"github.com/djherbis/buffer/wrapio"
)
type ring struct {
BufferAt
L int64
*wrapio.WrapReader
*wrapio.WrapWriter
}
// NewRing returns a Ring Buffer from a BufferAt.
// It overwrites old data in the Buffer when needed (when its full).
func NewRing(buffer BufferAt) Buffer {
return &ring{
BufferAt: buffer,
WrapReader: wrapio.NewWrapReader(buffer, 0, buffer.Cap()),
WrapWriter: wrapio.NewWrapWriter(buffer, 0, buffer.Cap()),
}
}
func (buf *ring) Len() int64 {
return buf.L
}
func (buf *ring) Cap() int64 {
return math.MaxInt64
}
func (buf *ring) Read(p []byte) (n int, err error) {
if buf.L == buf.BufferAt.Cap() {
buf.WrapReader.Seek(buf.WrapWriter.Offset(), 0)
}
n, err = io.LimitReader(buf.WrapReader, buf.L).Read(p)
buf.L -= int64(n)
return n, err
}
func (buf *ring) Write(p []byte) (n int, err error) {
n, err = buf.WrapWriter.Write(p)
buf.L += int64(n)
if buf.L > buf.BufferAt.Cap() {
buf.L = buf.BufferAt.Cap()
}
return n, err
}
func (buf *ring) Reset() {
buf.BufferAt.Reset()
buf.L = 0
buf.WrapReader = wrapio.NewWrapReader(buf.BufferAt, 0, buf.BufferAt.Cap())
buf.WrapWriter = wrapio.NewWrapWriter(buf.BufferAt, 0, buf.BufferAt.Cap())
}