|
| 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