|
| 1 | +# -*- coding: UTF-8 -*- |
| 2 | +"""Rotate-Bits Codec - rotate-N-bits 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 | +import operator |
| 11 | + |
| 12 | +from ..__common__ import * |
| 13 | + |
| 14 | + |
| 15 | +__examples__ = { |
| 16 | + 'enc(rotate-0|rotate-8|rotate-left-8)': None, |
| 17 | + 'enc(rotate1|rotate-right-1|rotate_1)': {'This is a test': "*449\x1049\x100\x10:29:"}, |
| 18 | + 'dec(rotate1)': {'*449\x1049\x100\x10:29:': "Thhr hr ` tdrt"}, |
| 19 | + 'enc(rotate-left-1|rotate_left_1)': {'This is a test': "¨ÐÒæ@Òæ@Â@èÊæè"}, |
| 20 | +} |
| 21 | +__guess__ = ["rotate-%s" % i for i in "12"] + ["rotate-left-%s" % i for i in "12"] |
| 22 | + |
| 23 | + |
| 24 | +if PY3: |
| 25 | + def _getn(i): |
| 26 | + m = 1 |
| 27 | + if str(i).startswith("left"): |
| 28 | + i = i[4:].lstrip("-_") |
| 29 | + m = -1 |
| 30 | + return m * int(i) |
| 31 | + |
| 32 | + |
| 33 | + def _rotaten(text, n=1): |
| 34 | + op = [operator.lshift, operator.rshift][n > 0] |
| 35 | + n = abs(n) |
| 36 | + return "".join(chr(op(ord(c), n)) for c in ensure_str(text)) |
| 37 | + |
| 38 | + |
| 39 | + def rotate_encode(i): |
| 40 | + def encode(text, errors="strict"): |
| 41 | + return _rotaten(text, _getn(i)), len(text) |
| 42 | + return encode |
| 43 | + |
| 44 | + |
| 45 | + def rotate_decode(i): |
| 46 | + def decode(text, errors="strict"): |
| 47 | + return _rotaten(text, -_getn(i)), len(text) |
| 48 | + return decode |
| 49 | + |
| 50 | + |
| 51 | + add("rotate", rotate_encode, rotate_decode, r"rotate(?:[-_]?bits)?[-_]?((?:left[-_]?)?[1-7])$") |
| 52 | + |
0 commit comments