Varlen Encoding

From Lazarus wiki
Revision as of 03:09, 23 March 2019 by CuriousKit (talk | contribs) (Added the rest of the encoding)

Varlen Encoding (short for "variable length") is a way of storing a QWord so that small values take as few bytes as possible.

Inspiration

The inspiration and design of Varlen encoding came from two sources:

Some data fields are statistically more likely to contain small values, such as those used for sequential indices and string lengths, but whose upper limit may be the size of a LongWord or a QWord. If many hundreds of these values are stored, space can be quickly wasted when most of the bytes that make up the full integer value are zero, and this can be problematic on media with limited capacity. The design of Varlen Encoding is an attempt to reduce this wastage with minimal performance impact.

Format

A Varlen-encoded integer (henceforth just called a Varlen) takes between 1 and 9 bytes to store. The first byte, known as a Lead Byte, encodes a byte count and the most significant bits of the number, stored in big-endian order. The bit pattern of the Lead Byte dictates the number of Data Bytes that follow:

Lead Byte Value Range Description
0####### $00..$7F No data bytes; #'s encode a 7-bit value between $00 to $7F (0 to 127)
10###### $0080..$407F 1 data byte follows; #'s encode a 14-bit value offset by $80 (add $80 to the value to obtain the actual integer)
110##### $004080..$20407F 2 data bytes follow; #'s encode a 21-bit value offset by $4080
1110#### $00204080..$1020407F 3 data bytes follow; #'s encode a 28-bit value offset by $204080
11110### $00 10204080..$08 1020407F 4 data bytes follow; #'s encode a 35-bit value offset by $10204080
111110## $0008 10204080..$0408 1020407F 5 data bytes follow; #'s encode a 42-bit value offset by $08 10204080
1111110# $000408 10204080..$020408 1020407F 6 data bytes follow; #'s encode a 49-bit value offset by $0408 10204080
11111110 $00020408 10204080..$01020408 1020407F 7 data bytes follow; #'s encode a 56-bit value offset by $020408 10204080
11111111 $01020408 10204080..$FFFFFFFF FFFFFFFF 8 data bytes follow; #'s encode a 64-bit value offset by $01020408 10204080