Faster RLE codec implementation (#938)

* faster pyrogram lre encode implementation

* Update file_id.py

* optimized rle decode

Co-authored-by: andrew (from workstation) <andrew-ld@protonmail.com>
Co-authored-by: Dan <14043624+delivrance@users.noreply.github.com>
This commit is contained in:
andrew-ld 2022-03-28 20:10:52 +02:00 committed by GitHub
parent 190760cf0e
commit 06ee482b23
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -21,6 +21,7 @@ import logging
import struct import struct
from enum import IntEnum from enum import IntEnum
from io import BytesIO from io import BytesIO
from typing import List
from pyrogram.raw.core import Bytes, String from pyrogram.raw.core import Bytes, String
@ -63,7 +64,7 @@ def rle_encode(s: bytes) -> bytes:
Returns: Returns:
``bytes``: The encoded bytes ``bytes``: The encoded bytes
""" """
r: bytes = b"" r: List[int] = []
n: int = 0 n: int = 0
for b in s: for b in s:
@ -71,15 +72,15 @@ def rle_encode(s: bytes) -> bytes:
n += 1 n += 1
else: else:
if n: if n:
r += bytes([0, n]) r.extend((0, n))
n = 0 n = 0
r += bytes([b]) r.append(b)
if n: if n:
r += bytes([0, n]) r.extend((0, n))
return r return bytes(r)
def rle_decode(s: bytes) -> bytes: def rle_decode(s: bytes) -> bytes:
@ -87,12 +88,12 @@ def rle_decode(s: bytes) -> bytes:
Parameters: Parameters:
s (``bytes``): s (``bytes``):
Bytes to encode Bytes to decode
Returns: Returns:
``bytes``: The encoded bytes ``bytes``: The decoded bytes
""" """
r: bytes = b"" r: List[int] = []
z: bool = False z: bool = False
for b in s: for b in s:
@ -101,12 +102,12 @@ def rle_decode(s: bytes) -> bytes:
continue continue
if z: if z:
r += b"\x00" * b r.extend((0,) * b)
z = False z = False
else: else:
r += bytes([b]) r.append(b)
return r return bytes(r)
class FileType(IntEnum): class FileType(IntEnum):