-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbuffer.go
88 lines (75 loc) · 1.47 KB
/
buffer.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
package rely
import (
"io"
)
// buffer is a helper struct for serializing and deserializing as the caller
// does not need to externally manage where in the buffer they are currently reading or writing to.
type buffer struct {
buf []byte
pos int
}
func newBuffer(size int) *buffer {
b := &buffer{}
b.buf = make([]byte, size)
return b
}
func newBufferFromRef(buf []byte) *buffer {
b := &buffer{}
b.buf = buf
b.pos = 0
return b
}
func (b *buffer) bytes() []byte {
return b.buf[:b.pos]
}
func (b *buffer) reset() *buffer {
b.pos = 0
return b
}
func (b *buffer) getBytes(length int) ([]byte, error) {
bufferLength := len(b.buf)
bufferWindow := b.pos + length
if bufferLength < length {
return nil, io.EOF
}
if bufferWindow > bufferLength {
return nil, io.EOF
}
value := b.buf[b.pos:bufferWindow]
b.pos += length
return value, nil
}
func (b *buffer) getUint8() (uint8, error) {
buf, err := b.getBytes(sizeUint8)
if err != nil {
return 0, nil
}
return buf[0], nil
}
func (b *buffer) getUint16() (uint16, error) {
var n uint16
buf, err := b.getBytes(sizeUint16)
if err != nil {
return 0, nil
}
n |= uint16(buf[0])
n |= uint16(buf[1]) << 8
return n, nil
}
func (b *buffer) writeBytes(src []byte) {
b.pos += copy(b.buf[b.pos:], src)
}
func (b *buffer) writeUint8(n uint8) {
b.buf[b.pos] = n
b.pos++
}
func (b *buffer) writeUint16(n uint16) {
b.buf[b.pos] = byte(n)
b.pos++
b.buf[b.pos] = byte(n >> 8)
b.pos++
}
const (
sizeUint8 = 1
sizeUint16 = 2
)