##// END OF EJS Templates
pure: use string for another exception in the pure version of base85...
marmoute -
r44082:4cd91104 stable
parent child Browse files
Show More
@@ -1,88 +1,88 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(
15 15 b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef"
16 16 b"ghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~"
17 17 )
18 18 _b85chars2 = [(a + b) for a in _b85chars for b in _b85chars]
19 19 _b85dec = {}
20 20
21 21
22 22 def _mkb85dec():
23 23 for i, c in enumerate(_b85chars):
24 24 _b85dec[c] = i
25 25
26 26
27 27 def b85encode(text, pad=False):
28 28 """encode text in base85 format"""
29 29 l = len(text)
30 30 r = l % 4
31 31 if r:
32 32 text += b'\0' * (4 - r)
33 33 longs = len(text) >> 2
34 34 words = struct.unpack(b'>%dL' % longs, text)
35 35
36 36 out = b''.join(
37 37 _b85chars[(word // 52200625) % 85]
38 38 + _b85chars2[(word // 7225) % 7225]
39 39 + _b85chars2[word % 7225]
40 40 for word in words
41 41 )
42 42
43 43 if pad:
44 44 return out
45 45
46 46 # Trim padding
47 47 olen = l % 4
48 48 if olen:
49 49 olen += 1
50 50 olen += l // 4 * 5
51 51 return out[:olen]
52 52
53 53
54 54 def b85decode(text):
55 55 """decode base85-encoded text"""
56 56 if not _b85dec:
57 57 _mkb85dec()
58 58
59 59 l = len(text)
60 60 out = []
61 61 for i in range(0, len(text), 5):
62 62 chunk = text[i : i + 5]
63 63 chunk = pycompat.bytestr(chunk)
64 64 acc = 0
65 65 for j, c in enumerate(chunk):
66 66 try:
67 67 acc = acc * 85 + _b85dec[c]
68 68 except KeyError:
69 69 raise ValueError(
70 70 'bad base85 character at position %d' % (i + j)
71 71 )
72 72 if acc > 4294967295:
73 raise ValueError(b'Base85 overflow in hunk starting at byte %d' % i)
73 raise ValueError('Base85 overflow in hunk starting at byte %d' % i)
74 74 out.append(acc)
75 75
76 76 # Pad final chunk if necessary
77 77 cl = l % 5
78 78 if cl:
79 79 acc *= 85 ** (5 - cl)
80 80 if cl > 1:
81 81 acc += 0xFFFFFF >> (cl - 2) * 8
82 82 out[-1] = acc
83 83
84 84 out = struct.pack(b'>%dL' % (len(out)), *out)
85 85 if cl:
86 86 out = out[: -(5 - cl)]
87 87
88 88 return out
General Comments 0
You need to be logged in to leave comments. Login now