Skip to content

Commit 564aa5a

Browse files
committed
Refactored codec: uu
1 parent 837e91a commit 564aa5a

1 file changed

Lines changed: 29 additions & 20 deletions

File tree

codext/others/uuencode.py

Lines changed: 29 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -7,39 +7,48 @@
77
- decodes file content to str (read)
88
- encodes file content from str to bytes (write)
99
"""
10-
from io import BytesIO
11-
from uu import decode as _dec, encode as _enc
10+
from binascii import a2b_uu as _dec, b2a_uu as _enc
1211

1312
from ..__common__ import *
1413

1514

1615
__examples__ = {
1716
'enc(uu|uu_codec)': {'this is a test': "begin 666 -\n.=&AI<R!I<R!A('1E<W0 \n \nend\n"},
18-
'dec(uu-encode)': {'.=&AI<R!I<R!A(\'1E<W0 ': "this is a test"},
19-
'dec(uuencode)': {'.=&AI<R!I<R!A(\'1E<W0`': "this is a test"},
20-
'dec(uu-codec)': {'begin 666 -\n.=&AI<R!I<R!A(\'1E<W0`': "this is a test"},
21-
'dec(uu_codec)': {'\n.=&AI<R!I<R!A(\'1E<W0`\n\n\n`\nend': "this is a test"},
17+
'dec(uu-encode)': {'.=&AI<R!I<R!A(\'1E<W0 ': "this is a test", '.=&AI<R!I<R!A(\'1E<W0`': "this is a test"},
18+
'dec(uu-codec)': {'begin 666 -\n.=&AI<R!I<R!A(\'1E<W0`': None, '.=&AI<R!I<R!A(\'1E<W0`\n\n\n`\nend': None},
19+
'dec(uu_codec)': {'begin 777 test.txt\n.=&AI<R!I<R!A(\'1E<W0`\n\n\n`\nend': "this is a test"},
20+
'enc-dec(uu)': ["@random{512,1024,2048}"],
2221
}
2322

2423

2524
def uu_encode(text, errors="strict"):
26-
out = BytesIO()
27-
_enc(BytesIO(b(text)), out)
28-
return out.getvalue(), len(text)
25+
r, t = b"begin 666 -\n", b(text)
26+
for i in range(0, len(t), 45):
27+
r += _enc(t[i:i+45])
28+
return r + b" \nend\n", len(text)
2929

3030

3131
def uu_decode(text, errors="strict"):
32-
t = b(text).strip(b"\n")
33-
if not re.match(b"^begin [1-7]{3} .*$", t.split(b"\n")[0]):
34-
t = b"begin 666 -\n" + t
35-
if not re.match(b"^end$", t.split(b"\n")[-1]):
36-
t += [b"", b"`"][t[-1] == b"`"] + b"\nend"
37-
out = BytesIO()
38-
_dec(BytesIO(t), out, quiet=True)
39-
out = out.getvalue()
40-
while out.endswith(b"\x00" * 42):
41-
out = out[:-42]
42-
return out, len(text)
32+
h = handle_error("uu", "strict", decode=True, kind="token", item="line")
33+
lines = b(text).strip(b" \t\r\n\f").split(b"\n")
34+
start, end = re.match(b"^begin [1-7]{3} .*$", lines[0]), re.match(b"^end$", lines[-1])
35+
if start and end:
36+
lines = lines[1:-1]
37+
elif not start and not end:
38+
pass
39+
else:
40+
if errors == "ignore":
41+
lines = lines[1:] if start else lines[:-1]
42+
elif end:
43+
h(lines[0], 0)
44+
elif start:
45+
h(lines[-1], len(lines)-1)
46+
while len(lines) > 0 and lines[-1].strip(b" \t\r\n\f") in [b"", b"`"]:
47+
lines = lines[:-1]
48+
r = b""
49+
for l in lines:
50+
r += _dec(l.strip(b" \t\r\n\f"))
51+
return r, len(text)
4352

4453

4554
add("uu", uu_encode, uu_decode, pattern=r"^uu(?:[-_]?encode|[-_]codec)?$",

0 commit comments

Comments
 (0)