-
Notifications
You must be signed in to change notification settings - Fork 0
/
varints.go
66 lines (52 loc) · 1.13 KB
/
varints.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
package protocol
import (
"errors"
"io"
"math/bits"
)
// https://wiki.vg/VarInt_And_VarLong
const (
// VarIntMaxBytes is the maximum number of bytes required to represent a single VarInt.
VarIntMaxBytes = 5
segmentBits = 0x7F
continueBit = 0x80
)
var (
errVarIntTooBig = errors.New("VarInt too big")
)
// VarIntSize returns the number of bytes required to write the given value as a VarInt.
func VarIntSize(v int32) int {
return (31-bits.LeadingZeros32(uint32(v)))/7 + 1
}
// ReadVarInt reads a single VarInt from an io.ByteReader.
func ReadVarInt(r io.ByteReader) (int32, error) {
var v, pos int32
for {
b, err := r.ReadByte()
if err != nil {
return 0, err
}
v |= int32(b&segmentBits) << pos
if b&continueBit == 0 {
break
}
pos += 7
if pos >= 32 {
return 0, errVarIntTooBig
}
}
return v, nil
}
// WriteVarInt writes a single VarInt to io.ByteWriter.
func WriteVarInt(w io.ByteWriter, v int32) error {
for {
if v&(^segmentBits) == 0 {
return w.WriteByte(byte(v))
}
err := w.WriteByte(byte(v&segmentBits) | continueBit)
if err != nil {
return err
}
v = int32(uint32(v) >> 7)
}
}