Skip to content

Commit ee726c2

Browse files
committed
Improved bytes/text in/out handling
1 parent 0cba811 commit ee726c2

27 files changed

Lines changed: 337 additions & 37 deletions

File tree

‎docs/pages/howto.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,12 @@ Whatever solution is chosen, the following arguments shall be considered:
2525

2626
- `ename` (first positional argument): Choose the shortest possible encoding name. If it clashes with another codec, always remember that `codext` resolves codecs in order of registry, that is from the first added. Also, it resolves codecs based on the given pattern. So, a codec with a clashing name could still be selected if the pattern does not match for the codec with the precedence but matches for this codec.
2727
- `pattern` (keyword-argument): If not defined, it defaults to the encoding name. It can be a regular expression ; in this case, it should not be too broad. A codec decode or encode function can be parametrized through the pattern using the **first capture group**. It is important to note that the first capture group is used and not any other. This means that any other group definition shall use the do-not-capture specifier, that is "`(?:...)`".
28+
- `plain` and `encoded` (keyword-arguments): These tell the kind of the plain side (what is encoded) and of the encoded side of the codec: "`bytes`" for data, handled byte for byte, or "`text`" for characters. They decide how a `bytes` input is passed to the encode and decode functions and how their output is turned back into `bytes`: a "`bytes`" side is passed byte for byte (as a `str` of the characters 0 to 255, which [`b`](https://github.com/dhondta/python-codext/blob/main/src/codext/utils.py) turns back into the same bytes), while a "`text`" side is read from UTF-8 (or Latin-1 if not valid UTF-8) and written in UTF-8. If both sides are "`text`" and the input is not valid UTF-8, the output is written in Latin-1 (e.g. `rot13` turns `b"caf\xe9"` into `b"pns\xe9"`). By default, the plain side holds bytes for the `base`, `binary`, `checksum`, `compression` and `hashing` categories, and the encoded side for the `binary` and `compression` ones (and for barcodes, except their `-text` variants) ; both hold text otherwise. Each can also be a function giving the kind from the encoding name.
29+
30+
!!! note "Bytes or text ?"
31+
32+
A codec that works on the bytes of its input (e.g. a base encoding, a compression or a cipher on bytes) has a "`bytes`" plain side, so that any data is recovered exactly, including bytes that happen to be valid UTF-8 ; a codec that works on characters (e.g. a substitution of letters, a case conversion or a codec encoding the code points of the characters) has a "`text`" plain side, so that a UTF-8 text given as `bytes` gives the same result as the same text given as a `str`. The tests in `tests/test_bytes.py` check these properties for every codec.
33+
2834

2935
!!! danger "Too broad pattern"
3036

‎scripts/audit_bytes.py‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import json, sys
2+
from functools import wraps
3+
import codext, codext.__common__ as C, codext.utils as U
4+
5+
variant = sys.argv[1]
6+
orig = C.fix_inout_formats
7+
8+
def make(variant):
9+
def deco(f):
10+
@wraps(f)
11+
def w(*a, **k):
12+
a0, enc = a[0], None
13+
if isinstance(a0, bytes):
14+
if variant == "p1":
15+
x = a0.decode("latin-1")
16+
else:
17+
try:
18+
x, enc = a0.decode("utf-8"), "utf-8"
19+
except UnicodeDecodeError:
20+
x, enc = a0.decode("latin-1"), "latin-1"
21+
else:
22+
x = U.ensure_str(a0) if isinstance(a0, str) else a0
23+
r = f(x, *a[1:], **k)
24+
out = r[0] if isinstance(r, (tuple, list)) else r
25+
if isinstance(a0, bytes):
26+
if variant == "p2" and isinstance(out, str):
27+
try:
28+
out = out.encode(enc)
29+
except UnicodeEncodeError:
30+
out = U.b(out)
31+
else:
32+
out = U.fix(out, a0)
33+
else:
34+
out = U.fix(out, a0)
35+
if isinstance(r, (tuple, list)):
36+
return (out, len(a0) if isinstance(a0, bytes) else r[1]) + tuple(r[2:])
37+
return out
38+
return w
39+
return deco
40+
41+
if variant != "current":
42+
C.fix_inout_formats = make(variant)
43+
codext.reset()
44+
45+
BYTES = [b"8\xc2\xb96", b"\xff\x00\x80abc", bytes(range(256))]
46+
TEXT = ["café ça", "naïve résumé", "日本 ok"]
47+
res = {}
48+
names = set()
49+
for e in codext.list_encodings():
50+
try:
51+
p = codext.lookup(e, False).parameters
52+
except Exception:
53+
continue
54+
if p.get("category") in ("native", "hashing", "checksum"):
55+
continue
56+
for g in (p.get("guess") or [e])[:2]:
57+
names.add((g, p.get("category")))
58+
for e, cat in sorted(names):
59+
exact, textok, tested_b, tested_t = 0, 0, 0, 0
60+
for x in BYTES:
61+
try:
62+
enc = codext.encode(x, e)
63+
if codext.decode(enc, e) is None: continue
64+
except Exception:
65+
continue
66+
tested_b += 1
67+
try:
68+
d = codext.decode(enc, e); d = d if isinstance(d, bytes) else U.b(d)
69+
exact += d == x
70+
except Exception:
71+
pass
72+
for s in TEXT:
73+
try:
74+
ref = codext.encode(s, e)
75+
refb = ref if isinstance(ref, bytes) else ref.encode("utf-8")
76+
got = codext.encode(s.encode("utf-8"), e)
77+
except Exception:
78+
continue
79+
tested_t += 1
80+
textok += got == refb
81+
res[e] = {"cat": cat, "exact": [exact, tested_b], "text": [textok, tested_t]}
82+
json.dump(res, open(sys.argv[2], "w"))

‎src/codext/__common__.py‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,11 @@
4343
# categories that were renamed or split, with the current categories of their codecs (still accepted, with a warning)
4444
DEPRECATED_CATEGORIES = {'crypto': ["cipher", "obfuscation"]}
4545
CODECS_CACHE = {}
46+
# categories whose codecs handle data (bytes) on their plain side, and on their encoded side
47+
PLAIN_BYTES_CATEGORIES = ["base", "base-generic", "binary", "checksum", "compression", "hashing"]
48+
ENCODED_DEFAULTS = {'binary': "bytes", 'compression': "bytes",
49+
# a barcode gives an image, unless its "-text" variant gives it as text
50+
'barcode': lambda name: "text" if re.search(r"[-_](?:text|txt)(?:$|[-_])", name) else "bytes"}
4651

4752
__codecs_registry = []
4853
# caches depending on the state of the registry (cleared whenever it changes)
@@ -164,6 +169,10 @@ def add(ename, encode=None, decode=None, pattern=None, text=True, add_to_codecs=
164169
:param add_to_codecs: also add the search function to the native registry
165170
NB: this will make the codec available in the built-in open(...) but will make it impossible
166171
to remove the codec later
172+
:param plain: kind of the plain side (what is encoded): "bytes" (data, handled byte for byte) or "text"
173+
(characters, read from and written to bytes as UTF-8), or a function giving it from the
174+
encoding name ; by default, depending on the category
175+
:param encoded: kind of the encoded side, as for plain
167176
"""
168177
remove(ename)
169178
if encode:
@@ -187,12 +196,20 @@ def add(ename, encode=None, decode=None, pattern=None, text=True, add_to_codecs=
187196
for c in [cat, category]:
188197
if c not in CODECS_CATEGORIES:
189198
CODECS_CATEGORIES.append(c)
199+
# kinds of the plain and encoded sides of the codec, deciding how bytes are read and written (see fix_inout_formats)
200+
plain = kwargs.pop('plain', None) or ["text", "bytes"][category in PLAIN_BYTES_CATEGORIES]
201+
encoded = kwargs.pop('encoded', None) or ENCODED_DEFAULTS.get(category, "text")
202+
for side in [plain, encoded]:
203+
if not callable(side) and side not in ["bytes", "text"]:
204+
raise ValueError(f"Bad kind of side for codec '{ename}': {side} (shall be 'bytes' or 'text')")
190205
# search function for the new encoding
191206
@_with_repr(ename)
192207
def getregentry(encoding):
193208
if encoding != ename and not (rx and rx.match(encoding)):
194209
return
195210
fenc, fdec, name = encode, decode, encoding
211+
# the kinds of the sides may depend on the encoding name (e.g. "qr" gives an image, while "qr-text" gives text)
212+
p_kind, e_kind = [k(encoding) if callable(k) else k for k in (plain, encoded)]
196213
# prepare CodecInfo input arguments
197214
if pattern:
198215
m, args, i = rx.match(encoding), [], 1
@@ -222,10 +239,10 @@ def getregentry(encoding):
222239
fenc = fenc(*args) if fenc else fenc
223240
fdec = fdec(*args) if fdec else fdec
224241
if fenc:
225-
fenc = fix_inout_formats(fenc)
242+
fenc = fix_inout_formats(fenc, p_kind, e_kind)
226243
if fdec:
227244
sl, sc = getattr(fdec, '__strip__', (False, False))
228-
fdec = fix_inout_formats(fdec)
245+
fdec = fix_inout_formats(fdec, e_kind, p_kind)
229246
if sl or sc:
230247
def _striplines(f):
231248
def __wrapper(input, *a, **kw):
@@ -279,6 +296,7 @@ class StreamReader(Codec, codecs.StreamReader):
279296
ci.parameters['pattern'] = pattern
280297
ci.parameters['text'] = text
281298
ci.parameters['category'] = category
299+
ci.parameters['plain'], ci.parameters['encoded'] = p_kind, e_kind
282300
ci.parameters['examples'] = kwargs.get('examples', glob.get('__examples__'))
283301
ci.parameters['guess'] = kwargs.get('guess', glob.get('__guess__', [ename])) or []
284302
ci.parameters['module'] = kwargs.get('module', glob.get('__name__'))

‎src/codext/base/base91.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,8 @@ def base91_decode(mode):
8181
def decode(text, errors="strict"):
8282
t, s, bits, alt = b(_stripl(text, True, True)), "", "", re.search(r'[-_]alt(ernate)?$', mode) is not None
8383
ehandler = handle_error("base91", errors, decode=True)
84-
for i in range(0, len(t), 2):
84+
# with the alternate variant, a last single character holds 6 bits, handled after the pairs
85+
for i in range(0, len(t) - (alt and len(t) % 2), 2):
8586
try:
8687
n = b91[__chr(t[i])] * [1, 91][alt]
8788
except KeyError:

‎src/codext/binary/elias.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,6 @@ def delta_dec(bits, i):
7373

7474

7575
add("elias-gamma", universal("elias-gamma", gamma_enc, gamma_dec), universal("elias-gamma", gamma_enc, gamma_dec, True),
76-
r"^(?:elias[-_]?)?gamma" + PATTERN_INTEGERS, examples=__examples1__, guess=__guess1__)
76+
r"^(?:elias[-_]?)?gamma" + PATTERN_INTEGERS, examples=__examples1__, guess=__guess1__, plain="text")
7777
add("elias-delta", universal("elias-delta", delta_enc, delta_dec), universal("elias-delta", delta_enc, delta_dec, True),
78-
r"^(?:elias[-_]?)?delta" + PATTERN_INTEGERS, examples=__examples2__, guess=__guess2__)
78+
r"^(?:elias[-_]?)?delta" + PATTERN_INTEGERS, examples=__examples2__, guess=__guess2__, plain="text")

‎src/codext/binary/fibonacci.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,4 +62,4 @@ def fibonacci_dec(bits, i):
6262

6363
add("fibonacci", universal("fibonacci", fibonacci_enc, fibonacci_dec), universal("fibonacci", fibonacci_enc,
6464
fibonacci_dec, True), r"^fib(?:onacci(?:[-_]cod(?:e|ing))?)?" + PATTERN_INTEGERS, examples=__examples__,
65-
guess=__guess__)
65+
guess=__guess__, plain="text")

‎src/codext/ciphers/shift.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,5 +33,5 @@ def encode(text, errors="strict"):
3333

3434

3535
add("shift", ord_shift_encode, ord_shift_decode, r"shift[-_]?([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$",
36-
transitive=True)
36+
transitive=True, plain="bytes")
3737

‎src/codext/common/octal.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,9 @@
2727
ENCMAP2 = {chr(i): oct2(i).zfill(3) for i in range(256)}
2828

2929

30-
add_map("octal-spaced", ENCMAP1, sep=" ", pattern=r"^octals?[-_]spaced$", examples=__examples1__,
30+
add_map("octal-spaced", ENCMAP1, plain="bytes", sep=" ", pattern=r"^octals?[-_]spaced$", examples=__examples1__,
3131
entropy=lambda e: .07258*e+2.3739, printables_rate=1.)
32-
add_map("octal", ENCMAP2, pattern=r"^octals?$", examples=__examples2__, entropy=lambda e: .08803*e+2.19498,
32+
add_map("octal", ENCMAP2, plain="bytes", pattern=r"^octals?$", examples=__examples2__,
33+
entropy=lambda e: .08803*e+2.19498,
3334
printables_rate=1.)
3435

‎src/codext/common/ordinal.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@
2525
ENCMAP2 = {chr(i): str(i).zfill(3) for i in range(256)}
2626

2727

28-
add_map("ordinal-spaced", ENCMAP1, sep=" ", pattern=r"^ordinals?[-_]spaced$", examples=__examples1__, entropy=3.,
28+
add_map("ordinal-spaced", ENCMAP1, plain="bytes", sep=" ", pattern=r"^ordinals?[-_]spaced$", examples=__examples1__,
29+
entropy=3., printables_rate=1.)
30+
add_map("ordinal", ENCMAP2, plain="bytes", pattern=r"^ordinals?$", examples=__examples2__, entropy=3.,
2931
printables_rate=1.)
30-
add_map("ordinal", ENCMAP2, pattern=r"^ordinals?$", examples=__examples2__, entropy=3., printables_rate=1.)
3132

‎src/codext/compressions/lz78.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,5 +84,5 @@ def lz78_decompress(input, errors="strict"):
8484
return "".join(chr(i) for i in out), len(out)
8585

8686

87-
add("lz78", lz78_compress, lz78_decompress)
87+
add("lz78", lz78_compress, lz78_decompress, plain="text")
8888

0 commit comments

Comments
 (0)