Class VarIntTool

java.lang.Object
io.datarouter.bytes.varint.VarIntTool

public class VarIntTool extends Object
Encodes a positive long value to a variable number of bytes. The leftmost bit (the sign bit) of each byte indicates if there are more values. A "1" bit (negative java byte value) indicates there is at least one more value byte. The leftmost byte is the least significant byte, each of which is negative until the last byte which is positive. Note the bitwise ordering of the byte arrays does not match Integer/Long ordering. Each byte contains 1 metadata/continuation bit and 7 data bits: - Values 0 to 127 are encoded in 1 byte. - Values 128 to 16_383 are encoded in 2 bytes. - Values 16_384 to 2_097_151 are encoded in 3 bytes. - Values 2_097_152 to 268_435_455 are encoded in 4 bytes. - Etc. - Long.MAX_VALUE is encoded in 9 bytes. The primary use case is for encoding many values that usually fit in 1 or sometimes 2 bytes. This can save 75% of space versus encoding ints to 4 bytes while still allowing big values. Calling length(value) calculates the encoded length quickly, faster than encoding the value to obtain the length. Encoding can be written to an OutputStream without heap allocations. Decoding can be read from an InputStream without heap allocations.