Created
June 1, 2025 11:10
-
-
Save ascopes/bf457458d865bb91098ea9a53f45f004 to your computer and use it in GitHub Desktop.
Python encoding of "octal numbers" in tar files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import typing as t | |
| @t.final | |
| class TarOctalAsciiNumber(int): | |
| __slots__: t.Sequence[str] = () | |
| def __new__(cls, value: int) -> t.Self: | |
| return super().__new__(cls, value) | |
| def to_octal_ascii(self, size: int) -> bytes: | |
| data = oct(self)[2:].encode("ascii") + b"\0" | |
| if len(data) > size: | |
| raise ValueError(f"Cannot fit {data} into {size} bytes") | |
| lpad = b"\0" * (len(data) - size) | |
| return lpad + data | |
| @classmethod | |
| def from_octal_ascii(cls, data: bytes) -> t.Self: | |
| string = data.strip(b" \0").decode("ascii") | |
| value = int(string, 8) | |
| return cls(value) | |
| def __repr__(self) -> str: | |
| return f"{type(self).__name__}(value={super()!r}}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment