Coverage for src/blob_dict/blob/__init__.py: 0%
34 statements
« prev ^ index » next coverage.py v7.8.0, created at 2025-04-07 08:32 -0700
« prev ^ index » next coverage.py v7.8.0, created at 2025-04-07 08:32 -0700
1from __future__ import annotations
3from base64 import b64decode, b64encode
4from typing import Any, override
6from simple_zstd import compress, decompress
9class BytesBlob:
10 def __init__(self, blob: bytes) -> None:
11 super().__init__()
13 self._blob_bytes: bytes = blob
15 def as_blob(
16 self,
17 blob_class: type[BytesBlob],
18 blob_class_args: dict[str, Any] | None = None,
19 ) -> BytesBlob:
20 return blob_class(self._blob_bytes, **(blob_class_args or {}))
22 def as_bytes(self, *, compression: bool = False) -> bytes:
23 return compress(self._blob_bytes) if compression else self._blob_bytes
25 @staticmethod
26 def from_bytes(b: bytes, *, compression: bool = False) -> BytesBlob:
27 return BytesBlob(decompress(b) if compression else b)
29 @staticmethod
30 def from_b64_str(s: str) -> BytesBlob:
31 return BytesBlob(b64decode(s))
33 def as_b64_str(self) -> str:
34 return b64encode(self._blob_bytes).decode("ascii")
36 def __repr__(self) -> str:
37 return f"{self.__class__.__name__}({self.as_bytes().__repr__()})"
40class StrBlob(BytesBlob):
41 def __init__(self, blob: bytes | str) -> None:
42 if isinstance(blob, str):
43 blob = blob.encode()
45 super().__init__(blob)
47 def as_str(self) -> str:
48 return self._blob_bytes.decode()
50 def __str__(self) -> str:
51 return self.as_str()
53 @override
54 def __repr__(self) -> str:
55 return f"{self.__class__.__name__}({self.as_str().__repr__()})"