Skip to content

Commit 4c22ff8

Browse files
committed
Added codec: base38
1 parent 4ef0ca1 commit 4c22ff8

5 files changed

Lines changed: 75 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,7 @@ CACTCGGTCGGCCATATGTTCGGCCATATGTTCGTCTGTTCACTCGCCCATACACT
272272
- [X] `base26`: conversion to alphabet letters
273273
- [X] `base32`: classical conversion according to the RFC4648 with all its variants ([zbase32](https://philzimmermann.com/docs/human-oriented-base-32-encoding.txt), extended hexadecimal, [geohash](https://en.wikipedia.org/wiki/Geohash), [Crockford](https://www.crockford.com/base32))
274274
- [X] `base36`: [Base36](https://en.wikipedia.org/wiki/Base36) conversion to letters and digits (with a variant inverting both groups)
275+
- [X] `base38`: [Base38](https://github.com/project-chip/connectedhomeip/blob/master/src/setup_payload/Base38Encode.cpp) encoding of the Matter setup QR codes (chunks of 3 bytes)
275276
- [X] `base45`: [Base45](https://datatracker.ietf.org/doc/html/draft-faltstrom-base45-04.txt) DRAFT algorithm (with a variant inverting letters and digits)
276277
- [X] `base58`: multiple versions of [Base58](https://en.bitcoinwiki.org/wiki/Base58) (bitcoin, flickr, ripple)
277278
- [X] `base62`: [Base62](https://en.wikipedia.org/wiki/Base62) conversion to lower- and uppercase letters and digits (with a variant with letters and digits inverted)

‎docs/pages/enc/base.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ Note that for `base64`, it overwrites the native `base64_codec` to also support
6464
`base10` | text <-> Base10 encoded text | `base[-_]?10|int(?:eger)?|dec(?:imal)?` |
6565
`base11` | text <-> Base11 encoded text | `base[-_]?11(|[-_]inv(erted)?)` |
6666
`base36` | text <-> Base36 encoded text | `base[-_]?36(|[-_]inv(erted)?)` |
67+
`base38` | data <-> Base38 encoded text | `base[-_]?38` | Matter QR code payload encoding (chunks of 3 bytes)
6768
`base45` | text <-> Base45 encoded text | `base[-_]?45(|[-_]inv(erted)?)` |
6869
`base58` | text <-> Base58 encoded text | `base[-_]?58(|[-_](bc|bitcoin|rp|ripple|fl|flickr|short[-]?url|url))` | Supports Bitcoin, Ripple and short URL
6970
`base62` | text <-> Base62 encoded text | `base[-_]?62(|[-_]inv(erted)?)` |
@@ -83,6 +84,15 @@ Note that for `base64`, it overwrites the native `base64_codec` to also support
8384
'this is a test'
8485
```
8586

87+
Base38 is the encoding of the payloads of the [Matter](https://github.com/project-chip/connectedhomeip) setup QR codes. The data is taken by chunks of 3 bytes, each chunk being read as a little-endian integer and written with the least significant digit first in the alphabet "`0-9A-Z-.`" (5 characters for 3 bytes, 4 for 2 bytes and 2 for 1 byte). It differs from the generic base conversion, which converts the whole input as a single integer.
88+
89+
```python
90+
>>> codext.encode("Hello World!", "base38")
91+
'KKHF3W2S013OPM3EJX11'
92+
>>> codext.decode("KKHF3W2S013OPM3EJX11", "base38")
93+
'Hello World!'
94+
```
95+
8696
```python
8797
>>> codext.encode("this is a test!", "base45")
8898
'AWE+EDH44.OEOCC7WE QEX0'

‎pyproject.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ base32-geohash = "codext.base.baseN:main32geo"
8686
base32-crockford = "codext.base.baseN:main32crk"
8787
base32-z = "codext.base.baseN:mainz32"
8888
base36 = "codext.base.baseN:main36"
89+
base38 = "codext.base.base38:main38"
8990
base45 = "codext.base.base45:main"
9091
base58-bitcoin = "codext.base.baseN:main58bc"
9192
base58-ripple = "codext.base.baseN:main58rp"

‎src/codext/base/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from argparse import ArgumentParser, RawTextHelpFormatter
33
from types import MethodType
44

5+
from .base38 import *
56
from .base45 import *
67
from .base85 import *
78
from .base91 import *

‎src/codext/base/base38.py‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# -*- coding: UTF-8 -*-
2+
"""Base38 Codec - base38 content encoding.
3+
4+
Base38 is the encoding of the payloads of the Matter (smart home standard) setup QR codes. The data is taken by chunks
5+
of 3 bytes, each chunk being read as a little-endian integer and written with the least significant digit first, in
6+
the alphabet "0-9A-Z-.". A chunk of 3 bytes gives 5 characters, a last chunk of 2 bytes gives 4 characters and a last
7+
chunk of 1 byte gives 2 characters.
8+
9+
This codec:
10+
- en/decodes strings from str to str
11+
- en/decodes strings from bytes to bytes
12+
- decodes file content to str (read)
13+
- encodes file content from str to bytes (write)
14+
15+
Reference: https://github.com/project-chip/connectedhomeip/blob/master/src/setup_payload/Base38Encode.cpp
16+
"""
17+
from ._base import main
18+
from ..__common__ import *
19+
20+
21+
# test vectors from https://github.com/project-chip/connectedhomeip/blob/master/src/setup_payload/tests/TestQRCode.cpp
22+
__examples__ = {
23+
'enc(base38|base-38|base_38)': {'': "", '\n': "A0", '\n\n': "OT10", '\n\n\n': "-N.B0", '\n\n\x00': "OT100",
24+
'\n\n(': "Y6V91", '\n\n)': "KL0B1", '\n\n\xff': "Q-M08", '#': "Z0",
25+
'\xff\x00': "R600", '.\x00\x00': "81000", '\xff': "R6", '\xff\xff': "NE71",
26+
'\xff\xff\xff': "PLS18",
27+
'Hello World!': "KKHF3W2S013OPM3EJX11"},
28+
'dec(base38)': {'KKHF3W2S013OPM3EJX11': "Hello World!", 'A0': "\n", 'S600': "\x00\x01",
29+
'OE710': "\x00\x00\x01", 'S6': None, 'OE71': None, 'QLS18': None, ' 0': None,
30+
'[0': None, '0\x01': None, 'A': None, 'KKHF3W': None},
31+
'enc-dec(base38)': ["\xff", "\xff\xfe", "\xff\xfe\xfd", "\xff\xfe\xfd\xfc", "@random{512,1024}"],
32+
}
33+
__guess__ = ["base38"]
34+
35+
36+
B38, CHUNKS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-.", {1: 2, 2: 4, 3: 5}
37+
38+
39+
def base38_encode(text, errors="strict"):
40+
t, r = b(text), []
41+
for i in range(0, len(t), 3):
42+
v = int.from_bytes(t[i:i+3], "little")
43+
for _ in range(CHUNKS[len(t[i:i+3])]):
44+
v, d = divmod(v, 38)
45+
r.append(B38[d])
46+
return (s := "".join(r)), len(s)
47+
48+
49+
def base38_decode(text, errors="strict"):
50+
_h, text, r = handle_error("base38", errors, decode=True), ensure_str(text), b""
51+
# a wrong character cannot be replaced in a chunk, hence it is dropped
52+
t = "".join(c if c in B38 else _h(c, i) and "" for i, c in enumerate(text))
53+
for i in range(0, len(t), 5):
54+
chunk = t[i:i+5]
55+
n, v = {2: 1, 4: 2, 5: 3}.get(len(chunk), 0), sum(B38.index(c) * 38 ** k for k, c in enumerate(chunk))
56+
# a last chunk of 1 or 3 characters cannot be decoded and the value of a chunk must fit in its number of bytes
57+
r += v.to_bytes(n, "little") if n and v < 256 ** n else b(_h(chunk, i, r))
58+
return r, len(r)
59+
60+
61+
add("base38", base38_encode, base38_decode, r"^base[-_]?38$", expansion_factor=5 / 3)
62+
main38 = main(38, "<https://github.com/project-chip/connectedhomeip>", inv=False, swap=False)

0 commit comments

Comments
 (0)