-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReader.go
129 lines (103 loc) · 2.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package binary
import (
"errors"
)
type Reader struct {
off int
n int
buf []byte
}
func (r *Reader) Buffer() ([]byte){
return r.buf
}
func (r *Reader) ReadByte() (num byte, err error) {
bb, err := r.Read(1)
if err != nil {
return
}
num = bb[0]
return
}
func (r *Reader) ReadSignedShort() (num int16, err error) {
n, err := r.ReadNumber(2)
num = int16(n)
return
}
func (r *Reader) ReadUnsignedShort() (num uint16, err error) {
n, err := r.ReadNumber(2)
num = uint16(n)
return
}
func (r *Reader) ReadSignedInt32() (num int32, err error) {
n, err := r.ReadNumber(4)
num = int32(n)
return
}
func (r *Reader) ReadUnsignedInt32() (num uint32, err error) {
n, err := r.ReadNumber(4)
num = uint32(n)
return
}
func (r *Reader) ReadSignedLong() (num int64, err error) {
num, err = r.ReadNumber(8)
return
}
func (r *Reader) ReadUnsignedLong() (num uint64, err error) {
n, err := r.ReadNumber(8)
num = uint64(n)
return
}
func (r *Reader) ReadByteArray() (n byte, ar []byte, err error) {
n, err = r.ReadByte() //todo make varint
if err != nil {
return
}
ar, err = r.Read(int(n))
if err != nil {
r.off-- // Потому что ReadByte(), что вызывается выше, инкрементит offset
}
return
}
var errNumberBytes = errors.New("number can have 1/2/4/8 bytes")
func (r *Reader) ReadNumber(n int) (num int64, err error) {
if n < 1 || n > 8 {
return 0, errNumberBytes
}
p, err := r.Read(n)
if err != nil {
return 0, err
}
// Костыль, чтобы внутри for'а не делать все время приведение типа у переменной n
unsignedN := uint(n) * 8
// Странный момент. Ввел дополнительный j, чтобы лишний раз i не делить на 8
i := uint(0)
j := i
for i < unsignedN {
num |= int64(p[j]) << i
i += 8
j++
}
return
}
var errBytesAmount = errors.New("amount of bytes must be positive")
var errNotEnoughBytes = errors.New("not enough bytes in buffer")
func (r *Reader) Read(n int) ([]byte, error) {
if n < 1 {
return nil, errBytesAmount
}
if r.n < (n + r.off) {
return nil, errNotEnoughBytes
}
r.off += n
return r.buf[r.off-n : r.off], nil
}
func (r *Reader) RemainingAmount() int { return r.n - r.off }
func (r *Reader) Remaining() []byte { return r.buf[r.off:] }
func (r *Reader) Size() int {
return r.n
}
func (r *Reader) init(buf []byte, n int) {
r.n = n
r.buf = buf
r.off = 0
}