Available on crate feature
alloc only.Expand description
Simple and efficient encoding of variably-sized integers
This encoding is little-endian, appending the seven least-significant bits to a byte vector, until the remaining bits are zero. The eight bit is reserved to mark whether or not the encoding continues.
VARINT_VALUE_MASK = (1 << 7) - 1
fn encode_varint(value) {
if value == 0 {
return [0]
}
result = []
while value != 0 {
next_byte = value & VARINT_VALUE_MASK
value >>= 7
next_byte |= (value != 0) << 7
result.push(next_byte)
}
return result
}
fn decode_varint(bytestream) {
result = 0
i = 0
while true {
next_byte = bytestream.next_byte()
result |= (next_byte & VARINT_VALUE_MASK) << i
if (next_byte >> 7) == 0 {
# Check this was canonical, without unnecessary extra bytes
assert (i == 0) || (next_byte != 0)
return result
}
i += 7
}
}Implementations MUST ensure that (next_byte & mask) << i DOES NOT shift any set bits past
the boundary of the container. Implementations SHOULD terminate early if i exceeds the
bit-length of the container (as either a bit will overflow the container, or the final byte
will be zero and therefore the number is non-canonically encoded, either case being invalid).
Constantsยง
- VARINT_
VALUE_ ๐MASK
Functionsยง
- decode_
varint ๐ - This function runs in time variable to the input.
- encode_
varint ๐ - This function runs in time variable to the input.