Debian Codegraph @

proto/buffer/circular.go

raw
1 package buffer
2
3 import (
4 "errors"
5 "io"
6 )
7
8 var (
9 FullError = errors.New("Buffer is full")
10 )
11
12 // Reads as much data
13 func readInto(rd io.Reader, p []byte) (n int, err error) {
14 var nr int
15 for n < len(p) {
16 nr, err = rd.Read(p[n:])
17 n += nr
18 if err != nil {
19 return
20 }
21 }
22 return
23 }
24
25 // A circular buffer on top of a byte-array
26 // NOTE: It does not implement the Write() method, it implements ReadFrom()
27 // to avoid copies
28 type Circular struct {
29 buf []byte // the bytes
30 size int // == len(buf)
31 head int // index of the next byte to read
32 tail int // index of the last byte available to read
33 }
34
35 // Returns a new circular buffer of the given size
36 func NewCircular(size int) *Circular {
37 return &Circular{
38 buf: make([]byte, size+1),
39 size: size + 1,
40 }
41 }
42
43 // Copy data from the given reader into the buffer
44 // Any errors encountered while reading are returned EXCEPT io.EOF.
45 // If the reader fills the buffer, it returns buffer.FullError
46 func (c *Circular) ReadFrom(rd io.Reader) (n int, err error) {
47 // IF:
48 // [---H+++T--]
49 if c.tail >= c.head {
50 n, err = readInto(rd, c.buf[c.tail:])
51 c.tail = (c.tail + n) % c.size
52 if err == io.EOF {
53 return n, nil
54 } else if err != nil {
55 return
56 }
57 }
58
59 // NOW:
60 // [T---H++++] or [++T--H+++]
61 n2, err := readInto(rd, c.buf[c.tail:c.head])
62 n += n2
63 c.tail += n2
64 if err == nil {
65 err = FullError
66 } else if err == io.EOF {
67 err = nil
68 }
69 return
70 }
71
72 // Read data out of the buffer. This never fails but may
73 // return n==0 if there is no data to be read
74 func (c *Circular) Read(p []byte) (n int, err error) {
75 if c.head > c.tail {
76 n = copy(p, c.buf[c.head:])
77 c.head = (c.head + n) % c.size
78 if c.head != 0 {
79 return
80 }
81 }
82
83 n2 := copy(p[n:], c.buf[c.head:c.tail])
84 n += n2
85 c.head += n2
86 return
87 }