z85.py revision 781d71db
1"""Python implementation of Z85 85-bit encoding
2
3Z85 encoding is a plaintext encoding for a bytestring interpreted as 32bit integers.
4Since the chunks are 32bit, a bytestring must be a multiple of 4 bytes.
5See ZMQ RFC 32 for details.
6
7
8"""
9
10# Copyright (C) PyZMQ Developers
11# Distributed under the terms of the Modified BSD License.
12
13import sys
14import struct
15
16PY3 = sys.version_info[0] >= 3
17# Z85CHARS is the base 85 symbol table
18Z85CHARS = b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^!/*?&<>()[]{}@%$#"
19# Z85MAP maps integers in [0,84] to the appropriate character in Z85CHARS
20Z85MAP = dict([(c, idx) for idx, c in enumerate(Z85CHARS)])
21
22_85s = [ 85**i for i in range(5) ][::-1]
23
24def encode(rawbytes):
25    """encode raw bytes into Z85"""
26    # Accepts only byte arrays bounded to 4 bytes
27    if len(rawbytes) % 4:
28        raise ValueError("length must be multiple of 4, not %i" % len(rawbytes))
29
30    nvalues = len(rawbytes) / 4
31
32    values = struct.unpack('>%dI' % nvalues, rawbytes)
33    encoded = []
34    for v in values:
35        for offset in _85s:
36            encoded.append(Z85CHARS[(v // offset) % 85])
37
38    # In Python 3, encoded is a list of integers (obviously?!)
39    if PY3:
40        return bytes(encoded)
41    else:
42        return b''.join(encoded)
43
44def decode(z85bytes):
45    """decode Z85 bytes to raw bytes"""
46    if len(z85bytes) % 5:
47        raise ValueError("Z85 length must be multiple of 5, not %i" % len(z85bytes))
48
49    nvalues = len(z85bytes) / 5
50    values = []
51    for i in range(0, len(z85bytes), 5):
52        value = 0
53        for j, offset in enumerate(_85s):
54            value += Z85MAP[z85bytes[i+j]] * offset
55        values.append(value)
56    return struct.pack('>%dI' % nvalues, *values)
57