XB Library: xb::parser::vsn

The VSN stands for Variable-Size Number that allows to encode numeric value of any size to only neccessary number of bytes. See XB format specification for more details.


namespace xb {
namespace parser {
namespace vsn {

    void encode (xb::size_type vsn, xb::alias & output) throw ();
    xb::size_type decode (xb::const_alias & input, xb::size_type * m = 0) throw ();
    void skip (xb::const_alias & input, xb::size_type & length) throw ();

    xb::size_type length (xb::size_type) throw ();



This function encodes numeric value of the first parameter into the output as a VSN. The second parameter (output) is a reference to an object that implements the xb::alias interface. Upon exiting, the alias points to first byte after the encoded number.


This function parses as much data from the input (first parameter) as needed (but not more than available) to construct a valid numeric value from a VSN. The parsed number is returned. The input is a reference to an object that implements the xb::const_alias interface. This alias is updated to point to first byte after the VSN.

If the m pointer is used (not null), the variable it points to is incremented of number of bytes parsed by this function.


The skip function updates its arguments the way as decode would but much faster. The function simply increments the input alias until it skips the whole VSN.


This function returns number of bytes required to encode the VSN passed as the first parameter.


// ...

xb::size_type number = X;
xb::size_type buffer_size = N;
unsigned char buffer [N];

// ...

if (xb::parser::vsn::length (number) <= buffer_size) {
    xb::buffer_alias output (buffer, buffer_size);
    xb::parser::vsn::encode (number, output);

} else {
    // not enough space in buffer

// ...


When speaking of binary data it is difficult to specify the width of numeric value that describes its length. For example we could specify 32-bit value, which means the data could be of 0 .. 4294967295 bytes. But we could easily find this size not to be enought, so we could specify the size to be 64-bit. Then we would find 64-bits to be excessive overhead when we store only few bytes of data.

So we introduce VSNs. Variable-Size Number is key element of XB. This allows us to store small values into few bytes and still be able to encode larger values using more bytes.

VSN encoding is based on technique where we reserve the most significant bit of each byte for an continue-flag. While the flag is set, next byte contain another, more significant, bits of the number.

Example of VSNs:

     0: 00000000
   109: 01101101
   129: 10000001 00000001
  9999: 10001111 01001110
123456: 11000000 11000100 00000111