|
| 1 | +# -*- coding: UTF-8 -*- |
| 2 | +"""A1Z26 Codec - A1Z26 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 |
| 11 | + |
| 12 | +from ..__common__ import * |
| 13 | + |
| 14 | + |
| 15 | +SEP = "-_/|,;:*" |
| 16 | + |
| 17 | +__examples__ = { |
| 18 | + 'enc(a1z26-BAD)': None, |
| 19 | + 'dec(a1z26)': {'1-12-123': None}, |
| 20 | + 'enc(a1z26)': {'test123': None, 'this is a test': "20-8-9-19 9-19 1 20-5-19-20"}, |
| 21 | + 'enc(a1z26-/)': {'this is a test': "20/8/9/19 9/19 1 20/5/19/20"}, |
| 22 | +} |
| 23 | +__guess__ = ["a1z26", "a1z26_"] + ["a1z26-" + s for s in SEP[2:]] |
| 24 | + |
| 25 | + |
| 26 | +def a1z26_encode(sep): |
| 27 | + sep = sep[-1] if len(sep) > 0 else "-" |
| 28 | + def encode(text, errors="strict"): |
| 29 | + words = [] |
| 30 | + for word in text.split(): |
| 31 | + w = [] |
| 32 | + for k, c in enumerate(word): |
| 33 | + try: |
| 34 | + w.append(str(lower.index(c.lower()) + 1)) |
| 35 | + except ValueError: |
| 36 | + w.append(handle_error("a1z26", errors)(c, k)) |
| 37 | + words.append(sep.join(w).strip(sep)) |
| 38 | + return " ".join(words), len(text) |
| 39 | + return encode |
| 40 | + |
| 41 | + |
| 42 | +def a1z26_decode(sep): |
| 43 | + sep = sep[-1] if len(sep) > 0 else "-" |
| 44 | + def decode(text, errors="strict"): |
| 45 | + k, words = 0, [] |
| 46 | + for word in text.split(): |
| 47 | + w = "" |
| 48 | + for i in word.split(sep): |
| 49 | + k += 1 |
| 50 | + try: |
| 51 | + w += lower[int(i)-1] |
| 52 | + except IndexError: |
| 53 | + w += handle_error("a1z26", errors, decode=True)(str(i), k) |
| 54 | + words.append(w) |
| 55 | + return " ".join(words), len(text) |
| 56 | + return decode |
| 57 | + |
| 58 | + |
| 59 | +add("a1z26", a1z26_encode, a1z26_decode, pattern=r"^a1z26(|[-_]|[-_][/|,;:\*])$") |
| 60 | + |
0 commit comments