Skip to content

Commit 60becfd

Browse files
committed
Added codec: rle
1 parent 507a6e7 commit 60becfd

4 files changed

Lines changed: 151 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,7 @@ This category also contains `ascii85`, `adobe`, `[x]btoa`, `zeromq` with the `ba
324324
- [X] `pkzip_deflate`: standard Zip-deflate compression/decompression
325325
- [X] `pkzip_bzip2`: standard BZip2 compression/decompression
326326
- [X] `pkzip_lzma`: standard LZMA compression/decompression
327+
- [X] `rle`: compresses runs of identical characters with Run-Length Encoding (count before or after each character, compact, bytes or repeated-byte escape variants)
327328

328329
> :warning: Compression functions are of course definitely **NOT** encoding functions ; they are implemented for leveraging the `.encode(...)` API from `codecs`.
329330

‎docs/pages/enc/compressions.md‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,3 +73,36 @@ This implements multiple compression types available in the native [`zipfile`](h
7373
'a test string'
7474
```
7575

76+
-----
77+
78+
### Run-Length Encoding
79+
80+
This replaces each run of identical consecutive characters by its length followed by the character. The default variant writes the length in decimal ; it cannot encode digits, as they would be confused with the lengths. The `compact` variant omits a length of 1, the `suffix` variant writes the length after the character (both can be combined as `rle-compact-suffix`), while the `bytes` variant writes the length as a single character (code point 1 to 255) and can encode any input. The `escape` variant keeps single characters as they are and writes a run as the character twice followed by the number of extra repeats as a single character (code point 0 to 255) ; it can encode any input and does not expand text without repeats.
81+
82+
**Codec** | **Conversions** | **Aliases** | **Comment**
83+
:---: | :---: | --- | ---
84+
`rle` | text <-> RLE-compressed text | `run-length`, `runlength`, `run_length_encoding` | digits cannot be encoded ; decoding accepts lengths of 1 being omitted
85+
`rle-compact` | text <-> RLE-compressed text | `run-length-compact` | lengths of 1 are omitted
86+
`rle-suffix` | text <-> RLE-compressed text | `run-length-suffix` | lengths after the characters (e.g. `A3B2`)
87+
`rle-compact-suffix` | text <-> RLE-compressed text | `run-length-compact-suffix` | lengths after the characters, lengths of 1 being omitted
88+
`rle-bytes` | data <-> RLE-compressed data | `run-length-bytes` | each run as a (length, character) pair, longer runs being split
89+
`rle-escape` | data <-> RLE-compressed data | `run-length-escape` | runs as a repeated character and a count of extra repeats, longer runs being split
90+
91+
```python
92+
>>> codext.encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBB", "rle")
93+
'12W1B12W3B'
94+
>>> codext.encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBB", "rle-compact")
95+
'12WB12W3B'
96+
>>> codext.decode("12WB12W3B", "run-length")
97+
'WWWWWWWWWWWWBWWWWWWWWWWWWBBB'
98+
>>> codext.encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBB", "rle-suffix")
99+
'W12B1W12B3'
100+
>>> codext.encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBB", "rle-compact-suffix")
101+
'W12BW12B3'
102+
>>> codext.encode("AAAB", "rle-bytes")
103+
'\x03A\x01B'
104+
>>> codext.encode("AAAAAB", "rle-escape")
105+
'AA\x03B'
106+
>>> codext.decode("AA\x03B", "rle-escape")
107+
'AAAAAB'
108+
```

‎src/codext/compressions/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from .lz77 import *
44
from .lz78 import *
55
from .pkzip import *
6+
from .rle import *
67

78

89
for e in list_encodings("compression"):

‎src/codext/compressions/rle.py‎

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
# -*- coding: UTF-8 -*-
2+
"""Run-Length Encoding Codec - RLE compression algorithm.
3+
4+
NB: Not an encoding properly speaking.
5+
6+
Each run of identical consecutive characters is replaced by its length followed by the character. Three variants are
7+
supported:
8+
- textual (default): the length is written in decimal before the character (e.g. "AAAB" gives "3A1B") ; digits cannot
9+
be encoded, as they would be confused with the lengths
10+
- compact: same as textual, except that a length of 1 is omitted (e.g. "AAAB" gives "3AB")
11+
- suffix: the length is written after the character instead (e.g. "AAAB" gives "A3B1", or "A3B" if also compact)
12+
- bytes: the length is written as a single character (code point 1 to 255) before the character, longer runs being
13+
split ; this variant can encode any input
14+
- escape: single characters are kept as is, while a run is written as the character twice followed by the number of
15+
extra repeats as a single character (code point 0 to 255, e.g. "AAAAAB" gives "AA\x03B"), longer runs being split ;
16+
this variant can encode any input and does not expand text without repeats
17+
18+
When decoding the textual variants, a character without length is taken once, so that both forms are decoded.
19+
20+
This codec:
21+
- en/decodes strings from str to str
22+
- en/decodes strings from bytes to bytes
23+
- decodes file content to str (read)
24+
- encodes file content from str to bytes (write)
25+
26+
Reference: https://en.wikipedia.org/wiki/Run-length_encoding
27+
"""
28+
import re
29+
from itertools import groupby
30+
from string import digits as DG
31+
32+
from ..__common__ import *
33+
34+
35+
__examples__ = {
36+
'enc(rle|run-length|runlength|run_length_encoding)': {
37+
'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW': "12W1B12W3B24W1B14W"},
38+
'enc(rle-compact)': {'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW': "12WB12W3B24WB14W"},
39+
'enc(rle)': {'Room 101': None},
40+
'dec(rle)': {'12WB3!': "WWWWWWWWWWWWB!!!", '3A0B': None, '3A2': None},
41+
'enc(rle-suffix|run-length-suffix)': {'AAABB C': "A3B2 1C1"},
42+
'enc(rle-compact-suffix)': {'AAABB C': "A3B2 C"},
43+
'dec(rle-suffix)': {'W12B!3': "WWWWWWWWWWWWB!!!", 'A3B0': None, '2A3': None},
44+
'enc(rle-bytes)': {'AAAB': "\x03A\x01B"},
45+
'dec(rle-bytes)': {'\x03': None, '\x00A': None},
46+
'enc-dec(rle|rle-compact|rle-suffix|rle-compact-suffix)': ["", "AAAB", "Hello, World!", " spaced out "],
47+
'enc(rle-escape|run-length-escape)': {'AAAAAB': "AA\x03B", 'AB': "AB", 'AABBB': "AA\x00BB\x01"},
48+
'dec(rle-escape)': {'AA': None, 'AB\u0100': "AB\u0100", 'AA\u0100': None},
49+
'enc-dec(rle-bytes|rle-escape)': ["", "A" * 300, "A" * 514, "A" * 515, "Room 101", "@random"],
50+
}
51+
52+
53+
def rle_encode(binary=None, compact=None, suffix=None):
54+
def encode(text, errors="strict"):
55+
text, r = ensure_str(text), []
56+
if binary == "bytes":
57+
for c, run in groupby(text):
58+
n = len(list(run))
59+
# a length cannot exceed 255 in a single character ; longer runs are split
60+
r += [chr(255) + c] * (n // 255) + ([chr(n % 255) + c] if n % 255 else [])
61+
elif binary == "escape":
62+
for c, run in groupby(text):
63+
n = len(list(run))
64+
# a pair holds at most 2 + 255 characters ; longer runs are split, a remaining single character being
65+
# kept as is
66+
r += [2 * c + chr(255)] * (n // 257) + ([] if (m := n % 257) == 0 else [c] if m == 1 else
67+
[2 * c + chr(m - 2)])
68+
else:
69+
# digits would be confused with the lengths, hence they are handled as errors
70+
_h = handle_error("rle", errors)
71+
text = "".join(_h(c, i) if c in DG else c for i, c in enumerate(text))
72+
for c, run in groupby(text):
73+
n = len(list(run))
74+
n = "" if n == 1 and compact else str(n)
75+
r.append(c + n if suffix else n + c)
76+
return (s := "".join(r)), len(s)
77+
return encode
78+
79+
80+
def rle_decode(binary=None, compact=None, suffix=None):
81+
# a character without length is taken once, so that the compact variants are decoded too ; digits that cannot be
82+
# bound to a character (trailing ones with lengths first, leading ones with lengths last) are matched separately
83+
token = re.compile(r"([^0-9])([0-9]*)|([0-9]+)" if suffix else r"([0-9]*)([^0-9])|([0-9]+)")
84+
def decode(text, errors="strict"):
85+
text, r, _h = ensure_str(text), "", handle_error("rle", errors, decode=True)
86+
if binary == "bytes":
87+
for i in range(0, len(text), 2):
88+
if len(pair := text[i:i+2]) < 2 or not 0 < ord(pair[0]) < 256:
89+
r += _h(pair, i, r)
90+
else:
91+
r += pair[1] * ord(pair[0])
92+
elif binary == "escape":
93+
i = 0
94+
while i < len(text):
95+
if text[i+1:i+2] != text[i]:
96+
r, i = r + text[i], i + 1
97+
continue
98+
# a repeated character is followed by the number of extra repeats
99+
if len(run := text[i:i+3]) < 3 or ord(run[2]) > 255:
100+
r += _h(run, i, r)
101+
else:
102+
r += run[0] * (2 + ord(run[2]))
103+
i += 3
104+
else:
105+
for m in token.finditer(text):
106+
c, n = m.group(1, 2) if suffix else m.group(2, 1)
107+
if m.group(3) or n and int(n) == 0:
108+
r += _h(m.group(), m.start(), r)
109+
else:
110+
r += c * int(n or 1)
111+
return r, len(r)
112+
return decode
113+
114+
115+
add("rle", rle_encode, rle_decode,
116+
r"^(?:rle|run[-_]?length(?:[-_]encoding)?)(?:[-_](bytes|escape)|(?:[-_](compact))?(?:[-_](suffix))?)$")

0 commit comments

Comments
 (0)