-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathvarint.go
57 lines (49 loc) · 878 Bytes
/
varint.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
package midi
// EncodeVarint returns the varint encoding of x.
func EncodeVarint(x uint32) []byte {
if x>>7 == 0 {
return []byte{
byte(x),
}
}
if x>>14 == 0 {
return []byte{
byte(0x80 | x>>7),
byte(127 & x),
}
}
if x>>21 == 0 {
return []byte{
byte(0x80 | x>>14),
byte(0x80 | x>>7),
byte(127 & x),
}
}
return []byte{
byte(0x80 | x>>21),
byte(0x80 | x>>14),
byte(0x80 | x>>7),
byte(127 & x),
}
}
// DecodeVarint reads a varint-encoded integer from the slice.
// It returns the integer and the number of bytes consumed, or
// zero if there is not enough.
func DecodeVarint(buf []byte) (x uint32, n int) {
if len(buf) < 1 {
return 0, 0
}
if buf[0] <= 0x80 {
return uint32(buf[0]), 1
}
var b byte
for _, b = range buf {
x = x << 7
x |= uint32(b) & 0x7F
n++
if b&0x80 == 0 {
return x, n
}
}
return x, n
}