From 70157b8bd919da6352a084596d06ff7054faa225 Mon Sep 17 00:00:00 2001 From: Klesti Selimaj Date: Tue, 28 Jul 2026 04:22:46 +0200 Subject: [PATCH] PWP --- __init__.py => src/__init__.py | 0 src/pwp.py | 179 +++++++++++++++++++++++++++++++++ 2 files changed, 179 insertions(+) rename __init__.py => src/__init__.py (100%) create mode 100644 src/pwp.py diff --git a/__init__.py b/src/__init__.py similarity index 100% rename from __init__.py rename to src/__init__.py diff --git a/src/pwp.py b/src/pwp.py new file mode 100644 index 0000000..eb5f4da --- /dev/null +++ b/src/pwp.py @@ -0,0 +1,179 @@ +import struct +import typing +from typing import get_type_hints, get_origin, get_args + + +class PWPError(Exception): + pass + + +def encode_value(value, typ) -> bytes: + origin = get_origin(typ) + + # Optional[T] + if origin is typing.Union: + args = get_args(typ) + + if type(None) in args: + if value is None: + return b"\x00" + + real_type = next(t for t in args if t is not type(None)) + return b"\x01" + encode_value(value, real_type) + + # list[T] + if origin is list: + item_type = get_args(typ)[0] + + out = len(value).to_bytes(4, "little") + + for item in value: + out += encode_value(item, item_type) + + return out + + # dict[K, V] + if origin is dict: + key_type, value_type = get_args(typ) + + out = len(value).to_bytes(4, "little") + + for k, v in value.items(): + out += encode_value(k, key_type) + out += encode_value(v, value_type) + + return out + + # primitives + if typ is str: + data = value.encode("utf-8") + return len(data).to_bytes(4, "little") + data + + if typ is bytes: + return len(value).to_bytes(4, "little") + value + + if typ is int: + return struct.pack("