-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoded.go
68 lines (63 loc) · 1.36 KB
/
encoded.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
package abc
import (
"encoding/binary"
"io"
)
// Support for encoded U30, U32, S32 values.
func readU30(r io.Reader) (uint32, error) {
value, err := readU32(r)
if err != nil {
return 0, err
}
if value >= 0x40000000 {
return 0, ErrBadEncoded
}
return value, nil
}
func readU32(r io.Reader) (uint32, error) {
var result uint32
var buffer uint8
for i := uint(0); i < 4; i++ {
if err := binary.Read(r, binary.LittleEndian, &buffer); err != nil {
return 0, err
}
result += uint32(buffer&0x7f) << (7 * i)
if (buffer & 0x80) == 0 {
return result, nil
}
}
if err := binary.Read(r, binary.LittleEndian, &buffer); err != nil {
return 0, err
}
if (buffer & 0xf0) != 0 {
return 0, ErrBadEncoded
}
return result + (uint32(buffer&0xf) << 28), nil
}
func readS32(r io.Reader) (int32, error) {
var result int32
var buffer uint8
for i := uint(0); i < 4; i++ {
if err := binary.Read(r, binary.LittleEndian, &buffer); err != nil {
return 0, err
}
result += int32(buffer&0x7f) << (7 * i)
if (buffer & 0x80) == 0 {
if (buffer & 0x40) == 1 {
result = -result
}
return result, nil
}
}
if err := binary.Read(r, binary.LittleEndian, &buffer); err != nil {
return 0, err
}
if (buffer & 0xf0) != 0 {
return 0, ErrBadEncoded
}
result += int32(buffer&0xf) << 28
if (buffer & 0x40) == 1 {
result = -result
}
return result, nil
}