|
| 1 | +# -*- coding: UTF-8 -*- |
| 2 | +"""Base91 Codec - base91 content encoding. |
| 3 | +
|
| 4 | +This codec: |
| 5 | +- en/decodes strings from str to str |
| 6 | +- en/decodes strings from bytes to bytes |
| 7 | +- decodes file content to str (read) |
| 8 | +- encodes file content from str to bytes (write) |
| 9 | +""" |
| 10 | +from string import ascii_lowercase as lower, ascii_uppercase as upper, digits |
| 11 | + |
| 12 | +from ..__common__ import * |
| 13 | + |
| 14 | + |
| 15 | +B91 = { |
| 16 | + '': upper + lower + digits + "!#$%&()*+,./:;<=>?@[]^_`{|}~\"", |
| 17 | + 'inv': lower + upper + digits + "!#$%&()*+,./:;<=>?@[]^_`{|}~\"", |
| 18 | +} |
| 19 | + |
| 20 | + |
| 21 | +__chr = lambda c: chr(c) if isinstance(c, int) else c |
| 22 | +__ord = lambda c: ord(c) if not isinstance(c, int) else c |
| 23 | + |
| 24 | + |
| 25 | +class Base91DecodeError(ValueError): |
| 26 | + pass |
| 27 | + |
| 28 | + |
| 29 | +def base91_encode(mode): |
| 30 | + b91 = B91[["inv", ""][mode == ""]] |
| 31 | + def encode(text, errors="strict"): |
| 32 | + t = b(text) |
| 33 | + s = "" |
| 34 | + bits = "" |
| 35 | + for c in t: |
| 36 | + bits = bin(__ord(c))[2:].zfill(8) + bits |
| 37 | + if len(bits) > 13: |
| 38 | + n = int(bits[-13:], 2) |
| 39 | + if n > 88: |
| 40 | + bits = bits[:-13] |
| 41 | + else: |
| 42 | + n = int(bits[-14:], 2) |
| 43 | + bits = bits[:-14] |
| 44 | + s += b91[n % 91] + b91[n // 91] |
| 45 | + if len(bits) > 0: |
| 46 | + n = int(bits, 2) |
| 47 | + s += b91[n % 91] |
| 48 | + if len(bits) > 7 or n > 90: |
| 49 | + s += b91[n // 91] |
| 50 | + return s, len(t) |
| 51 | + return encode |
| 52 | + |
| 53 | + |
| 54 | +def base91_decode(mode): |
| 55 | + b91 = {c: i for i, c in enumerate(B91[["inv", ""][mode == ""]])} |
| 56 | + def decode(text, errors="strict"): |
| 57 | + t = b(text) |
| 58 | + s = "" |
| 59 | + bits = "" |
| 60 | + for i in range(0, len(t), 2): |
| 61 | + try: |
| 62 | + n = b91[__chr(t[i])] |
| 63 | + except KeyError: |
| 64 | + raise Base91DecodeError("'base91' codec can't decode character '%s' in position %d" % (__chr(t[i]), i)) |
| 65 | + try: |
| 66 | + j = i + 1 |
| 67 | + n += b91[__chr(t[j])] * 91 |
| 68 | + except IndexError: |
| 69 | + pass |
| 70 | + except KeyError: |
| 71 | + raise Base91DecodeError("'base91' codec can't decode character '%s' in position %d" % (__chr(t[j]), j)) |
| 72 | + bits = bin(n)[2:].zfill([14, 13][n & 8191 > 88]) + bits |
| 73 | + while len(bits) > 8: |
| 74 | + s += chr(int(bits[-8:], 2)) |
| 75 | + bits = bits[:-8] |
| 76 | + if len(bits) > 0 and not set(bits) == {"0"}: |
| 77 | + s += chr(int(bits, 2)) |
| 78 | + return s, len(t) |
| 79 | + return decode |
| 80 | + |
| 81 | + |
| 82 | +add("base91", base91_encode, base91_decode, r"^base[-_]?91(|[-_]inv(?:erted)?)$") |
| 83 | + |
0 commit comments