##// END OF EJS Templates
py3: converts bytes to pycompat.bytestr to get bytechrs while enumerating...
Pulkit Goyal -
r36209:80301c90 default
parent child Browse files
Show More
@@ -1,79 +1,80 b''
1 1 # base85.py: pure python base85 codec
2 2 #
3 3 # Copyright (C) 2009 Brendan Cully <brendan@kublai.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from __future__ import absolute_import
9 9
10 10 import struct
11 11
12 12 from .. import pycompat
13 13
14 14 _b85chars = pycompat.bytestr("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef"
15 15 "ghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~")
16 16 _b85chars2 = [(a + b) for a in _b85chars for b in _b85chars]
17 17 _b85dec = {}
18 18
19 19 def _mkb85dec():
20 20 for i, c in enumerate(_b85chars):
21 21 _b85dec[c] = i
22 22
23 23 def b85encode(text, pad=False):
24 24 """encode text in base85 format"""
25 25 l = len(text)
26 26 r = l % 4
27 27 if r:
28 28 text += '\0' * (4 - r)
29 29 longs = len(text) >> 2
30 30 words = struct.unpack('>%dL' % (longs), text)
31 31
32 32 out = ''.join(_b85chars[(word // 52200625) % 85] +
33 33 _b85chars2[(word // 7225) % 7225] +
34 34 _b85chars2[word % 7225]
35 35 for word in words)
36 36
37 37 if pad:
38 38 return out
39 39
40 40 # Trim padding
41 41 olen = l % 4
42 42 if olen:
43 43 olen += 1
44 44 olen += l // 4 * 5
45 45 return out[:olen]
46 46
47 47 def b85decode(text):
48 48 """decode base85-encoded text"""
49 49 if not _b85dec:
50 50 _mkb85dec()
51 51
52 52 l = len(text)
53 53 out = []
54 54 for i in range(0, len(text), 5):
55 55 chunk = text[i:i + 5]
56 chunk = pycompat.bytestr(chunk)
56 57 acc = 0
57 58 for j, c in enumerate(chunk):
58 59 try:
59 60 acc = acc * 85 + _b85dec[c]
60 61 except KeyError:
61 62 raise ValueError('bad base85 character at position %d'
62 63 % (i + j))
63 64 if acc > 4294967295:
64 65 raise ValueError('Base85 overflow in hunk starting at byte %d' % i)
65 66 out.append(acc)
66 67
67 68 # Pad final chunk if necessary
68 69 cl = l % 5
69 70 if cl:
70 71 acc *= 85 ** (5 - cl)
71 72 if cl > 1:
72 73 acc += 0xffffff >> (cl - 2) * 8
73 74 out[-1] = acc
74 75
75 76 out = struct.pack('>%dL' % (len(out)), *out)
76 77 if cl:
77 78 out = out[:-(5 - cl)]
78 79
79 80 return out
General Comments 0
You need to be logged in to leave comments. Login now