blob: 1d87fe61ba9d91cefa422085335f322a47b8aa00 [file] [log] [blame]
Wyatt Heplerf9fb90f2020-09-30 18:59:33 -07001.. _module-pw_varint:
Wyatt Hepler3c4e5de2020-03-03 14:37:52 -08002
3---------
4pw_varint
5---------
Armando Montanez0054a9b2020-03-13 13:06:24 -07006The ``pw_varint`` module provides functions for encoding and decoding variable
Wyatt Hepler3c4e5de2020-03-03 14:37:52 -08007length integers, or varints. For smaller values, varints require less memory
8than a fixed-size encoding. For example, a 32-bit (4-byte) integer requires 1--5
9bytes when varint-encoded.
10
11`Protocol Buffers <https://developers.google.com/protocol-buffers/docs/encoding#varints>`_
12use a variable-length encoding for integers.
13
14Compatibility
15=============
16* C
Wyatt Hepler0132da52021-10-11 16:20:11 -070017* C++14 (with :doc:`../pw_polyfill/docs`)
Wyatt Hepler3c4e5de2020-03-03 14:37:52 -080018
Alexei Frolov388d4b92020-05-20 13:30:07 -070019API
20===
21
22.. cpp:function:: size_t EncodedSize(uint64_t integer)
23
24Returns the size of an integer when encoded as a varint. Works on both signed
25and unsigned integers.
26
27.. cpp:function:: size_t ZigZagEncodedSize(int64_t integer)
28
29Returns the size of a signed integer when ZigZag encoded as a varint.
30
Alexei Frolov6fe8ccf2021-03-30 13:19:40 -070031.. cpp:function:: uint64_t MaxValueInBytes(size_t bytes)
32
33Returns the maximum integer value that can be encoded as a varint into the
34specified number of bytes.
35
Scott James Remnanta19e2852021-12-14 17:53:04 -080036
37Stream API
38----------
39
40.. cpp:function:: StatusWithSize Read(stream::Reader& reader, int64_t* output)
41.. cpp:function:: StatusWithSize Read(stream::Reader& reader, uint64_t* output)
42
43Decoders a varint from the current position of a stream. If reading into a
44signed integer, the value is ZigZag decoded.
45
46Returns the number of bytes read from the stream, places the value in `output`,
47if successful. Returns `OutOfRange` if the varint does not fit in to the type,
48or if the input is exhausted before the number terminates.
49
50Reads a maximum of 10 bytes.
51
Wyatt Hepler3c4e5de2020-03-03 14:37:52 -080052Dependencies
53============
Armando Montanez0054a9b2020-03-13 13:06:24 -070054* ``pw_span``
Yuval Peressb8f3ad22021-10-26 22:55:27 -060055
56Zephyr
57======
58To enable ``pw_varint`` for Zephyr add ``CONFIG_PIGWEED_VARINT=y`` to the
59project's configuration.