Files
redapricot/client/wire/varint.go
T
2026-07-15 14:28:58 +08:00

52 lines
950 B
Go

package wire
import (
"errors"
"io"
)
// VarIntMaxBytes is the maximum encoded length of a Minecraft VarInt.
const VarIntMaxBytes = 5
var errVarIntTooBig = errors.New("wire: VarInt exceeds 5 bytes")
// ReadVarInt reads a Minecraft-style VarInt from a byte reader.
func ReadVarInt(r io.ByteReader) (int, error) {
var value, shift int
for {
b, err := r.ReadByte()
if err != nil {
return 0, err
}
value |= int(b&0x7F) << shift
if b&0x80 == 0 {
return value, nil
}
shift += 7
if shift >= 32 {
return 0, errVarIntTooBig
}
}
}
// AppendVarInt appends v encoded as a VarInt to dst.
func AppendVarInt(dst []byte, v int) []byte {
u := uint32(v)
for u&^uint32(0x7F) != 0 {
dst = append(dst, byte(u&0x7F)|0x80)
u >>= 7
}
return append(dst, byte(u))
}
// VarIntSize returns the encoded byte length of v.
func VarIntSize(v int) int {
n := 1
u := uint32(v)
for u&^uint32(0x7F) != 0 {
u >>= 7
n++
}
return n
}