bread-format 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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,107 @@
1
+ Metadata-Version: 2.4
2
+ Name: bread-format
3
+ Version: 0.1.0
4
+ Summary: Reads .bread files: triangle meshes kept bit for bit, and the scene that places them.
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://bread.synrgs.tech
7
+ Project-URL: Specification, https://github.com/breadslicer-app/bread-format/blob/main/SPEC.md
8
+ Project-URL: Source, https://github.com/breadslicer-app/bread-format/tree/main/python
9
+ Project-URL: Issues, https://github.com/breadslicer-app/bread-format/issues
10
+ Keywords: 3d,mesh,stl,3d-printing,resin,file-format,bread
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Operating System :: OS Independent
21
+ Classifier: Topic :: File Formats
22
+ Classifier: Topic :: Multimedia :: Graphics :: 3D Rendering
23
+ Classifier: Topic :: Multimedia :: Graphics :: 3D Modeling
24
+ Requires-Python: >=3.10
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Requires-Dist: zstandard>=0.23; python_version < "3.14"
28
+ Dynamic: license-file
29
+
30
+ # bread-format for Python
31
+
32
+ Reads `.bread` files: triangle meshes, kept bit for bit, and the scene that places them.
33
+
34
+ This reader is written from the specification alone,
35
+ [`SPEC.md`](https://github.com/breadslicer-app/bread-format/blob/main/SPEC.md), without the code of
36
+ the reference implementation. It reads every conformance file the way the reference reader does,
37
+ which shows that the specification is enough to read the format. Being plain Python, it is also
38
+ meant to be read, and to be a starting point for importing `.bread` into other programs.
39
+
40
+ ## Install
41
+
42
+ ```text
43
+ pip install bread-format
44
+ ```
45
+
46
+ It needs Python 3.10 or later. On Python 3.14 and later it uses nothing but the standard library,
47
+ whose `compression.zstd` decompresses the chunks; before 3.14, pip also installs the `zstandard`
48
+ package for that.
49
+
50
+ ## Use
51
+
52
+ ```python
53
+ from bread_format import BreadError, read_file
54
+
55
+ with open("model.bread", "rb") as f:
56
+ bread = read_file(f.read())
57
+
58
+ for leaf, mesh, transform in bread.placements():
59
+ node = bread.scene.nodes[leaf]
60
+ print(node.meta and node.meta.name, mesh.vertex_count, mesh.triangle_count)
61
+ ```
62
+
63
+ `read_file` returns a `BreadFile`:
64
+
65
+ | Field | What it holds |
66
+ |---|---|
67
+ | `scene` | the scene: `nodes`, `roots`, `subtrees`, `mesh_resources`, and its `meta` |
68
+ | `meshes` | one `Mesh` per `MESH` chunk, in file order |
69
+ | `settings` | the `PROJ` payload, a TOML document, or `None` |
70
+ | `thumbnail` | the `THMB` payload, a PNG, or `None` |
71
+ | `supports`, `hollows` | the `SUPP` and `HOLW` entries |
72
+ | `support_previews` | each support leaf with a preview, mapped to its mesh |
73
+ | `surface` | the `SURF` entries; `entry.values(mesh)` gives the paint of each triangle |
74
+ | `metadata` | the `META` entries a reader keeps: each has `node` (`None` for the whole file), `key` and `value`, and `text` or `uuid` for the registered keys |
75
+ | `roles` | the `ROLE` entries: each `leaf` that is not a model, and its `role`, `1` supports or `2` a raft (`is_known` is false for a reserved role, which means a model) |
76
+
77
+ A `Mesh` keeps its vertices as the bits of their `f32` coordinates, so that every one comes back
78
+ exactly, NaN payloads included:
79
+
80
+ - `mesh.vertex_bytes()` and `mesh.triangle_bytes()` give them as little-endian `f32` and `u32`,
81
+ ready for an array library: `numpy.frombuffer(mesh.vertex_bytes(), "<f4").reshape(-1, 3)`;
82
+ - `mesh.positions()` gives each vertex as three Python floats.
83
+
84
+ `placements()` walks the scene from each root (SPEC 5.4) and gives every leaf shown, its mesh and
85
+ its world transform, a 3 × 3 matrix and a translation in `f64`. `apply(transform, point)` places a
86
+ point.
87
+
88
+ Lengths are millimetres, with Z up (SPEC 3.5).
89
+
90
+ When a file is refused, `read_file` raises `BreadError`, whose `reason` is one of the reason codes
91
+ of [`conformance/README.md`](https://github.com/breadslicer-app/bread-format/blob/main/conformance/README.md), such as `"crc"` or `"malformed"`, and
92
+ whose `chunk` names the chunk at fault.
93
+
94
+ ## Speed
95
+
96
+ The reader favours being easy to follow over being fast: a mesh of 2 million triangles takes about
97
+ half a minute. For speed, use the reference implementation, the `bread-format` Rust crate.
98
+
99
+ ## Tests
100
+
101
+ ```text
102
+ python -m unittest discover -s tests
103
+ ```
104
+
105
+ run from this folder with `src` on `PYTHONPATH`, or after `pip install -e .`. They read every file
106
+ in [`conformance/`](https://github.com/breadslicer-app/bread-format/tree/main/conformance), so they
107
+ run from a clone of the repository.
@@ -0,0 +1,78 @@
1
+ # bread-format for Python
2
+
3
+ Reads `.bread` files: triangle meshes, kept bit for bit, and the scene that places them.
4
+
5
+ This reader is written from the specification alone,
6
+ [`SPEC.md`](https://github.com/breadslicer-app/bread-format/blob/main/SPEC.md), without the code of
7
+ the reference implementation. It reads every conformance file the way the reference reader does,
8
+ which shows that the specification is enough to read the format. Being plain Python, it is also
9
+ meant to be read, and to be a starting point for importing `.bread` into other programs.
10
+
11
+ ## Install
12
+
13
+ ```text
14
+ pip install bread-format
15
+ ```
16
+
17
+ It needs Python 3.10 or later. On Python 3.14 and later it uses nothing but the standard library,
18
+ whose `compression.zstd` decompresses the chunks; before 3.14, pip also installs the `zstandard`
19
+ package for that.
20
+
21
+ ## Use
22
+
23
+ ```python
24
+ from bread_format import BreadError, read_file
25
+
26
+ with open("model.bread", "rb") as f:
27
+ bread = read_file(f.read())
28
+
29
+ for leaf, mesh, transform in bread.placements():
30
+ node = bread.scene.nodes[leaf]
31
+ print(node.meta and node.meta.name, mesh.vertex_count, mesh.triangle_count)
32
+ ```
33
+
34
+ `read_file` returns a `BreadFile`:
35
+
36
+ | Field | What it holds |
37
+ |---|---|
38
+ | `scene` | the scene: `nodes`, `roots`, `subtrees`, `mesh_resources`, and its `meta` |
39
+ | `meshes` | one `Mesh` per `MESH` chunk, in file order |
40
+ | `settings` | the `PROJ` payload, a TOML document, or `None` |
41
+ | `thumbnail` | the `THMB` payload, a PNG, or `None` |
42
+ | `supports`, `hollows` | the `SUPP` and `HOLW` entries |
43
+ | `support_previews` | each support leaf with a preview, mapped to its mesh |
44
+ | `surface` | the `SURF` entries; `entry.values(mesh)` gives the paint of each triangle |
45
+ | `metadata` | the `META` entries a reader keeps: each has `node` (`None` for the whole file), `key` and `value`, and `text` or `uuid` for the registered keys |
46
+ | `roles` | the `ROLE` entries: each `leaf` that is not a model, and its `role`, `1` supports or `2` a raft (`is_known` is false for a reserved role, which means a model) |
47
+
48
+ A `Mesh` keeps its vertices as the bits of their `f32` coordinates, so that every one comes back
49
+ exactly, NaN payloads included:
50
+
51
+ - `mesh.vertex_bytes()` and `mesh.triangle_bytes()` give them as little-endian `f32` and `u32`,
52
+ ready for an array library: `numpy.frombuffer(mesh.vertex_bytes(), "<f4").reshape(-1, 3)`;
53
+ - `mesh.positions()` gives each vertex as three Python floats.
54
+
55
+ `placements()` walks the scene from each root (SPEC 5.4) and gives every leaf shown, its mesh and
56
+ its world transform, a 3 × 3 matrix and a translation in `f64`. `apply(transform, point)` places a
57
+ point.
58
+
59
+ Lengths are millimetres, with Z up (SPEC 3.5).
60
+
61
+ When a file is refused, `read_file` raises `BreadError`, whose `reason` is one of the reason codes
62
+ of [`conformance/README.md`](https://github.com/breadslicer-app/bread-format/blob/main/conformance/README.md), such as `"crc"` or `"malformed"`, and
63
+ whose `chunk` names the chunk at fault.
64
+
65
+ ## Speed
66
+
67
+ The reader favours being easy to follow over being fast: a mesh of 2 million triangles takes about
68
+ half a minute. For speed, use the reference implementation, the `bread-format` Rust crate.
69
+
70
+ ## Tests
71
+
72
+ ```text
73
+ python -m unittest discover -s tests
74
+ ```
75
+
76
+ run from this folder with `src` on `PYTHONPATH`, or after `pip install -e .`. They read every file
77
+ in [`conformance/`](https://github.com/breadslicer-app/bread-format/tree/main/conformance), so they
78
+ run from a clone of the repository.
@@ -0,0 +1,42 @@
1
+ # SPDX-FileCopyrightText: 2026 SynrgStudio
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ [build-system]
5
+ requires = ["setuptools>=77"]
6
+ build-backend = "setuptools.build_meta"
7
+
8
+ [project]
9
+ name = "bread-format"
10
+ version = "0.1.0"
11
+ description = "Reads .bread files: triangle meshes kept bit for bit, and the scene that places them."
12
+ readme = "README.md"
13
+ requires-python = ">=3.10"
14
+ license = "Apache-2.0"
15
+ license-files = ["LICENSE"]
16
+ # Zstandard is in the standard library from Python 3.14 (compression.zstd).
17
+ dependencies = ['zstandard >= 0.23; python_version < "3.14"']
18
+ keywords = ["3d", "mesh", "stl", "3d-printing", "resin", "file-format", "bread"]
19
+ classifiers = [
20
+ "Development Status :: 3 - Alpha",
21
+ "Intended Audience :: Developers",
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3 :: Only",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ "Programming Language :: Python :: 3.13",
28
+ "Programming Language :: Python :: 3.14",
29
+ "Operating System :: OS Independent",
30
+ "Topic :: File Formats",
31
+ "Topic :: Multimedia :: Graphics :: 3D Rendering",
32
+ "Topic :: Multimedia :: Graphics :: 3D Modeling",
33
+ ]
34
+
35
+ [project.urls]
36
+ Homepage = "https://bread.synrgs.tech"
37
+ Specification = "https://github.com/breadslicer-app/bread-format/blob/main/SPEC.md"
38
+ Source = "https://github.com/breadslicer-app/bread-format/tree/main/python"
39
+ Issues = "https://github.com/breadslicer-app/bread-format/issues"
40
+
41
+ [tool.setuptools.packages.find]
42
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,44 @@
1
+ # SPDX-FileCopyrightText: 2026 SynrgStudio
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Reads .bread files: triangle meshes, kept bit for bit, and the scene that
5
+ places them.
6
+
7
+ Written from the specification alone (SPEC.md), with the Python standard
8
+ library only, as a second reader of the format::
9
+
10
+ from bread_format import read_file
11
+
12
+ with open("model.bread", "rb") as f:
13
+ bread = read_file(f.read())
14
+ for leaf, mesh, transform in bread.placements():
15
+ ...
16
+ """
17
+
18
+ from ._bytes import Meta
19
+ from .errors import BreadError
20
+ from .file import BreadFile, read_file
21
+ from .mesh import Mesh, read_mesh
22
+ from .metadata import MetaEntry
23
+ from .scene import IDENTITY, Node, Scene, Transform, apply, compose
24
+ from .slicer import Entry, Paint, Role, fingerprint_of
25
+
26
+ __all__ = [
27
+ "IDENTITY",
28
+ "BreadError",
29
+ "BreadFile",
30
+ "Entry",
31
+ "Mesh",
32
+ "Meta",
33
+ "MetaEntry",
34
+ "Node",
35
+ "Paint",
36
+ "Role",
37
+ "Scene",
38
+ "Transform",
39
+ "apply",
40
+ "compose",
41
+ "fingerprint_of",
42
+ "read_file",
43
+ "read_mesh",
44
+ ]
@@ -0,0 +1,127 @@
1
+ # SPDX-FileCopyrightText: 2026 SynrgStudio
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Reading payload fields (SPEC 3.1 to 3.3) and bit streams (SPEC 6.6)."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import struct
9
+ from dataclasses import dataclass
10
+
11
+ from .errors import Malformed
12
+
13
+ _U16 = struct.Struct("<H")
14
+ _U32 = struct.Struct("<I")
15
+ _U64 = struct.Struct("<Q")
16
+ _F64 = struct.Struct("<d")
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Meta:
21
+ """A name and a comment, each a string or None (SPEC 5.1, 6.2)."""
22
+
23
+ name: str | None
24
+ comment: str | None
25
+
26
+
27
+ class Fields:
28
+ """Reads the fields of one payload, in order.
29
+
30
+ Every read past the end raises Malformed, and so does ``end`` when bytes
31
+ are left: a payload that is cut short or padded is malformed (SPEC 3.3).
32
+ """
33
+
34
+ def __init__(self, data: bytes | memoryview) -> None:
35
+ self._data = memoryview(data)
36
+ self._pos = 0
37
+
38
+ def left(self) -> int:
39
+ return len(self._data) - self._pos
40
+
41
+ def take(self, n: int) -> memoryview:
42
+ if n > self.left():
43
+ raise Malformed
44
+ out = self._data[self._pos : self._pos + n]
45
+ self._pos += n
46
+ return out
47
+
48
+ def u8(self) -> int:
49
+ return self.take(1)[0]
50
+
51
+ def u16(self) -> int:
52
+ return _U16.unpack(self.take(2))[0]
53
+
54
+ def u32(self) -> int:
55
+ return _U32.unpack(self.take(4))[0]
56
+
57
+ def u64(self) -> int:
58
+ return _U64.unpack(self.take(8))[0]
59
+
60
+ def f64(self) -> float:
61
+ return _F64.unpack(self.take(8))[0]
62
+
63
+ def flag(self) -> bool:
64
+ value = self.u8()
65
+ if value > 1:
66
+ raise Malformed
67
+ return value == 1
68
+
69
+ def count(self, at_least: int) -> int:
70
+ """A count of items that take at least ``at_least`` bytes each,
71
+ checked against the bytes left before anything is allocated for it."""
72
+ n = self.u32()
73
+ if n > self.left() // at_least:
74
+ raise Malformed
75
+ return n
76
+
77
+ def byte_string(self) -> memoryview:
78
+ return self.take(self.u32())
79
+
80
+ def text(self) -> str:
81
+ try:
82
+ return str(self.byte_string(), "utf-8")
83
+ except UnicodeDecodeError:
84
+ raise Malformed from None
85
+
86
+ def optional_text(self) -> str | None:
87
+ return self.text() if self.flag() else None
88
+
89
+ def meta(self) -> Meta | None:
90
+ """A *has metadata* flag, then a name and a comment when it is set."""
91
+ if not self.flag():
92
+ return None
93
+ return Meta(self.optional_text(), self.optional_text())
94
+
95
+ def end(self) -> None:
96
+ if self.left():
97
+ raise Malformed
98
+
99
+
100
+ class Bits:
101
+ """Reads a bit stream (SPEC 6.6): values packed least significant bit
102
+ first. ``end`` checks that the stream is exactly as long as the bits read
103
+ need, with the unused bits of its last byte at 0."""
104
+
105
+ def __init__(self, data: bytes | memoryview) -> None:
106
+ self._data = bytes(data)
107
+ self._pos = 0
108
+
109
+ def read(self, n: int) -> int:
110
+ value = 0
111
+ got = 0
112
+ while got < n:
113
+ index = self._pos >> 3
114
+ if index >= len(self._data):
115
+ raise Malformed
116
+ shift = self._pos & 7
117
+ width = min(8 - shift, n - got)
118
+ value |= ((self._data[index] >> shift) & ((1 << width) - 1)) << got
119
+ got += width
120
+ self._pos += width
121
+ return value
122
+
123
+ def end(self) -> None:
124
+ if len(self._data) != (self._pos + 7) >> 3:
125
+ raise Malformed
126
+ if self._pos & 7 and self._data[-1] >> (self._pos & 7):
127
+ raise Malformed