Skip to content

Commit 65a0cbf

Browse files
committed
Added codec: leb128
1 parent 4c22ff8 commit 65a0cbf

4 files changed

Lines changed: 88 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,7 @@ CACTCGGTCGGCCATATGTTCGGCCATATGTTCGTCTGTTCACTCGCCCATACACT
288288
- [X] `base32768`: [Base32768](https://github.com/qntm/base32768) custom conversion (15 bits per character, optimised for UTF-16)
289289
- [X] `base65536`: [Base65536](https://github.com/qntm/base65536) custom conversion (16 bits per character, optimised for UTF-32)
290290
- [X] `bech32`: [Bech32](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki) encoding with a human-readable part ; `bech32m` for its [Bech32m](https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki) variant
291+
- [X] `leb128` (or *varint*): [LEB128](https://en.wikipedia.org/wiki/LEB128) encoding of lists of integers ; `sleb128` for its signed variant
291292
- [X] `base-genericN`: see [base encodings](https://python-codext.readthedocs.io/en/latest/enc/base.html) ; supports any possible base
292293

293294
This category also contains `ascii85`, `adobe`, `[x]btoa`, `zeromq` with the `base85` codec.

‎docs/pages/enc/base.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,8 @@ This encoding implements various different versions of Base85.
165165
`base100` | text <-> Base100 encoded text | `base[-_]?100|emoji` | Python 3 only
166166
`base122` | text <-> Base122 encoded text | `base[-_]?122` | Python 3 only
167167
`base128` | text <-> Base128 encoded text | `base[-_]?128` | Relies on the ASCII charset
168+
`leb128` | integers <-> LEB128 (varint) bytes | `uleb128`, `varint` | unsigned integers, separated by whitespaces or commas
169+
`sleb128` | integers <-> signed LEB128 bytes | `leb128-signed` | signed integers (two's complement)
168170
`base1024` | data <-> Ecoji encoded text | `base[-_]?1024`, `ecoji`, `ecoji-v1`, `ecoji-v2` | 10 bits per emoji ; encodes with Ecoji version 2 by default
169171
`bech32` | data <-> Bech32 encoded text | `bech32-<hrp>` | human-readable part required for encoding
170172
`bech32m` | data <-> Bech32m encoded text | `bech32m-<hrp>` | human-readable part required for encoding
@@ -220,3 +222,14 @@ Bech32 ([BIP-173](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki
220222
>>> codext.encode("Hello, World!", "bech32m-test")
221223
'test1fpjkcmr09ss9wmmjd3jzzmkehgn'
222224
```
225+
226+
LEB128 (Little Endian Base 128), also known as varint, writes integers with 7 bits per byte, least significant group first, the most significant bit of each byte being set except for the last one. The signed variant (SLEB128) writes the integers in two's complement, its last byte being sign-extended. When encoding, the text holds the integers in decimal, separated by whitespaces or commas ; when decoding, the integers are separated by a space. Unlike `base128`, which converts the whole input as a single integer with the ASCII charset, these codecs work on lists of integers.
227+
228+
```python
229+
>>> codext.encode("624485 300", "leb128")
230+
'å\x8e&¬\x02'
231+
>>> codext.decode("å\x8e&¬\x02", "varint")
232+
'624485 300'
233+
>>> codext.encode("-123456", "sleb128")
234+
'À»x'
235+
```

‎src/codext/base/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from .bech32 import *
1313
from .base65536 import *
1414
from .baseN import *
15+
from .leb128 import *
1516
from ..__common__ import *
1617
from ..__info__ import __version__
1718

‎src/codext/base/leb128.py‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# -*- coding: UTF-8 -*-
2+
"""LEB128 Codec - leb128 (varint) content encoding.
3+
4+
LEB128 (Little Endian Base 128), also known as varint, writes integers with 7 bits per byte, least significant group
5+
first, the most significant bit of each byte being set except for the last one. The signed variant (SLEB128) writes
6+
the integers in two's complement, its last byte being sign-extended.
7+
8+
When encoding, the text holds the integers in decimal, separated by whitespaces or commas ; when decoding, the
9+
integers are separated by a space.
10+
11+
This codec:
12+
- en/decodes strings from str to str
13+
- en/decodes strings from bytes to bytes
14+
- decodes file content to str (read)
15+
- encodes file content from str to bytes (write)
16+
17+
Reference: https://en.wikipedia.org/wiki/LEB128
18+
"""
19+
from ..__common__ import *
20+
21+
22+
__examples1__ = {
23+
'enc(leb128|uleb128|varint|leb-128)': {'0': "\x00", '127': "\x7f", '128': "\x80\x01", '300': "\xac\x02",
24+
'624485': "\xe5\x8e\x26", '1 2, 3': "\x01\x02\x03", '-1': None, 'a': None},
25+
'dec(leb128)': {'\xe5\x8e\x26\xac\x02': "624485 300", '\x80\x00': "0", '\x80': None},
26+
'enc-dec(leb128)': ["", "0", "1 127 128 16383 16384 18446744073709551615"],
27+
}
28+
__examples2__ = {
29+
'enc(sleb128|leb128-signed|sleb-128)': {'0': "\x00", '-1': "\x7f", '63': "\x3f", '64': "\xc0\x00", '-64': "\x40",
30+
'-65': "\xbf\x7f", '-123456': "\xc0\xbb\x78", '1.5': None},
31+
'dec(sleb128)': {'\xc0\xbb\x78\x7f': "-123456 -1", '\xc0': None},
32+
'enc-dec(sleb128)': ["", "0", "-1 63 64 -64 -65 -123456 9223372036854775807"],
33+
}
34+
__guess1__ = __guess2__ = []
35+
36+
37+
def __leb128(signed=False, decode=False):
38+
ename = ["leb128", "sleb128"][signed]
39+
def _code(text, errors="strict"):
40+
_h, r = handle_error(ename, errors, decode=decode, kind="token" if not decode else "byte"), []
41+
if decode:
42+
v, k, start = 0, 0, 0
43+
for i, x in enumerate(b(text)):
44+
v, k, start = v | (x & 0x7f) << k, k + 7, start if k else i
45+
if x < 0x80:
46+
# the last byte holds the sign bit (0x40) for the signed variant
47+
r.append(str(v - (1 << k) if signed and x & 0x40 else v))
48+
v, k = 0, 0
49+
if k:
50+
# an incomplete integer (most significant bit set in its last byte) cannot be decoded
51+
r.append(_h(ensure_str(b(text)[start:]), start, " ".join(r)))
52+
return (s := " ".join(x for x in r if x != "")), len(s)
53+
for m in re.finditer(r"[^\s,]+", ensure_str(text)):
54+
t = m.group()
55+
if not re.match(r"^[-+]?\d+$", t) or not signed and int(t) < 0:
56+
r.append(_h(t, m.start()))
57+
else:
58+
v, out = int(t), []
59+
while True:
60+
x, v = v & 0x7f, v >> 7
61+
# with the signed variant, the encoding stops when the remaining bits are a sign extension
62+
if (v == 0 and not (signed and x & 0x40)) or (signed and v == -1 and x & 0x40):
63+
out.append(x)
64+
break
65+
out.append(x | 0x80)
66+
r.append("".join(map(chr, out)))
67+
return (s := "".join(r)), len(s)
68+
return _code
69+
70+
71+
for _n, _s, _p, _ex, _gs in [("leb128", False, r"^(?:u?leb[-_]?128|varint)$", __examples1__, __guess1__),
72+
("sleb128", True, r"^(?:sleb[-_]?128|leb[-_]?128[-_]signed)$", __examples2__, __guess2__)]:
73+
add(_n, __leb128(_s), __leb128(_s, True), _p, examples=_ex, guess=_gs)

0 commit comments

Comments
 (0)