binal 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- binal-0.1.0/PKG-INFO +84 -0
- binal-0.1.0/README.md +73 -0
- binal-0.1.0/pyproject.toml +36 -0
- binal-0.1.0/pyproject.toml.orig +35 -0
- binal-0.1.0/src/binal/__init__.py +111 -0
- binal-0.1.0/src/binal/_internal/__init__.py +5 -0
- binal-0.1.0/src/binal/_internal/buffer.py +244 -0
- binal-0.1.0/src/binal/_internal/compiler.py +474 -0
- binal-0.1.0/src/binal/_internal/decoder.py +364 -0
- binal-0.1.0/src/binal/_internal/encoder.py +426 -0
- binal-0.1.0/src/binal/bits.py +8 -0
- binal-0.1.0/src/binal/checksum.py +55 -0
- binal-0.1.0/src/binal/codecs.py +39 -0
- binal-0.1.0/src/binal/collections.py +7 -0
- binal-0.1.0/src/binal/constraints.py +101 -0
- binal-0.1.0/src/binal/errors.py +141 -0
- binal-0.1.0/src/binal/fields.py +202 -0
- binal-0.1.0/src/binal/io.py +5 -0
- binal-0.1.0/src/binal/model.py +310 -0
- binal-0.1.0/src/binal/py.typed +0 -0
- binal-0.1.0/src/binal/schema.py +49 -0
- binal-0.1.0/src/binal/types.py +125 -0
binal-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: binal
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Declarative, type-safe binary modeling for Python.
|
|
5
|
+
Author: Henrik Wu
|
|
6
|
+
Author-email: Henrik Wu <295322314+oceanus403@users.noreply.github.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Requires-Python: >=3.11
|
|
9
|
+
Project-URL: Repository, https://github.com/oceanus403/binal
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
|
|
12
|
+
# Binal
|
|
13
|
+
|
|
14
|
+
Declarative, type-safe binary modeling for Python.
|
|
15
|
+
|
|
16
|
+
Binal is a pure-Python library for defining, encoding, decoding, validating, and composing binary data structures using native Python classes and type annotations.
|
|
17
|
+
|
|
18
|
+
It provides a unified binary modeling system that eliminates repetitive serialization logic, manual buffer management, offset calculations, bitwise operations, and structural validation.
|
|
19
|
+
|
|
20
|
+
The data model serves as the single source of truth for both Python objects and their binary representations.
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
|
+
|
|
24
|
+
Requires Python 3.11+.
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
uv add binal
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install binal
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Quick Start
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from typing import Annotated
|
|
38
|
+
|
|
39
|
+
from binal import BinaryModel, Prefixed, UInt8, UInt16
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Packet(BinaryModel, byte_order="big"):
|
|
43
|
+
version: UInt8
|
|
44
|
+
payload: Annotated[bytes, Prefixed(UInt16)]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
packet = Packet(version=1, payload=b"Hello")
|
|
48
|
+
data = packet.encode()
|
|
49
|
+
# b'\x01\x00\x05Hello'
|
|
50
|
+
packet = Packet.decode(data)
|
|
51
|
+
# Packet(version=1, payload=b'Hello')
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Features
|
|
55
|
+
|
|
56
|
+
- Declarative models with native type annotations
|
|
57
|
+
- Integers (including custom widths), floats, booleans, bytes, strings, and bit fields
|
|
58
|
+
- Nested models, collections, enums, and tagged unions
|
|
59
|
+
- Length-prefixed, fixed-length, null-terminated, and length-dependent fields
|
|
60
|
+
- Derived lengths, counts, and checksums (CRC32, CRC16, Adler32)
|
|
61
|
+
- Conditional and dependent fields
|
|
62
|
+
- Variable-length integers: ULEB128, SLEB128, ZigZag
|
|
63
|
+
- Schema introspection with field offsets and sizes
|
|
64
|
+
- File, buffer, stream, and asynchronous I/O
|
|
65
|
+
- Structured errors with field paths and byte offsets
|
|
66
|
+
- Zero runtime dependencies, pure Python
|
|
67
|
+
|
|
68
|
+
See the [documentation](docs/) and `examples/` for more.
|
|
69
|
+
|
|
70
|
+
## Development
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
uv sync --locked
|
|
74
|
+
uv run ruff format
|
|
75
|
+
uv run ruff check
|
|
76
|
+
uv run pyright
|
|
77
|
+
uv run pytest
|
|
78
|
+
uv run pytest --cov=binal
|
|
79
|
+
uv build
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## License
|
|
83
|
+
|
|
84
|
+
MIT. See [LICENSE](LICENSE).
|
binal-0.1.0/README.md
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# Binal
|
|
2
|
+
|
|
3
|
+
Declarative, type-safe binary modeling for Python.
|
|
4
|
+
|
|
5
|
+
Binal is a pure-Python library for defining, encoding, decoding, validating, and composing binary data structures using native Python classes and type annotations.
|
|
6
|
+
|
|
7
|
+
It provides a unified binary modeling system that eliminates repetitive serialization logic, manual buffer management, offset calculations, bitwise operations, and structural validation.
|
|
8
|
+
|
|
9
|
+
The data model serves as the single source of truth for both Python objects and their binary representations.
|
|
10
|
+
|
|
11
|
+
## Installation
|
|
12
|
+
|
|
13
|
+
Requires Python 3.11+.
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
uv add binal
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pip install binal
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Quick Start
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from typing import Annotated
|
|
27
|
+
|
|
28
|
+
from binal import BinaryModel, Prefixed, UInt8, UInt16
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Packet(BinaryModel, byte_order="big"):
|
|
32
|
+
version: UInt8
|
|
33
|
+
payload: Annotated[bytes, Prefixed(UInt16)]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
packet = Packet(version=1, payload=b"Hello")
|
|
37
|
+
data = packet.encode()
|
|
38
|
+
# b'\x01\x00\x05Hello'
|
|
39
|
+
packet = Packet.decode(data)
|
|
40
|
+
# Packet(version=1, payload=b'Hello')
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Features
|
|
44
|
+
|
|
45
|
+
- Declarative models with native type annotations
|
|
46
|
+
- Integers (including custom widths), floats, booleans, bytes, strings, and bit fields
|
|
47
|
+
- Nested models, collections, enums, and tagged unions
|
|
48
|
+
- Length-prefixed, fixed-length, null-terminated, and length-dependent fields
|
|
49
|
+
- Derived lengths, counts, and checksums (CRC32, CRC16, Adler32)
|
|
50
|
+
- Conditional and dependent fields
|
|
51
|
+
- Variable-length integers: ULEB128, SLEB128, ZigZag
|
|
52
|
+
- Schema introspection with field offsets and sizes
|
|
53
|
+
- File, buffer, stream, and asynchronous I/O
|
|
54
|
+
- Structured errors with field paths and byte offsets
|
|
55
|
+
- Zero runtime dependencies, pure Python
|
|
56
|
+
|
|
57
|
+
See the [documentation](docs/) and `examples/` for more.
|
|
58
|
+
|
|
59
|
+
## Development
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
uv sync --locked
|
|
63
|
+
uv run ruff format
|
|
64
|
+
uv run ruff check
|
|
65
|
+
uv run pyright
|
|
66
|
+
uv run pytest
|
|
67
|
+
uv run pytest --cov=binal
|
|
68
|
+
uv build
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## License
|
|
72
|
+
|
|
73
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "binal"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Declarative, type-safe binary modeling for Python."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
requires-python = ">=3.11"
|
|
8
|
+
dependencies = []
|
|
9
|
+
|
|
10
|
+
[[project.authors]]
|
|
11
|
+
name = "Henrik Wu"
|
|
12
|
+
email = "295322314+oceanus403@users.noreply.github.com"
|
|
13
|
+
|
|
14
|
+
[project.urls]
|
|
15
|
+
Repository = "https://github.com/oceanus403/binal"
|
|
16
|
+
|
|
17
|
+
[build-system]
|
|
18
|
+
requires = ["uv_build>=0.13.10,<0.14.0"]
|
|
19
|
+
build-backend = "uv_build"
|
|
20
|
+
|
|
21
|
+
[tool.ruff]
|
|
22
|
+
target-version = "py311"
|
|
23
|
+
|
|
24
|
+
[tool.pyright]
|
|
25
|
+
pythonVersion = "3.11"
|
|
26
|
+
typeCheckingMode = "strict"
|
|
27
|
+
include = ["src/binal"]
|
|
28
|
+
|
|
29
|
+
[dependency-groups]
|
|
30
|
+
dev = [
|
|
31
|
+
"hypothesis>=6.170.17",
|
|
32
|
+
"pyright>=1.1.414",
|
|
33
|
+
"pytest>=9.2.0",
|
|
34
|
+
"pytest-cov>=7.1.0",
|
|
35
|
+
"ruff>=0.17.6",
|
|
36
|
+
]
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "binal"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Declarative, type-safe binary modeling for Python."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
authors = [
|
|
8
|
+
{ name = "Henrik Wu", email = "295322314+oceanus403@users.noreply.github.com" }
|
|
9
|
+
]
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
dependencies = []
|
|
12
|
+
|
|
13
|
+
[project.urls]
|
|
14
|
+
Repository = "https://github.com/oceanus403/binal"
|
|
15
|
+
|
|
16
|
+
[build-system]
|
|
17
|
+
requires = ["uv_build>=0.13.10,<0.14.0"]
|
|
18
|
+
build-backend = "uv_build"
|
|
19
|
+
|
|
20
|
+
[tool.ruff]
|
|
21
|
+
target-version = "py311"
|
|
22
|
+
|
|
23
|
+
[tool.pyright]
|
|
24
|
+
pythonVersion = "3.11"
|
|
25
|
+
typeCheckingMode = "strict"
|
|
26
|
+
include = ["src/binal"]
|
|
27
|
+
|
|
28
|
+
[dependency-groups]
|
|
29
|
+
dev = [
|
|
30
|
+
"hypothesis>=6.170.17",
|
|
31
|
+
"pyright>=1.1.414",
|
|
32
|
+
"pytest>=9.2.0",
|
|
33
|
+
"pytest-cov>=7.1.0",
|
|
34
|
+
"ruff>=0.17.6",
|
|
35
|
+
]
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Binal: declarative, type-safe binary modeling for Python."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .bits import BitModel, Bits
|
|
6
|
+
from .checksum import CRC16, CRC32, Adler32, Checksum
|
|
7
|
+
from .codecs import Codec
|
|
8
|
+
from .collections import Array
|
|
9
|
+
from .constraints import Custom, MaxLength, MinLength, Pattern, Range
|
|
10
|
+
from .errors import BinalError, DecodeError, EncodeError, SchemaError, ValidationError
|
|
11
|
+
from .fields import (
|
|
12
|
+
Align,
|
|
13
|
+
CountOf,
|
|
14
|
+
EnumField,
|
|
15
|
+
Fixed,
|
|
16
|
+
LengthOf,
|
|
17
|
+
Magic,
|
|
18
|
+
NullTerminated,
|
|
19
|
+
Padding,
|
|
20
|
+
Prefixed,
|
|
21
|
+
Sized,
|
|
22
|
+
TaggedUnion,
|
|
23
|
+
When,
|
|
24
|
+
)
|
|
25
|
+
from .model import BinaryModel
|
|
26
|
+
from .schema import FieldInfo, Schema
|
|
27
|
+
from .types import (
|
|
28
|
+
SLEB128,
|
|
29
|
+
ULEB128,
|
|
30
|
+
Bool8,
|
|
31
|
+
Float16,
|
|
32
|
+
Float32,
|
|
33
|
+
Float64,
|
|
34
|
+
Int8,
|
|
35
|
+
Int16,
|
|
36
|
+
Int24,
|
|
37
|
+
Int32,
|
|
38
|
+
Int64,
|
|
39
|
+
Integer,
|
|
40
|
+
IntegerCodec,
|
|
41
|
+
UInt8,
|
|
42
|
+
UInt16,
|
|
43
|
+
UInt24,
|
|
44
|
+
UInt32,
|
|
45
|
+
UInt64,
|
|
46
|
+
VarInt,
|
|
47
|
+
VarUInt,
|
|
48
|
+
ZigZag32,
|
|
49
|
+
ZigZag64,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
__version__ = "0.1.0"
|
|
53
|
+
|
|
54
|
+
__all__ = [
|
|
55
|
+
"CRC16",
|
|
56
|
+
"CRC32",
|
|
57
|
+
"SLEB128",
|
|
58
|
+
"ULEB128",
|
|
59
|
+
"Adler32",
|
|
60
|
+
"Align",
|
|
61
|
+
"Array",
|
|
62
|
+
"BinalError",
|
|
63
|
+
"BinaryModel",
|
|
64
|
+
"BitModel",
|
|
65
|
+
"Bits",
|
|
66
|
+
"Bool8",
|
|
67
|
+
"Checksum",
|
|
68
|
+
"Codec",
|
|
69
|
+
"CountOf",
|
|
70
|
+
"Custom",
|
|
71
|
+
"DecodeError",
|
|
72
|
+
"EncodeError",
|
|
73
|
+
"EnumField",
|
|
74
|
+
"FieldInfo",
|
|
75
|
+
"Fixed",
|
|
76
|
+
"Float16",
|
|
77
|
+
"Float32",
|
|
78
|
+
"Float64",
|
|
79
|
+
"Int8",
|
|
80
|
+
"Int16",
|
|
81
|
+
"Int24",
|
|
82
|
+
"Int32",
|
|
83
|
+
"Int64",
|
|
84
|
+
"Integer",
|
|
85
|
+
"IntegerCodec",
|
|
86
|
+
"LengthOf",
|
|
87
|
+
"Magic",
|
|
88
|
+
"MaxLength",
|
|
89
|
+
"MinLength",
|
|
90
|
+
"NullTerminated",
|
|
91
|
+
"Padding",
|
|
92
|
+
"Pattern",
|
|
93
|
+
"Prefixed",
|
|
94
|
+
"Range",
|
|
95
|
+
"Schema",
|
|
96
|
+
"SchemaError",
|
|
97
|
+
"Sized",
|
|
98
|
+
"TaggedUnion",
|
|
99
|
+
"UInt8",
|
|
100
|
+
"UInt16",
|
|
101
|
+
"UInt24",
|
|
102
|
+
"UInt32",
|
|
103
|
+
"UInt64",
|
|
104
|
+
"ValidationError",
|
|
105
|
+
"VarInt",
|
|
106
|
+
"VarUInt",
|
|
107
|
+
"When",
|
|
108
|
+
"ZigZag32",
|
|
109
|
+
"ZigZag64",
|
|
110
|
+
"__version__",
|
|
111
|
+
]
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""Byte/bit buffer access for encoding and decoding."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import struct
|
|
6
|
+
from typing import Literal, cast
|
|
7
|
+
|
|
8
|
+
from ..errors import DecodeError
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Writer:
|
|
12
|
+
"""Append-only binary writer with bit-level support."""
|
|
13
|
+
|
|
14
|
+
def __init__(self, bit_order: str = "msb") -> None:
|
|
15
|
+
self.data = bytearray()
|
|
16
|
+
self.bit_order = bit_order
|
|
17
|
+
self._bits = 0
|
|
18
|
+
self._nbits = 0
|
|
19
|
+
|
|
20
|
+
def tell(self) -> int:
|
|
21
|
+
return len(self.data)
|
|
22
|
+
|
|
23
|
+
def flush_bits(self) -> None:
|
|
24
|
+
if self._nbits == 0:
|
|
25
|
+
return
|
|
26
|
+
if self.bit_order == "msb":
|
|
27
|
+
byte = (self._bits << (8 - self._nbits)) & 0xFF
|
|
28
|
+
else:
|
|
29
|
+
byte = self._bits & 0xFF
|
|
30
|
+
self.data.append(byte)
|
|
31
|
+
self._bits = 0
|
|
32
|
+
self._nbits = 0
|
|
33
|
+
|
|
34
|
+
def align(self, alignment: int) -> None:
|
|
35
|
+
self.flush_bits()
|
|
36
|
+
while len(self.data) % alignment != 0:
|
|
37
|
+
self.data.append(0)
|
|
38
|
+
|
|
39
|
+
def write_bytes(self, value: bytes) -> None:
|
|
40
|
+
self.flush_bits()
|
|
41
|
+
self.data.extend(value)
|
|
42
|
+
|
|
43
|
+
def write_bits(self, value: int, width: int) -> None:
|
|
44
|
+
if width == 0:
|
|
45
|
+
return
|
|
46
|
+
mask = (1 << width) - 1
|
|
47
|
+
value &= mask
|
|
48
|
+
if self.bit_order == "msb":
|
|
49
|
+
self._bits = (self._bits << width) | value
|
|
50
|
+
self._nbits += width
|
|
51
|
+
while self._nbits >= 8:
|
|
52
|
+
shift = self._nbits - 8
|
|
53
|
+
self.data.append((self._bits >> shift) & 0xFF)
|
|
54
|
+
self._bits &= (1 << shift) - 1 if shift else 0
|
|
55
|
+
self._nbits -= 8
|
|
56
|
+
else:
|
|
57
|
+
self._bits |= value << self._nbits
|
|
58
|
+
self._nbits += width
|
|
59
|
+
while self._nbits >= 8:
|
|
60
|
+
self.data.append(self._bits & 0xFF)
|
|
61
|
+
self._bits >>= 8
|
|
62
|
+
self._nbits -= 8
|
|
63
|
+
|
|
64
|
+
def write_int(self, value: int, bits: int, signed: bool, byte_order: str) -> None:
|
|
65
|
+
if bits % 8 == 0:
|
|
66
|
+
self.flush_bits()
|
|
67
|
+
nbytes = bits // 8
|
|
68
|
+
try:
|
|
69
|
+
self.data.extend(
|
|
70
|
+
value.to_bytes(
|
|
71
|
+
nbytes,
|
|
72
|
+
cast(Literal["big", "little"], byte_order),
|
|
73
|
+
signed=signed,
|
|
74
|
+
)
|
|
75
|
+
)
|
|
76
|
+
except OverflowError as exc:
|
|
77
|
+
raise ValueError(
|
|
78
|
+
f"integer {value} does not fit in {bits} bits"
|
|
79
|
+
) from exc
|
|
80
|
+
else:
|
|
81
|
+
self.write_bits(value, bits)
|
|
82
|
+
|
|
83
|
+
def write_float(self, value: float, bits: int, byte_order: str) -> None:
|
|
84
|
+
self.flush_bits()
|
|
85
|
+
fmt_char = {16: "e", 32: "f", 64: "d"}[bits]
|
|
86
|
+
prefix = ">" if byte_order == "big" else "<"
|
|
87
|
+
self.data.extend(struct.pack(f"{prefix}{fmt_char}", value))
|
|
88
|
+
|
|
89
|
+
def write_varint(self, value: int, kind: str, zigzag: bool) -> None:
|
|
90
|
+
self.flush_bits()
|
|
91
|
+
if zigzag:
|
|
92
|
+
value = (value << 1) ^ (value >> 63)
|
|
93
|
+
if kind == "sleb128":
|
|
94
|
+
# Signed LEB128.
|
|
95
|
+
more = True
|
|
96
|
+
v = value
|
|
97
|
+
while more:
|
|
98
|
+
byte = v & 0x7F
|
|
99
|
+
v >>= 7
|
|
100
|
+
sign_bit = byte & 0x40
|
|
101
|
+
if (v == 0 and not sign_bit) or (v == -1 and sign_bit):
|
|
102
|
+
more = False
|
|
103
|
+
else:
|
|
104
|
+
byte |= 0x80
|
|
105
|
+
self.data.append(byte)
|
|
106
|
+
return
|
|
107
|
+
# ULEB128 (unsigned, also used for zigzag-encoded values).
|
|
108
|
+
if value < 0:
|
|
109
|
+
raise ValueError("ULEB128 cannot encode negative values")
|
|
110
|
+
v = value
|
|
111
|
+
while True:
|
|
112
|
+
byte = v & 0x7F
|
|
113
|
+
v >>= 7
|
|
114
|
+
if v:
|
|
115
|
+
self.data.append(byte | 0x80)
|
|
116
|
+
else:
|
|
117
|
+
self.data.append(byte)
|
|
118
|
+
break
|
|
119
|
+
|
|
120
|
+
def bytes(self) -> bytes:
|
|
121
|
+
self.flush_bits()
|
|
122
|
+
return bytes(self.data)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class Reader:
|
|
126
|
+
"""Sequential binary reader with bit-level support."""
|
|
127
|
+
|
|
128
|
+
def __init__(
|
|
129
|
+
self, data: bytes | bytearray | memoryview, bit_order: str = "msb"
|
|
130
|
+
) -> None:
|
|
131
|
+
self.data = bytes(data)
|
|
132
|
+
self.pos = 0
|
|
133
|
+
self.bit_order = bit_order
|
|
134
|
+
self._bit_byte = 0
|
|
135
|
+
self._bit_pos = 0 # bits already consumed in _bit_byte (0-7)
|
|
136
|
+
|
|
137
|
+
def remaining(self) -> int:
|
|
138
|
+
if self._bit_pos:
|
|
139
|
+
return len(self.data) - self.pos - 1
|
|
140
|
+
return len(self.data) - self.pos
|
|
141
|
+
|
|
142
|
+
def offset(self) -> int:
|
|
143
|
+
return self.pos
|
|
144
|
+
|
|
145
|
+
def bytes_consumed(self) -> int:
|
|
146
|
+
return self.pos + (1 if self._bit_pos else 0)
|
|
147
|
+
|
|
148
|
+
def _ensure(self, n: int, path: str = "") -> None:
|
|
149
|
+
if self.remaining() < n:
|
|
150
|
+
raise DecodeError(
|
|
151
|
+
"Unexpected end of input",
|
|
152
|
+
path=path,
|
|
153
|
+
offset=self.pos,
|
|
154
|
+
expected=n,
|
|
155
|
+
available=self.remaining(),
|
|
156
|
+
reason="Unexpected end of input",
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
def align_byte(self) -> None:
|
|
160
|
+
if self._bit_pos:
|
|
161
|
+
self.pos += 1
|
|
162
|
+
self._bit_pos = 0
|
|
163
|
+
|
|
164
|
+
def read_bytes(self, n: int, path: str = "") -> bytes:
|
|
165
|
+
self.align_byte()
|
|
166
|
+
self._ensure(n, path)
|
|
167
|
+
chunk = self.data[self.pos : self.pos + n]
|
|
168
|
+
self.pos += n
|
|
169
|
+
return chunk
|
|
170
|
+
|
|
171
|
+
def read_byte(self, path: str = "") -> int:
|
|
172
|
+
return self.read_bytes(1, path)[0]
|
|
173
|
+
|
|
174
|
+
def read_bits(self, width: int, path: str = "") -> int:
|
|
175
|
+
if width == 0:
|
|
176
|
+
return 0
|
|
177
|
+
result = 0
|
|
178
|
+
bits_read = 0
|
|
179
|
+
while bits_read < width:
|
|
180
|
+
if self._bit_pos == 0:
|
|
181
|
+
self._ensure(1, path)
|
|
182
|
+
self._bit_byte = self.data[self.pos]
|
|
183
|
+
avail = 8 - self._bit_pos
|
|
184
|
+
take = min(avail, width - bits_read)
|
|
185
|
+
if self.bit_order == "msb":
|
|
186
|
+
shift = 8 - self._bit_pos - take
|
|
187
|
+
chunk = (self._bit_byte >> shift) & ((1 << take) - 1)
|
|
188
|
+
result = (result << take) | chunk
|
|
189
|
+
else:
|
|
190
|
+
chunk = (self._bit_byte >> self._bit_pos) & ((1 << take) - 1)
|
|
191
|
+
result |= chunk << bits_read
|
|
192
|
+
self._bit_pos += take
|
|
193
|
+
bits_read += take
|
|
194
|
+
if self._bit_pos == 8:
|
|
195
|
+
self.pos += 1
|
|
196
|
+
self._bit_pos = 0
|
|
197
|
+
return result
|
|
198
|
+
|
|
199
|
+
def read_int(self, bits: int, signed: bool, byte_order: str, path: str = "") -> int:
|
|
200
|
+
if bits % 8 == 0:
|
|
201
|
+
raw = self.read_bytes(bits // 8, path)
|
|
202
|
+
return int.from_bytes(
|
|
203
|
+
raw, cast(Literal["big", "little"], byte_order), signed=signed
|
|
204
|
+
)
|
|
205
|
+
value = self.read_bits(bits, path)
|
|
206
|
+
if signed and value & (1 << (bits - 1)):
|
|
207
|
+
value -= 1 << bits
|
|
208
|
+
return value
|
|
209
|
+
|
|
210
|
+
def read_float(self, bits: int, byte_order: str, path: str = "") -> float:
|
|
211
|
+
fmt_char = {16: "e", 32: "f", 64: "d"}[bits]
|
|
212
|
+
prefix = ">" if byte_order == "big" else "<"
|
|
213
|
+
size = bits // 8
|
|
214
|
+
raw = self.read_bytes(size, path)
|
|
215
|
+
return float(struct.unpack(f"{prefix}{fmt_char}", raw)[0])
|
|
216
|
+
|
|
217
|
+
def read_varint(self, kind: str, zigzag: bool, path: str = "") -> int:
|
|
218
|
+
if kind == "sleb128":
|
|
219
|
+
result = 0
|
|
220
|
+
shift = 0
|
|
221
|
+
while True:
|
|
222
|
+
byte = self.read_byte(path)
|
|
223
|
+
result |= (byte & 0x7F) << shift
|
|
224
|
+
shift += 7
|
|
225
|
+
if not (byte & 0x80):
|
|
226
|
+
if byte & 0x40:
|
|
227
|
+
result |= -(1 << shift)
|
|
228
|
+
break
|
|
229
|
+
return result
|
|
230
|
+
# ULEB128.
|
|
231
|
+
result = 0
|
|
232
|
+
shift = 0
|
|
233
|
+
while True:
|
|
234
|
+
byte = self.read_byte(path)
|
|
235
|
+
result |= (byte & 0x7F) << shift
|
|
236
|
+
shift += 7
|
|
237
|
+
if not (byte & 0x80):
|
|
238
|
+
break
|
|
239
|
+
if zigzag:
|
|
240
|
+
return (result >> 1) ^ -(result & 1)
|
|
241
|
+
return result
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
__all__ = ["Reader", "Writer"]
|