Skip to content

varint

Varint encoding and decoding of integer values.

This module provides functions to encode non-negative integers -- or iterables of them -- using the variable-length varint representation, and to decode such buffers back into lists of integers.

Example
buf = []
varint.varint_encode(300, buf)
varint.varint_decode(buf)  # [300]

varint_encode(v, encbuf)

Append the varint encoding of a value to a buffer.

Integers are encoded using the 7-bit varint scheme; iterables are encoded element by element into the same buffer.

Parameters:

Name Type Description Default
v

Non-negative integer, numpy integer or iterable of integers to encode.

required
encbuf

List-like buffer to append encoded bytes to.

required
Example
buf = []
varint.varint_encode(300, buf)
buf  # [172, 2] - 300 = 0b100101100 -> 2 varint groups
Source code in py_misc_utils/varint.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
def varint_encode(v, encbuf):
  """Append the varint encoding of a value to a buffer.

  Integers are encoded using the 7-bit varint scheme; iterables are
  encoded element by element into the same buffer.

  Args:
    v: Non-negative integer, numpy integer or iterable of integers to
      encode.
    encbuf: List-like buffer to append encoded bytes to.

  Example:
    buf = []
    varint.varint_encode(300, buf)
    buf  # [172, 2] - 300 = 0b100101100 -> 2 varint groups
  """
  if isinstance(v, (int, np.integer)):
    tas.check_ge(v, 0, msg=f'Cannot encode negative values: {v}')

    # Unsigned numpy dtypes overflow when masked with the signed ~0x7f
    # pattern, so work on a plain Python integer throughout.
    cv = int(v)
    while (cv & ~0x7f) != 0:
      encbuf.append(0x80 | (cv & 0x7f))
      cv >>= 7

    encbuf.append(cv & 0x7f)
  elif hasattr(v, '__iter__'):
    for xv in v:
      varint_encode(xv, encbuf)
  else:
    alog.xraise(RuntimeError, f'Unsupported type: {v} ({type(v)})')

varint_decode(encbuf)

Decode all the varint values contained in a buffer.

Parameters:

Name Type Description Default
encbuf

Buffer holding the encoded bytes.

required

Returns:

Type Description

A list with all the values decoded from the buffer.

Raises:

Type Description
ValueError

If the buffer does not contain a valid varint stream.

Example
buf = []
varint.varint_encode(300, buf)
varint.varint_decode(buf)  # [300]
Source code in py_misc_utils/varint.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def varint_decode(encbuf):
  """Decode all the varint values contained in a buffer.

  Args:
    encbuf: Buffer holding the encoded bytes.

  Returns:
    A list with all the values decoded from the buffer.

  Raises:
    ValueError: If the buffer does not contain a valid varint stream.

  Example:
    buf = []
    varint.varint_encode(300, buf)
    varint.varint_decode(buf)  # [300]
  """
  values, cpos = [], 0
  try:
    while cpos < len(encbuf):
      value, cpos = _varint_decode(encbuf, cpos)
      values.append(value)
  except IndexError:
    # Handle out-of-range buffer access outside, to avoid checks within the inner loop.
    enc_data = ','.join(f'0x{x:02x}' for x in encbuf[cpos:cpos + 10])
    alog.xraise(
        ValueError,
        f'Invalid varint encoded buffer content at offset {cpos}: {enc_data} ...')

  return values