Skip to content

Commit f9b8a4a

Browse files
committed
Added codec: xxencode
1 parent b625ddd commit f9b8a4a

5 files changed

Lines changed: 109 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -383,6 +383,7 @@ This category also contains `ascii85`, `adobe`, `[x]btoa`, `zeromq` with the `ba
383383
- [X] `dna`: implements the 8 rules of DNA sequences (N belongs to [1,8])
384384
- [X] `letter-indices`: encodes consonants and/or vowels with their corresponding indices
385385
- [X] `markdown`: unidirectional encoding from Markdown to HTML
386+
- [X] `xx`: XXencode, a UUencode variant with an alphanumeric alphabet (`+`, `-`, digits and letters)
386387
- [X] `yenc`: Usenet binary-to-text encoding (raw, wrapped or framed with header, trailer and CRC32)
387388

388389
#### [Steganography](https://python-codext.readthedocs.io/en/latest/enc/stegano.html)

‎docs/pages/enc/others.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,23 @@ This is only for "encoding" (converting) Markdown to HTML.
7979

8080
-----
8181

82+
### XXencode
83+
84+
XXencode works like UUencode, but with an alphabet made of "`+`", "`-`", digits and letters only. Each line encodes up to 45 bytes and starts with the character holding its number of bytes ; the lines are framed by a `begin` line and an `end` line.
85+
86+
**Codec** | **Conversions** | **Aliases** | **Comment**
87+
:---: | :---: | --- | ---
88+
`xx` | data <-> XXencoded data | `xxencode`, `xx-encode`, `xx_codec` | decoding works with or without the `begin` and `end` lines
89+
90+
```python
91+
>>> codext.encode("Cat", "xxencode")
92+
'begin 666 -\n1Eq3o\n+\nend\n'
93+
>>> codext.decode("1Eq3o", "xx")
94+
'Cat'
95+
```
96+
97+
-----
98+
8299
### yEnc
83100

84101
yEnc is the binary-to-text encoding of Usenet. Each byte is shifted by 42 and only the critical characters (NUL, LF, CR, "`=`", as well as TAB and SPACE at the beginning or the end of a line and "`.`" at the beginning of a line) are escaped with "`=`".

‎src/codext/others/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,6 @@
44
from .letters import *
55
from .markdown import *
66
from .uuencode import *
7+
from .xxencode import *
78
from .yenc import *
89

‎src/codext/others/xxencode.py‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# -*- coding: UTF-8 -*-
2+
"""XX Codec - xxencode content encoding.
3+
4+
xxencode works like uuencode, but with an alphabet made of "+", "-", digits and letters only, so that the encoded data
5+
survives character set conversions (e.g. to EBCDIC). Each line encodes up to 45 bytes in groups of 3 bytes written as
6+
4 characters, and starts with the character holding its number of bytes. The lines are framed by a "begin" line and an
7+
"end" line, preceded by an empty data line ("+").
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://en.wikipedia.org/wiki/Xxencoding
16+
"""
17+
from string import ascii_lowercase as LC, ascii_uppercase as UC, digits as DG
18+
19+
from ..__common__ import *
20+
21+
22+
__examples__ = {
23+
'enc(xx|xxencode|xx-encode|xx_codec)': {'Cat': "begin 666 -\n1Eq3o\n+\nend\n"},
24+
'dec(xx)': {'1Eq3o': "Cat", 'begin 644 cat.txt\r\n1Eq3o\r\n+\r\nend\r\n': "Cat", '1Eq!o': None,
25+
'3Eq3o': None, '!Eq3o': None,
26+
'begin 644 cat.txt\n\n1Eq3o++++\n+\nend': "Cat"},
27+
'dec(xxencode)': {'begin 644 wikipedia-url.txt\nOO5FoQ1cj9rRrRmtrOKhdQ4JYOK2iPr7b1Ec+\n+\nend':
28+
"http://www.wikipedia.org\r\n"},
29+
'enc-dec(xx)': ["", "this is a test", "@random{512,1024,2048}"],
30+
}
31+
32+
33+
XX = "+-" + DG + UC + LC
34+
35+
36+
def xx_encode(text, errors="strict"):
37+
data, r = b(text), ["begin 666 -"]
38+
for i in range(0, len(data), 45):
39+
chunk, line = data[i:i+45], XX[len(data[i:i+45])]
40+
for j in range(0, len(chunk), 3):
41+
n = int.from_bytes(chunk[j:j+3].ljust(3, b"\0"), "big")
42+
line += "".join(XX[n >> s & 63] for s in (18, 12, 6, 0))
43+
r.append(line)
44+
return (s := "\n".join(r + ["+", "end", ""])), len(s)
45+
46+
47+
def xx_decode(text, errors="strict"):
48+
_h = handle_error("xx", errors, decode=True, kind="token", item="line")
49+
lines, r = [l.strip() for l in ensure_str(text).strip().splitlines()], b""
50+
if len(lines) > 0 and re.match(r"^begin [0-7]{3,4} ", lines[0]):
51+
lines = lines[1:]
52+
if len(lines) > 0 and lines[-1] == "end":
53+
lines = lines[:-1]
54+
for k, l in enumerate(lines):
55+
if l == "":
56+
continue
57+
# the first character holds the number of bytes of the line ; "+" (0) marks the end of the data
58+
if (n := XX.find(l[0])) == 0:
59+
break
60+
out, data, size = b"", l[1:], 0
61+
if n < 0:
62+
r += b(_h(l[0], k))
63+
n = len(data) * 3 // 4
64+
# each group of 4 characters holds 3 bytes, the last one being truncated to the announced number of bytes ; an
65+
# invalid group is handled as a whole, extra groups (padding) being discarded
66+
for j in range(0, len(data), 4):
67+
if size >= n:
68+
break
69+
g, t = data[j:j+4], min(3, n - size)
70+
size += t
71+
if any(c not in XX for c in g):
72+
out += b(_h(g, k))
73+
continue
74+
v = 0
75+
for c in g.ljust(4, "+"):
76+
v = v << 6 | XX.index(c)
77+
out += v.to_bytes(3, "big")[:t]
78+
r += out if size == n else out + b(_h(l, k))
79+
return r, len(r)
80+
81+
82+
add("xx", xx_encode, xx_decode, r"^xx(?:[-_]?encode|[-_]codec)?$",
83+
bonus_func=lambda o, *a: re.match(r"^begin [0-7]{3,4} .*\n(?:.*\n)*\+\nend$", ensure_str(o.text).strip(), re.M))

‎tests/test_manual.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,3 +227,10 @@ def test_codec_zero_width(self):
227227
STR = "A" + chr(0x1f600) + "B"
228228
self.assertEqual(codecs.encode(STR, "zero-width-full", "ignore"), codecs.encode("AB", "zero-width-full"))
229229
self.assertIn(chr(0x1f600), codecs.encode(STR, "zero-width-full", "leave"))
230+
231+
def test_codec_xxencode(self):
232+
# a bad length character is reported, the number of bytes then being guessed from the length of the line
233+
self.assertEqual(codecs.decode("!Eq3o", "xx", "ignore"), "Cat")
234+
# an invalid group of 4 characters is handled as a whole (length "4" means 6 bytes)
235+
self.assertEqual(codecs.decode("4Eq!oEq3o", "xx", "replace"), "?Cat")
236+
self.assertEqual(codecs.decode("4Eq!oEq3o", "xx", "ignore"), "Cat")

0 commit comments

Comments
 (0)