-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
111 lines (98 loc) · 1.9 KB
/
utils.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
package opentimestamps
import (
"io"
"strings"
)
func normalizeUrl(u string) string {
if strings.HasSuffix(u, "/") {
u = u[0 : len(u)-1]
}
if !strings.HasPrefix(u, "https://") && !strings.HasPrefix(u, "http://") {
u = "http://" + u
}
return u
}
type Buffer struct {
pos *int
buf []byte
}
func newBuffer(buf []byte) Buffer {
zero := 0
return Buffer{&zero, buf}
}
func (buf Buffer) readBytes(n int) ([]byte, error) {
// fmt.Println("reading", n, "bytes")
if *buf.pos >= len(buf.buf) {
return nil, io.EOF
}
res := buf.buf[*buf.pos : *buf.pos+n]
*buf.pos = *buf.pos + n
// fmt.Println("->", hex.EncodeToString(res))
return res, nil
}
func (buf Buffer) readByte() (byte, error) {
b, err := buf.readBytes(1)
if err != nil {
return 0, err
}
return b[0], nil
}
func (buf Buffer) readVarUint() (uint64, error) {
var value uint64 = 0
var shift uint64 = 0
for {
b, err := buf.readByte()
if err != nil {
return 0, err
}
value |= (uint64(b) & 0b01111111) << shift
shift += 7
if b&0b10000000 == 0 {
break
}
}
return value, nil
}
func (buf Buffer) readVarBytes() ([]byte, error) {
v, err := buf.readVarUint()
if err != nil {
return nil, err
}
b, err := buf.readBytes(int(v))
if err != nil {
return nil, err
}
return b, nil
}
func appendVarUint(buf []byte, value uint64) []byte {
if value == 0 {
buf = append(buf, 0)
} else {
for value != 0 {
b := byte(value & 0b01111111)
if value > 0b01111111 {
b |= 0b10000000
}
buf = append(buf, b)
if value <= 0b01111111 {
break
}
value >>= 7
}
}
return buf
}
func appendVarBytes(buf []byte, value []byte) []byte {
buf = appendVarUint(buf, uint64(len(value)))
buf = append(buf, value...)
return buf
}
func getCommonPrefixIndex(s1 []Instruction, s2 []Instruction) int {
n := min(len(s1), len(s2))
for i := 0; i < n; i++ {
if CompareInstructions(s1[i], s2[i]) != 0 {
return i
}
}
return n
}