Skip to content

Commit 5b09f0c

Browse files
committed
Added new codec: rotate
1 parent 19841a1 commit 5b09f0c

3 files changed

Lines changed: 72 additions & 0 deletions

File tree

codext/binary/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,5 @@
44
from .excess3 import *
55
from .gray import *
66
from .manchester import *
7+
from .rotate import *
78

codext/binary/rotate.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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+

docs/enc/binary.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,3 +139,22 @@ This codec XORes each group of 4 bits of the input text with a 1-byte clock sign
139139
'This is a test!'
140140
```
141141

142+
-----
143+
144+
### Rotate/Shift N bits
145+
146+
This codec rotates N bits using the `>>` (to the right) and `<<` (to the left) operations.
147+
148+
**Codec** | **Conversions** | **Aliases** | **Comment**
149+
:---: | :---: | --- | ---
150+
`rotate` | text <-> N-bits-rotated text | `rotate-N`, `rotate-right-N`, `rotate_left_N` | N belongs to [1,7] ; when nothing specified, it rotates to the right
151+
152+
```python
153+
>>> codext.encode("test", "rotate-1")
154+
':29:'
155+
>>> codext.encode("test", "rotate_right-1")
156+
':29:'
157+
>>> codext.encode("test", "rotate_left_1")
158+
'èÊæè'
159+
```
160+

0 commit comments

Comments
 (0)