-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoding.go
79 lines (65 loc) · 1.52 KB
/
encoding.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 negentropy
import (
"errors"
)
var ErrParseEndsPrematurely = errors.New("parse ends prematurely")
func getByte(encoded *[]byte) (byte, error) {
if len(*encoded) < 1 {
return 0, ErrParseEndsPrematurely
}
b := (*encoded)[0]
*encoded = (*encoded)[1:]
return b, nil
}
func getBytes(encoded *[]byte, n int) ([]byte, error) {
//fmt.Fprintln(os.Stderr, "getBytes", len(*encoded), n)
if len(*encoded) < n {
return nil, errors.New("parse ends prematurely")
}
result := (*encoded)[:n]
*encoded = (*encoded)[n:]
return result, nil
}
func decodeVarInt(encoded *[]byte) (int, error) {
//var res uint64
//
//for i := 0; i < len(*encoded); i++ {
// byte := (*encoded)[i]
// res = (res << 7) | uint64(byte&0x7F)
// if (byte & 0x80) == 0 {
// fmt.Fprintln(os.Stderr, "decodeVarInt", encoded, i)
// *encoded = (*encoded)[i+1:] // Advance the slice to reflect consumed bytes
// return res, nil
// }
//}
//return 0, ErrParseEndsPrematurely
res := 0
for {
if len(*encoded) == 0 {
return 0, errors.New("parse ends prematurely")
}
// Remove the first byte from the slice and update the slice.
// This simulates JavaScript's shift operation on arrays.
byte := (*encoded)[0]
*encoded = (*encoded)[1:]
res = (res << 7) | (int(byte) & 127)
if (byte & 128) == 0 {
break
}
}
return res, nil
}
func encodeVarInt(n int) []byte {
if n == 0 {
return []byte{0}
}
var o []byte
for n != 0 {
o = append([]byte{byte(n & 0x7F)}, o...)
n >>= 7
}
for i := 0; i < len(o)-1; i++ {
o[i] |= 0x80
}
return o
}