Debian Codegraph @

pypy/module/binascii/interp_uu.py

raw symbols SCIP
1 from pypy.interpreter.gateway import unwrap_spec
2 from rpython.rlib.rstring import StringBuilder
3 from pypy.module.binascii.interp_binascii import raise_Error
4 from pypy.module.binascii.interp_binascii import AsciiBufferUnwrapper
5
6 # ____________________________________________________________
7
8 def _a2b_read(space, s, index):
9 try:
10 c = s[index]
11 except IndexError:
12 return 0
13 # Check the character for legality. The 64 instead of the expected 63
14 # is because there are a few uuencodes out there that use '`' as zero
15 # instead of space.
16 if c < ' ' or c > chr(32 + 64):
17 if c == '\n' or c == '\r':
18 return 0
19 raise_Error(space, "Illegal char")
20 return (ord(c) - 0x20) & 0x3f
21 _a2b_read._always_inline_ = True
22
23
24 @unwrap_spec(ascii=AsciiBufferUnwrapper)
25 def a2b_uu(space, ascii):
26 "Decode a line of uuencoded data."
27
28 if len(ascii) == 0: # obscure case, for compability with CPython
29 length = (-0x20) & 0x3f
30 else:
31 length = (ord(ascii[0]) - 0x20) & 0x3f
32 res = StringBuilder(length)
33
34 for i in range(1, len(ascii), 4):
35 A = _a2b_read(space, ascii, i)
36 B = _a2b_read(space, ascii, i+1)
37 C = _a2b_read(space, ascii, i+2)
38 D = _a2b_read(space, ascii, i+3)
39 #
40 if res.getlength() < length:
41 res.append(chr(A << 2 | B >> 4))
42 elif A != 0 or B != 0:
43 raise_Error(space, "Trailing garbage")
44 #
45 if res.getlength() < length:
46 res.append(chr((B & 0xf) << 4 | C >> 2))
47 elif C != 0:
48 raise_Error(space, "Trailing garbage")
49 #
50 if res.getlength() < length:
51 res.append(chr((C & 0x3) << 6 | D))
52 elif D != 0:
53 raise_Error(space, "Trailing garbage")
54
55 remaining = length - res.getlength()
56 if remaining > 0:
57 res.append_multiple_char('\x00', remaining)
58 return space.newbytes(res.build())
59
60 # ____________________________________________________________
61
62 def _b2a_read(bin, i):
63 try:
64 return ord(bin[i])
65 except IndexError:
66 return 0
67 _b2a_read._always_inline_ = True
68
69 def _b2a_write(res, num, backtick):
70 if backtick and not num:
71 res.append(chr(0x60))
72 else:
73 res.append(chr(0x20 + num))
74 _b2a_write._always_inline_ = True
75
76 @unwrap_spec(bin='bufferstr', backtick=bool)
77 def b2a_uu(space, bin, __kwonly__, backtick=False):
78 "Uuencode a line of data."
79
80 length = len(bin)
81 if length > 45:
82 raise_Error(space, 'At most 45 bytes at once')
83 res = StringBuilder(2 + ((length + 2) // 3) * 4)
84 _b2a_write(res, length, backtick)
85
86 for i in range(0, length, 3):
87 A = _b2a_read(bin, i)
88 B = _b2a_read(bin, i+1)
89 C = _b2a_read(bin, i+2)
90 #
91 _b2a_write(res, A >> 2, backtick)
92 _b2a_write(res, (A & 0x3) << 4 | B >> 4, backtick)
93 _b2a_write(res, (B & 0xF) << 2 | C >> 6, backtick)
94 _b2a_write(res, C & 0x3F , backtick)
95
96 res.append('\n')
97 return space.newbytes(res.build())