forked from perlin-network/noise
-
Notifications
You must be signed in to change notification settings - Fork 1
/
reader.go
79 lines (61 loc) · 1.42 KB
/
reader.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
package payload
import (
"bytes"
"encoding/binary"
"io"
"github.com/pkg/errors"
)
var _ io.Reader = (*Reader)(nil)
type Reader struct {
reader *bytes.Reader
}
func NewReader(payload []byte) Reader {
return Reader{
reader: bytes.NewReader(payload),
}
}
// Len returns the number of bytes that have not yet been read so far.
func (r Reader) Len() int {
return r.reader.Len()
}
func (r Reader) Read(b []byte) (n int, err error) {
return r.reader.Read(b)
}
func (r Reader) ReadBytes() ([]byte, error) {
raw, err := r.ReadUint32()
if err != nil {
return nil, err
}
size := int(raw)
if size < 0 || size > r.reader.Len() {
return nil, errors.New("bytes out of bounds")
}
buf := make([]byte, size)
_, err = r.Read(buf)
if err != nil && errors.Cause(err) != io.EOF {
return nil, err
}
return buf, nil
}
func (r Reader) ReadString() (string, error) {
bytes, err := r.ReadBytes()
return string(bytes), err
}
func (r Reader) ReadByte() (byte, error) {
return r.reader.ReadByte()
}
func (r Reader) ReadUint16() (uint16, error) {
var buf [2]byte
_, err := r.reader.Read(buf[:])
return binary.LittleEndian.Uint16(buf[:]), err
}
func (r Reader) ReadUint32() (uint32, error) {
var buf [4]byte
_, err := r.reader.Read(buf[:])
return binary.LittleEndian.Uint32(buf[:]), err
}
func (r Reader) ReadUint64() (uint64, error) {
var buf [8]byte
_, err := r.reader.Read(buf[:])
return binary.LittleEndian.Uint64(buf[:]), err
}