================================================= How-To (de-)serialize integers in variable length ================================================= When space is at a premium and values may be small, it is may make sense to encode integer values in variable length. For this, liberate implements both the signed and unsigned variant of `LEB128`_ encoding. But simply, it encodes in the first bit of a byte whether the value should be shifted, and the next byte's value added. This again takes the first bit into account, and so forth until the entire value is decoded. SLEB128 and ULEB128 (the signed and unsigned variants) produce slightly different encoded results, so it's vital that you use them consistently across serialization and deserialization. .. _LEB128: https://dwarfstd.org/DownloadDwarf5.php .. seealso:: :doc:`types-varint` :doc:`serialization-integer` Serialization ============= Serialization follows the same pattern as serialization of integers in fixed size, except you need to use a ``varint`` C++ type, and you need to specify where to use :cpp:func:`liberate::serialization::sleb128_serialize_varint` or :cpp:func:`liberate::serialization::uleb128_serialize_varint`. .. sourcecode:: cpp :linenos: :dedent: :caption: Serialize an integer in variable size #include #include using namespace liberate::serialization; using namespace liberate::types; char buf[1024]; varint val = 12345; auto used = sleb128_serialize_varint(buf, sizeof(buf), assert(used > 0); Deserialization =============== Deserialization also holds no surprises at this point. .. sourcecode:: cpp :linenos: :dedent: :caption: Deserialize an integer in variable size varint val = 0; auto used = sleb128_deserialize_varint(val, buf, sizeof(buf)); assert(used > 0);