kaitaistruct 2.0.0a1__py3-none-any.whl
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.
- kaitaistruct-2.0.0a1.dist-info/METADATA +53 -0
- kaitaistruct-2.0.0a1.dist-info/RECORD +7 -0
- kaitaistruct-2.0.0a1.dist-info/WHEEL +5 -0
- kaitaistruct-2.0.0a1.dist-info/licenses/LICENSE +21 -0
- kaitaistruct-2.0.0a1.dist-info/top_level.txt +1 -0
- kaitaistruct-2.0.0a1.dist-info/zip-safe +1 -0
- kaitaistruct.py +1259 -0
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: kaitaistruct
|
|
3
|
+
Version: 2.0.0a1
|
|
4
|
+
Summary: Kaitai Struct declarative parser generator for binary data: runtime library for Python
|
|
5
|
+
Home-page: https://kaitai.io
|
|
6
|
+
Author: Kaitai Project
|
|
7
|
+
Author-email: greycat@kaitai.io
|
|
8
|
+
License: MIT
|
|
9
|
+
Project-URL: Documentation, https://doc.kaitai.io/
|
|
10
|
+
Project-URL: Code, https://github.com/kaitai-io/kaitai_struct_python_runtime
|
|
11
|
+
Project-URL: Issues, https://github.com/kaitai-io/kaitai_struct_python_runtime/issues
|
|
12
|
+
Project-URL: Gitter, https://gitter.im/kaitai_struct/Lobby
|
|
13
|
+
Keywords: kaitai,struct,construct,ksy,declarative,data structure,data format,file format,packet format,binary,parser,parsing,unpack,development
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Topic :: Software Development :: Build Tools
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
26
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
27
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
28
|
+
Requires-Python: >=3.8
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
License-File: LICENSE
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
|
|
33
|
+
# Kaitai Struct: runtime library for Python
|
|
34
|
+
|
|
35
|
+
[](https://pypi.org/project/kaitaistruct/)
|
|
36
|
+
[](https://pypi.org/project/kaitaistruct/#:~:text=Programming%20Language)
|
|
37
|
+
|
|
38
|
+
This library implements Kaitai Struct API for Python.
|
|
39
|
+
|
|
40
|
+
[Kaitai Struct](https://kaitai.io/) is a declarative language used for
|
|
41
|
+
describe various binary data structures, laid out in files or in memory:
|
|
42
|
+
i.e. binary file formats, network stream packet formats, etc.
|
|
43
|
+
|
|
44
|
+
It is similar to [Python's Construct 2.10](https://construct.readthedocs.io/en/latest/)
|
|
45
|
+
but it is language-agnostic. The format description is done in YAML-based .ksy
|
|
46
|
+
format, which then can be compiled into a wide range of target languages.
|
|
47
|
+
|
|
48
|
+
Further reading:
|
|
49
|
+
|
|
50
|
+
* [About Kaitai Struct](https://kaitai.io/)
|
|
51
|
+
* [About API implemented in this library](https://doc.kaitai.io/stream_api.html)
|
|
52
|
+
* [Python-specific notes](https://doc.kaitai.io/lang_python.html) in KS
|
|
53
|
+
documentation discuss installation and usage of this runtime
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
kaitaistruct.py,sha256=HFVCyYwjg1qEMhSvAqZU2dYN0PCPUokRn7BXyI_Zd40,41233
|
|
2
|
+
kaitaistruct-2.0.0a1.dist-info/licenses/LICENSE,sha256=btTYVQNchTHao78GFEo0O73bzwDWqwa53j5DUKp3E28,1076
|
|
3
|
+
kaitaistruct-2.0.0a1.dist-info/METADATA,sha256=BO_696w1DaNQrze6OVJHfCDtOHi8hOJFSh15YHkY61Y,2588
|
|
4
|
+
kaitaistruct-2.0.0a1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
kaitaistruct-2.0.0a1.dist-info/top_level.txt,sha256=qdyEoUwMYARmrbnrV-SRnz3b0yjs0xR_P-r5FrNW_QY,13
|
|
6
|
+
kaitaistruct-2.0.0a1.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
7
|
+
kaitaistruct-2.0.0a1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2015-2026 Kaitai Project
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
kaitaistruct
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
kaitaistruct.py
ADDED
|
@@ -0,0 +1,1259 @@
|
|
|
1
|
+
import itertools
|
|
2
|
+
import struct
|
|
3
|
+
import warnings
|
|
4
|
+
from contextlib import suppress
|
|
5
|
+
from io import SEEK_CUR, SEEK_END, SEEK_SET, BufferedIOBase, BytesIO
|
|
6
|
+
|
|
7
|
+
# Kaitai Struct runtime version, in the format defined by PEP 440.
|
|
8
|
+
# Used by our setup.cfg to set the version number in
|
|
9
|
+
# packaging/distribution metadata.
|
|
10
|
+
# Also used in Python code generated by older ksc versions (0.7 through 0.9)
|
|
11
|
+
# to check that the imported runtime is compatible with the generated code.
|
|
12
|
+
# Since ksc 0.10, the compatibility check instead uses the API_VERSION constant,
|
|
13
|
+
# so that the version string does not need to be parsed at runtime
|
|
14
|
+
# (see https://github.com/kaitai-io/kaitai_struct/issues/804).
|
|
15
|
+
__version__ = "2.0.0a1"
|
|
16
|
+
|
|
17
|
+
# Kaitai Struct runtime API version, as a tuple of ints.
|
|
18
|
+
# Used in generated Python code (since ksc 0.10) to check that the imported
|
|
19
|
+
# runtime is compatible with the generated code.
|
|
20
|
+
API_VERSION = (2, 0)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class KaitaiStruct:
|
|
24
|
+
def __init__(self, io):
|
|
25
|
+
self._io = io
|
|
26
|
+
|
|
27
|
+
def __enter__(self):
|
|
28
|
+
return self
|
|
29
|
+
|
|
30
|
+
def __exit__(self, *args, **kwargs):
|
|
31
|
+
self.close()
|
|
32
|
+
|
|
33
|
+
def close(self):
|
|
34
|
+
self._io.close()
|
|
35
|
+
|
|
36
|
+
@classmethod
|
|
37
|
+
def from_file(cls, filename):
|
|
38
|
+
# NOTE: we cannot use the `with` statement because KaitaiStream needs a
|
|
39
|
+
# file descriptor that remains open and takes care of closing it itself.
|
|
40
|
+
# Therefore, we're suppressing Ruff's rule
|
|
41
|
+
# [SIM115](https://docs.astral.sh/ruff/rules/open-file-with-context-handler/).
|
|
42
|
+
#
|
|
43
|
+
# We also won't use `pathlib` here (so we're suppressing
|
|
44
|
+
# [PTH123](https://docs.astral.sh/ruff/rules/builtin-open/)), because
|
|
45
|
+
# `filename` is traditionally expected to be a string.
|
|
46
|
+
f = open(filename, "rb") # noqa: SIM115, PTH123
|
|
47
|
+
try:
|
|
48
|
+
return cls(KaitaiStream(f))
|
|
49
|
+
except Exception:
|
|
50
|
+
# close file descriptor, then reraise the exception
|
|
51
|
+
f.close()
|
|
52
|
+
raise
|
|
53
|
+
|
|
54
|
+
@classmethod
|
|
55
|
+
def from_bytes(cls, buf):
|
|
56
|
+
return cls(KaitaiStream(BytesIO(buf)))
|
|
57
|
+
|
|
58
|
+
@classmethod
|
|
59
|
+
def from_io(cls, io):
|
|
60
|
+
return cls(KaitaiStream(io))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class ReadWriteKaitaiStruct(KaitaiStruct):
|
|
64
|
+
def __init__(self, io):
|
|
65
|
+
super().__init__(io)
|
|
66
|
+
self._dirty = True
|
|
67
|
+
|
|
68
|
+
def _fetch_instances(self):
|
|
69
|
+
raise NotImplementedError
|
|
70
|
+
|
|
71
|
+
def _write(self, io=None):
|
|
72
|
+
self._write__seq(io)
|
|
73
|
+
self._fetch_instances()
|
|
74
|
+
self._io.write_back_child_streams()
|
|
75
|
+
|
|
76
|
+
def _write__seq(self, io):
|
|
77
|
+
if io is not None:
|
|
78
|
+
self._io = io
|
|
79
|
+
if self._dirty:
|
|
80
|
+
raise ConsistencyNotCheckedError
|
|
81
|
+
|
|
82
|
+
def __setattr__(self, key, value):
|
|
83
|
+
super_setattr = super().__setattr__
|
|
84
|
+
if (
|
|
85
|
+
not key.startswith("_")
|
|
86
|
+
or key in {"_parent", "_root"}
|
|
87
|
+
or key.startswith("_unnamed")
|
|
88
|
+
):
|
|
89
|
+
# NOTE: `__setattr__()` parameters are positional-only, which the FBT003
|
|
90
|
+
# rule doesn't know, see https://github.com/astral-sh/ruff/issues/3247
|
|
91
|
+
super_setattr("_dirty", True) # noqa: FBT003
|
|
92
|
+
super_setattr(key, value)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class SubIO(BufferedIOBase):
|
|
96
|
+
def __init__(self, parent_io, parent_start, size):
|
|
97
|
+
self.parent_io = parent_io
|
|
98
|
+
self.parent_start = parent_start
|
|
99
|
+
self.size = size
|
|
100
|
+
self._pos = 0
|
|
101
|
+
|
|
102
|
+
def readable(self):
|
|
103
|
+
self._checkClosed()
|
|
104
|
+
return True
|
|
105
|
+
|
|
106
|
+
def seekable(self):
|
|
107
|
+
self._checkClosed()
|
|
108
|
+
return True
|
|
109
|
+
|
|
110
|
+
def writable(self):
|
|
111
|
+
self._checkClosed()
|
|
112
|
+
# NOTE: `SubIO` only supports reading for now
|
|
113
|
+
return False
|
|
114
|
+
|
|
115
|
+
def seek(self, offset, whence=SEEK_SET, /):
|
|
116
|
+
if not isinstance(offset, int):
|
|
117
|
+
msg = (
|
|
118
|
+
f"'{type(offset).__name__}' object cannot be interpreted as an integer"
|
|
119
|
+
)
|
|
120
|
+
raise TypeError(msg)
|
|
121
|
+
|
|
122
|
+
self._checkClosed()
|
|
123
|
+
|
|
124
|
+
if whence == SEEK_SET:
|
|
125
|
+
if offset < 0:
|
|
126
|
+
msg = f"negative seek value {offset}"
|
|
127
|
+
raise ValueError(msg)
|
|
128
|
+
self._pos = offset
|
|
129
|
+
elif whence == SEEK_CUR:
|
|
130
|
+
self._pos += offset
|
|
131
|
+
elif whence == SEEK_END:
|
|
132
|
+
self._pos = self.size + offset
|
|
133
|
+
else:
|
|
134
|
+
msg = f"invalid whence ({whence}, should be 0, 1 or 2)"
|
|
135
|
+
raise ValueError(msg)
|
|
136
|
+
|
|
137
|
+
self._pos = max(0, self._pos)
|
|
138
|
+
return self._pos
|
|
139
|
+
|
|
140
|
+
def tell(self):
|
|
141
|
+
self._checkClosed()
|
|
142
|
+
return self._pos
|
|
143
|
+
|
|
144
|
+
def read(self, size=-1, /):
|
|
145
|
+
if size is None:
|
|
146
|
+
size = -1
|
|
147
|
+
if not isinstance(size, int):
|
|
148
|
+
msg = f"argument should be integer or None, not '{type(size).__name__}'"
|
|
149
|
+
raise TypeError(msg)
|
|
150
|
+
|
|
151
|
+
self._checkClosed()
|
|
152
|
+
|
|
153
|
+
left = self.size - self._pos
|
|
154
|
+
|
|
155
|
+
size = left if size < 0 else min(size, left)
|
|
156
|
+
if size <= 0:
|
|
157
|
+
return b""
|
|
158
|
+
|
|
159
|
+
old_pos = self.parent_io.tell()
|
|
160
|
+
self.parent_io.seek(self.parent_start + self._pos)
|
|
161
|
+
try:
|
|
162
|
+
res = self.parent_io.read(size)
|
|
163
|
+
self._pos += len(res)
|
|
164
|
+
finally:
|
|
165
|
+
self.parent_io.seek(old_pos)
|
|
166
|
+
|
|
167
|
+
return res
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class KaitaiStream:
|
|
171
|
+
def __init__(self, io):
|
|
172
|
+
self._io = io
|
|
173
|
+
self.bits_left = 0
|
|
174
|
+
self.bits = 0
|
|
175
|
+
self.bits_le = False
|
|
176
|
+
self.bits_write_mode = False
|
|
177
|
+
|
|
178
|
+
self.write_back_handler = None
|
|
179
|
+
self.child_streams = []
|
|
180
|
+
|
|
181
|
+
# The size() method calls tell() and seek(), which will fail when called
|
|
182
|
+
# on a non-seekable stream. Non-seekable streams are supported for
|
|
183
|
+
# reading, so this is not fatal and we need to suppress these errors.
|
|
184
|
+
# Writing to a non-seekable stream (i.e. without the `_size` attribute)
|
|
185
|
+
# is currently not supported and will fail, but at this point we don't
|
|
186
|
+
# know whether any writing will be attempted on this stream.
|
|
187
|
+
#
|
|
188
|
+
# Although I haven't actually seen a bare ValueError raised in this case
|
|
189
|
+
# in practice, chances are some implementation may be doing it (see
|
|
190
|
+
# <https://docs.python.org/3/library/io.html#io.IOBase> for reference:
|
|
191
|
+
# "Also, implementations may raise a ValueError (or
|
|
192
|
+
# UnsupportedOperation) when operations they do not support are
|
|
193
|
+
# called."). And I've seen ValueError raised at least in Python 2 when
|
|
194
|
+
# calling read() on an unreadable stream.
|
|
195
|
+
with suppress(OSError, ValueError):
|
|
196
|
+
self._size = self.size()
|
|
197
|
+
|
|
198
|
+
def __enter__(self):
|
|
199
|
+
return self
|
|
200
|
+
|
|
201
|
+
def __exit__(self, *args, **kwargs):
|
|
202
|
+
self.close()
|
|
203
|
+
|
|
204
|
+
def close(self):
|
|
205
|
+
try:
|
|
206
|
+
if self.bits_write_mode:
|
|
207
|
+
self.write_align_to_byte()
|
|
208
|
+
else:
|
|
209
|
+
self.align_to_byte()
|
|
210
|
+
finally:
|
|
211
|
+
self._io.close()
|
|
212
|
+
|
|
213
|
+
# region Stream positioning
|
|
214
|
+
|
|
215
|
+
def is_eof(self):
|
|
216
|
+
if not self.bits_write_mode and self.bits_left > 0:
|
|
217
|
+
return False
|
|
218
|
+
|
|
219
|
+
# NB: previously, we first tried if self._io.read(1) did in fact read 1
|
|
220
|
+
# byte from the stream (and then seeked 1 byte back if so), but given
|
|
221
|
+
# that is_eof() may be called from both read and write contexts, it's
|
|
222
|
+
# more universal not to use read() at all. See also
|
|
223
|
+
# <https://github.com/kaitai-io/kaitai_struct_python_runtime/issues/75>.
|
|
224
|
+
return self._io.tell() >= self.size()
|
|
225
|
+
|
|
226
|
+
def seek(self, n):
|
|
227
|
+
if n < 0:
|
|
228
|
+
msg = f"cannot seek to invalid position {n}"
|
|
229
|
+
raise InvalidArgumentError(msg)
|
|
230
|
+
|
|
231
|
+
if self.bits_write_mode:
|
|
232
|
+
self.write_align_to_byte()
|
|
233
|
+
else:
|
|
234
|
+
self.align_to_byte()
|
|
235
|
+
|
|
236
|
+
self._io.seek(n)
|
|
237
|
+
|
|
238
|
+
def pos(self):
|
|
239
|
+
return self._io.tell() + (
|
|
240
|
+
1 if self.bits_write_mode and self.bits_left > 0 else 0
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
def size(self):
|
|
244
|
+
# Python has no internal File object API function to get
|
|
245
|
+
# current file / StringIO size, thus we use the following
|
|
246
|
+
# trick.
|
|
247
|
+
io = self._io
|
|
248
|
+
# Remember our current position
|
|
249
|
+
cur_pos = io.tell()
|
|
250
|
+
# Seek to the end of the stream and remember the full length
|
|
251
|
+
full_size = io.seek(0, SEEK_END)
|
|
252
|
+
|
|
253
|
+
# Seek back to the current position
|
|
254
|
+
io.seek(cur_pos)
|
|
255
|
+
return full_size
|
|
256
|
+
|
|
257
|
+
# endregion
|
|
258
|
+
|
|
259
|
+
# region Structs for numeric types
|
|
260
|
+
|
|
261
|
+
packer_s1 = struct.Struct("b")
|
|
262
|
+
packer_s2be = struct.Struct(">h")
|
|
263
|
+
packer_s4be = struct.Struct(">i")
|
|
264
|
+
packer_s8be = struct.Struct(">q")
|
|
265
|
+
packer_s2le = struct.Struct("<h")
|
|
266
|
+
packer_s4le = struct.Struct("<i")
|
|
267
|
+
packer_s8le = struct.Struct("<q")
|
|
268
|
+
|
|
269
|
+
packer_u1 = struct.Struct("B")
|
|
270
|
+
packer_u2be = struct.Struct(">H")
|
|
271
|
+
packer_u4be = struct.Struct(">I")
|
|
272
|
+
packer_u8be = struct.Struct(">Q")
|
|
273
|
+
packer_u2le = struct.Struct("<H")
|
|
274
|
+
packer_u4le = struct.Struct("<I")
|
|
275
|
+
packer_u8le = struct.Struct("<Q")
|
|
276
|
+
|
|
277
|
+
packer_f4be = struct.Struct(">f")
|
|
278
|
+
packer_f8be = struct.Struct(">d")
|
|
279
|
+
packer_f4le = struct.Struct("<f")
|
|
280
|
+
packer_f8le = struct.Struct("<d")
|
|
281
|
+
|
|
282
|
+
# endregion
|
|
283
|
+
|
|
284
|
+
# region Reading
|
|
285
|
+
|
|
286
|
+
# region Integer numbers
|
|
287
|
+
|
|
288
|
+
# region Signed
|
|
289
|
+
|
|
290
|
+
def read_s1(self):
|
|
291
|
+
return KaitaiStream.packer_s1.unpack(self.read_bytes(1))[0]
|
|
292
|
+
|
|
293
|
+
# region Big-endian
|
|
294
|
+
|
|
295
|
+
def read_s2be(self):
|
|
296
|
+
return KaitaiStream.packer_s2be.unpack(self.read_bytes(2))[0]
|
|
297
|
+
|
|
298
|
+
def read_s4be(self):
|
|
299
|
+
return KaitaiStream.packer_s4be.unpack(self.read_bytes(4))[0]
|
|
300
|
+
|
|
301
|
+
def read_s8be(self):
|
|
302
|
+
return KaitaiStream.packer_s8be.unpack(self.read_bytes(8))[0]
|
|
303
|
+
|
|
304
|
+
# endregion
|
|
305
|
+
|
|
306
|
+
# region Little-endian
|
|
307
|
+
|
|
308
|
+
def read_s2le(self):
|
|
309
|
+
return KaitaiStream.packer_s2le.unpack(self.read_bytes(2))[0]
|
|
310
|
+
|
|
311
|
+
def read_s4le(self):
|
|
312
|
+
return KaitaiStream.packer_s4le.unpack(self.read_bytes(4))[0]
|
|
313
|
+
|
|
314
|
+
def read_s8le(self):
|
|
315
|
+
return KaitaiStream.packer_s8le.unpack(self.read_bytes(8))[0]
|
|
316
|
+
|
|
317
|
+
# endregion
|
|
318
|
+
|
|
319
|
+
# endregion
|
|
320
|
+
|
|
321
|
+
# region Unsigned
|
|
322
|
+
|
|
323
|
+
def read_u1(self):
|
|
324
|
+
return KaitaiStream.packer_u1.unpack(self.read_bytes(1))[0]
|
|
325
|
+
|
|
326
|
+
# region Big-endian
|
|
327
|
+
|
|
328
|
+
def read_u2be(self):
|
|
329
|
+
return KaitaiStream.packer_u2be.unpack(self.read_bytes(2))[0]
|
|
330
|
+
|
|
331
|
+
def read_u4be(self):
|
|
332
|
+
return KaitaiStream.packer_u4be.unpack(self.read_bytes(4))[0]
|
|
333
|
+
|
|
334
|
+
def read_u8be(self):
|
|
335
|
+
return KaitaiStream.packer_u8be.unpack(self.read_bytes(8))[0]
|
|
336
|
+
|
|
337
|
+
# endregion
|
|
338
|
+
|
|
339
|
+
# region Little-endian
|
|
340
|
+
|
|
341
|
+
def read_u2le(self):
|
|
342
|
+
return KaitaiStream.packer_u2le.unpack(self.read_bytes(2))[0]
|
|
343
|
+
|
|
344
|
+
def read_u4le(self):
|
|
345
|
+
return KaitaiStream.packer_u4le.unpack(self.read_bytes(4))[0]
|
|
346
|
+
|
|
347
|
+
def read_u8le(self):
|
|
348
|
+
return KaitaiStream.packer_u8le.unpack(self.read_bytes(8))[0]
|
|
349
|
+
|
|
350
|
+
# endregion
|
|
351
|
+
|
|
352
|
+
# endregion
|
|
353
|
+
|
|
354
|
+
# endregion
|
|
355
|
+
|
|
356
|
+
# region Floating point numbers
|
|
357
|
+
|
|
358
|
+
# region Big-endian
|
|
359
|
+
|
|
360
|
+
def read_f4be(self):
|
|
361
|
+
return KaitaiStream.packer_f4be.unpack(self.read_bytes(4))[0]
|
|
362
|
+
|
|
363
|
+
def read_f8be(self):
|
|
364
|
+
return KaitaiStream.packer_f8be.unpack(self.read_bytes(8))[0]
|
|
365
|
+
|
|
366
|
+
# endregion
|
|
367
|
+
|
|
368
|
+
# region Little-endian
|
|
369
|
+
|
|
370
|
+
def read_f4le(self):
|
|
371
|
+
return KaitaiStream.packer_f4le.unpack(self.read_bytes(4))[0]
|
|
372
|
+
|
|
373
|
+
def read_f8le(self):
|
|
374
|
+
return KaitaiStream.packer_f8le.unpack(self.read_bytes(8))[0]
|
|
375
|
+
|
|
376
|
+
# endregion
|
|
377
|
+
|
|
378
|
+
# endregion
|
|
379
|
+
|
|
380
|
+
# region Unaligned bit values
|
|
381
|
+
|
|
382
|
+
def align_to_byte(self):
|
|
383
|
+
self.bits_left = 0
|
|
384
|
+
self.bits = 0
|
|
385
|
+
|
|
386
|
+
def read_bits_int_be(self, n):
|
|
387
|
+
"""Read an unsigned `n`-bit integer in big-endian parsing direction."""
|
|
388
|
+
self.bits_write_mode = False
|
|
389
|
+
|
|
390
|
+
res = 0
|
|
391
|
+
|
|
392
|
+
bits_needed = n - self.bits_left
|
|
393
|
+
self.bits_left = -bits_needed % 8
|
|
394
|
+
|
|
395
|
+
if bits_needed > 0:
|
|
396
|
+
# 1 bit => 1 byte
|
|
397
|
+
# 8 bits => 1 byte
|
|
398
|
+
# 9 bits => 2 bytes
|
|
399
|
+
bytes_needed = ((bits_needed - 1) // 8) + 1 # `ceil(bits_needed / 8)`
|
|
400
|
+
buf = self._read_bytes_not_aligned(bytes_needed)
|
|
401
|
+
res = int.from_bytes(buf, "big")
|
|
402
|
+
|
|
403
|
+
new_bits = res
|
|
404
|
+
res = res >> self.bits_left | self.bits << bits_needed
|
|
405
|
+
self.bits = new_bits # will be masked at the end of the function
|
|
406
|
+
else:
|
|
407
|
+
res = self.bits >> -bits_needed # shift unneeded bits out
|
|
408
|
+
|
|
409
|
+
mask = (1 << self.bits_left) - 1 # `bits_left` is in range 0..7
|
|
410
|
+
self.bits &= mask
|
|
411
|
+
|
|
412
|
+
return res
|
|
413
|
+
|
|
414
|
+
def read_bits_int(self, n):
|
|
415
|
+
"""Read an unsigned `n`-bit integer in big-endian parsing direction.
|
|
416
|
+
|
|
417
|
+
Deprecated and no longer used as of KSC 0.9. It is only available
|
|
418
|
+
for backward compatibility and will be removed in the future.
|
|
419
|
+
|
|
420
|
+
KSC 0.9 and later uses `read_bits_int_be()` instead.
|
|
421
|
+
"""
|
|
422
|
+
warnings.warn(
|
|
423
|
+
"read_bits_int() is deprecated since 0.9, use read_bits_int_be() instead",
|
|
424
|
+
DeprecationWarning,
|
|
425
|
+
stacklevel=2,
|
|
426
|
+
)
|
|
427
|
+
return self.read_bits_int_be(n)
|
|
428
|
+
|
|
429
|
+
def read_bits_int_le(self, n):
|
|
430
|
+
"""Read an unsigned `n`-bit integer in little-endian parsing direction."""
|
|
431
|
+
self.bits_write_mode = False
|
|
432
|
+
|
|
433
|
+
res = 0
|
|
434
|
+
bits_needed = n - self.bits_left
|
|
435
|
+
|
|
436
|
+
if bits_needed > 0:
|
|
437
|
+
# 1 bit => 1 byte
|
|
438
|
+
# 8 bits => 1 byte
|
|
439
|
+
# 9 bits => 2 bytes
|
|
440
|
+
bytes_needed = ((bits_needed - 1) // 8) + 1 # `ceil(bits_needed / 8)`
|
|
441
|
+
buf = self._read_bytes_not_aligned(bytes_needed)
|
|
442
|
+
res = int.from_bytes(buf, "little")
|
|
443
|
+
|
|
444
|
+
new_bits = res >> bits_needed
|
|
445
|
+
res = res << self.bits_left | self.bits
|
|
446
|
+
self.bits = new_bits
|
|
447
|
+
else:
|
|
448
|
+
res = self.bits
|
|
449
|
+
self.bits >>= n
|
|
450
|
+
|
|
451
|
+
self.bits_left = -bits_needed % 8
|
|
452
|
+
|
|
453
|
+
mask = (
|
|
454
|
+
1 << n
|
|
455
|
+
) - 1 # no problem with this in Python (arbitrary precision integers)
|
|
456
|
+
res &= mask
|
|
457
|
+
return res
|
|
458
|
+
|
|
459
|
+
# endregion
|
|
460
|
+
|
|
461
|
+
# region Byte arrays
|
|
462
|
+
|
|
463
|
+
def read_bytes(self, n):
|
|
464
|
+
self.align_to_byte()
|
|
465
|
+
return self._read_bytes_not_aligned(n)
|
|
466
|
+
|
|
467
|
+
def _read_bytes_not_aligned(self, n):
|
|
468
|
+
if n < 0:
|
|
469
|
+
msg = f"requested invalid {n} amount of bytes"
|
|
470
|
+
raise InvalidArgumentError(msg)
|
|
471
|
+
|
|
472
|
+
is_satisfiable = True
|
|
473
|
+
# When a large number of bytes is requested, try to check first
|
|
474
|
+
# that there is indeed enough data left in the stream.
|
|
475
|
+
# This avoids reading large amounts of data only to notice afterwards
|
|
476
|
+
# that it's not long enough. For smaller amounts of data, it's faster to
|
|
477
|
+
# first read the data unconditionally and check the length afterwards.
|
|
478
|
+
if (
|
|
479
|
+
n >= 8 * 1024 * 1024 # = 8 MiB
|
|
480
|
+
and self._io.seekable()
|
|
481
|
+
):
|
|
482
|
+
num_bytes_available = self.size() - self.pos()
|
|
483
|
+
is_satisfiable = n <= num_bytes_available
|
|
484
|
+
|
|
485
|
+
if is_satisfiable:
|
|
486
|
+
r = self._io.read(n)
|
|
487
|
+
num_bytes_available = len(r)
|
|
488
|
+
is_satisfiable = n <= num_bytes_available
|
|
489
|
+
|
|
490
|
+
if not is_satisfiable:
|
|
491
|
+
# noinspection PyUnboundLocalVariable
|
|
492
|
+
msg = f"requested {n} bytes, but only {num_bytes_available} bytes available"
|
|
493
|
+
raise EndOfStreamError(msg, n, num_bytes_available)
|
|
494
|
+
|
|
495
|
+
# noinspection PyUnboundLocalVariable
|
|
496
|
+
return r
|
|
497
|
+
|
|
498
|
+
def read_bytes_full(self):
|
|
499
|
+
self.align_to_byte()
|
|
500
|
+
return self._io.read()
|
|
501
|
+
|
|
502
|
+
def read_bytes_term(self, term, include_term, consume_term, eos_error):
|
|
503
|
+
self.align_to_byte()
|
|
504
|
+
term_byte = KaitaiStream.byte_from_int(term)
|
|
505
|
+
r = bytearray()
|
|
506
|
+
while True:
|
|
507
|
+
c = self._io.read(1)
|
|
508
|
+
if not c:
|
|
509
|
+
if eos_error:
|
|
510
|
+
raise NoTerminatorFoundError(term_byte, 0)
|
|
511
|
+
|
|
512
|
+
return bytes(r)
|
|
513
|
+
|
|
514
|
+
if c == term_byte:
|
|
515
|
+
if include_term:
|
|
516
|
+
r += c
|
|
517
|
+
if not consume_term:
|
|
518
|
+
self._io.seek(-1, SEEK_CUR)
|
|
519
|
+
return bytes(r)
|
|
520
|
+
|
|
521
|
+
r += c
|
|
522
|
+
|
|
523
|
+
def read_bytes_term_multi(self, term, include_term, consume_term, eos_error):
|
|
524
|
+
self.align_to_byte()
|
|
525
|
+
unit_size = len(term)
|
|
526
|
+
r = bytearray()
|
|
527
|
+
while True:
|
|
528
|
+
c = self._io.read(unit_size)
|
|
529
|
+
if len(c) < unit_size:
|
|
530
|
+
if eos_error:
|
|
531
|
+
raise NoTerminatorFoundError(term, len(c))
|
|
532
|
+
|
|
533
|
+
r += c
|
|
534
|
+
return bytes(r)
|
|
535
|
+
|
|
536
|
+
if c == term:
|
|
537
|
+
if include_term:
|
|
538
|
+
r += c
|
|
539
|
+
if not consume_term:
|
|
540
|
+
self._io.seek(-unit_size, SEEK_CUR)
|
|
541
|
+
return bytes(r)
|
|
542
|
+
|
|
543
|
+
r += c
|
|
544
|
+
|
|
545
|
+
def ensure_fixed_contents(self, expected):
|
|
546
|
+
"""Check that the `expected` bytes follow in the stream.
|
|
547
|
+
|
|
548
|
+
Deprecated and no longer used as of KSC 0.9. It is only available
|
|
549
|
+
for backward compatibility and will be removed in the future.
|
|
550
|
+
|
|
551
|
+
KSC 0.9 and later explicitly raises `ValidationNotEqualError` from an
|
|
552
|
+
`if` statement instead.
|
|
553
|
+
"""
|
|
554
|
+
warnings.warn(
|
|
555
|
+
"ensure_fixed_contents() is deprecated since 0.9, explicitly raise "
|
|
556
|
+
"ValidationNotEqualError from an `if` statement instead",
|
|
557
|
+
DeprecationWarning,
|
|
558
|
+
stacklevel=2,
|
|
559
|
+
)
|
|
560
|
+
actual = self._io.read(len(expected))
|
|
561
|
+
if actual != expected:
|
|
562
|
+
msg = (
|
|
563
|
+
f"unexpected fixed contents: got {actual!r}, "
|
|
564
|
+
f"was waiting for {expected!r}"
|
|
565
|
+
)
|
|
566
|
+
# NOTE: this method has always raised `Exception` directly and is now
|
|
567
|
+
# unused and slated for removal, so there's no point in "fixing" it.
|
|
568
|
+
raise Exception(msg) # noqa: TRY002
|
|
569
|
+
return actual
|
|
570
|
+
|
|
571
|
+
@staticmethod
|
|
572
|
+
def bytes_strip_right(data, pad_byte):
|
|
573
|
+
return data.rstrip(KaitaiStream.byte_from_int(pad_byte))
|
|
574
|
+
|
|
575
|
+
@staticmethod
|
|
576
|
+
def bytes_terminate(data, term, include_term):
|
|
577
|
+
term_index = KaitaiStream.byte_array_index_of(data, term)
|
|
578
|
+
if term_index == -1:
|
|
579
|
+
return data[:]
|
|
580
|
+
return data[: term_index + (1 if include_term else 0)]
|
|
581
|
+
|
|
582
|
+
@staticmethod
|
|
583
|
+
def bytes_terminate_multi(data, term, include_term):
|
|
584
|
+
unit_size = len(term)
|
|
585
|
+
search_index = data.find(term)
|
|
586
|
+
while True:
|
|
587
|
+
if search_index == -1:
|
|
588
|
+
return data[:]
|
|
589
|
+
mod = search_index % unit_size
|
|
590
|
+
if mod == 0:
|
|
591
|
+
return data[: search_index + (unit_size if include_term else 0)]
|
|
592
|
+
search_index = data.find(term, search_index + (unit_size - mod))
|
|
593
|
+
|
|
594
|
+
# endregion
|
|
595
|
+
|
|
596
|
+
# endregion
|
|
597
|
+
|
|
598
|
+
# region Writing
|
|
599
|
+
|
|
600
|
+
def _ensure_bytes_left_to_write(self, n, pos):
|
|
601
|
+
try:
|
|
602
|
+
full_size = self._size
|
|
603
|
+
except AttributeError:
|
|
604
|
+
msg = "writing to non-seekable streams is not supported"
|
|
605
|
+
raise ValueError(msg) from None
|
|
606
|
+
|
|
607
|
+
num_bytes_left = full_size - pos
|
|
608
|
+
if n > num_bytes_left:
|
|
609
|
+
msg = (
|
|
610
|
+
f"requested to write {n} bytes, but only "
|
|
611
|
+
f"{num_bytes_left} bytes left in the stream"
|
|
612
|
+
)
|
|
613
|
+
raise EndOfStreamError(msg, n, num_bytes_left)
|
|
614
|
+
|
|
615
|
+
# region Integer numbers
|
|
616
|
+
|
|
617
|
+
# region Signed
|
|
618
|
+
|
|
619
|
+
def write_s1(self, v):
|
|
620
|
+
self.write_bytes(KaitaiStream.packer_s1.pack(v))
|
|
621
|
+
|
|
622
|
+
# region Big-endian
|
|
623
|
+
|
|
624
|
+
def write_s2be(self, v):
|
|
625
|
+
self.write_bytes(KaitaiStream.packer_s2be.pack(v))
|
|
626
|
+
|
|
627
|
+
def write_s4be(self, v):
|
|
628
|
+
self.write_bytes(KaitaiStream.packer_s4be.pack(v))
|
|
629
|
+
|
|
630
|
+
def write_s8be(self, v):
|
|
631
|
+
self.write_bytes(KaitaiStream.packer_s8be.pack(v))
|
|
632
|
+
|
|
633
|
+
# endregion
|
|
634
|
+
|
|
635
|
+
# region Little-endian
|
|
636
|
+
|
|
637
|
+
def write_s2le(self, v):
|
|
638
|
+
self.write_bytes(KaitaiStream.packer_s2le.pack(v))
|
|
639
|
+
|
|
640
|
+
def write_s4le(self, v):
|
|
641
|
+
self.write_bytes(KaitaiStream.packer_s4le.pack(v))
|
|
642
|
+
|
|
643
|
+
def write_s8le(self, v):
|
|
644
|
+
self.write_bytes(KaitaiStream.packer_s8le.pack(v))
|
|
645
|
+
|
|
646
|
+
# endregion
|
|
647
|
+
|
|
648
|
+
# endregion
|
|
649
|
+
|
|
650
|
+
# region Unsigned
|
|
651
|
+
|
|
652
|
+
def write_u1(self, v):
|
|
653
|
+
self.write_bytes(KaitaiStream.packer_u1.pack(v))
|
|
654
|
+
|
|
655
|
+
# region Big-endian
|
|
656
|
+
|
|
657
|
+
def write_u2be(self, v):
|
|
658
|
+
self.write_bytes(KaitaiStream.packer_u2be.pack(v))
|
|
659
|
+
|
|
660
|
+
def write_u4be(self, v):
|
|
661
|
+
self.write_bytes(KaitaiStream.packer_u4be.pack(v))
|
|
662
|
+
|
|
663
|
+
def write_u8be(self, v):
|
|
664
|
+
self.write_bytes(KaitaiStream.packer_u8be.pack(v))
|
|
665
|
+
|
|
666
|
+
# endregion
|
|
667
|
+
|
|
668
|
+
# region Little-endian
|
|
669
|
+
|
|
670
|
+
def write_u2le(self, v):
|
|
671
|
+
self.write_bytes(KaitaiStream.packer_u2le.pack(v))
|
|
672
|
+
|
|
673
|
+
def write_u4le(self, v):
|
|
674
|
+
self.write_bytes(KaitaiStream.packer_u4le.pack(v))
|
|
675
|
+
|
|
676
|
+
def write_u8le(self, v):
|
|
677
|
+
self.write_bytes(KaitaiStream.packer_u8le.pack(v))
|
|
678
|
+
|
|
679
|
+
# endregion
|
|
680
|
+
|
|
681
|
+
# endregion
|
|
682
|
+
|
|
683
|
+
# endregion
|
|
684
|
+
|
|
685
|
+
# region Floating point numbers
|
|
686
|
+
|
|
687
|
+
# region Big-endian
|
|
688
|
+
|
|
689
|
+
def write_f4be(self, v):
|
|
690
|
+
self.write_bytes(KaitaiStream.packer_f4be.pack(v))
|
|
691
|
+
|
|
692
|
+
def write_f8be(self, v):
|
|
693
|
+
self.write_bytes(KaitaiStream.packer_f8be.pack(v))
|
|
694
|
+
|
|
695
|
+
# endregion
|
|
696
|
+
|
|
697
|
+
# region Little-endian
|
|
698
|
+
|
|
699
|
+
def write_f4le(self, v):
|
|
700
|
+
self.write_bytes(KaitaiStream.packer_f4le.pack(v))
|
|
701
|
+
|
|
702
|
+
def write_f8le(self, v):
|
|
703
|
+
self.write_bytes(KaitaiStream.packer_f8le.pack(v))
|
|
704
|
+
|
|
705
|
+
# endregion
|
|
706
|
+
|
|
707
|
+
# endregion
|
|
708
|
+
|
|
709
|
+
# region Unaligned bit values
|
|
710
|
+
|
|
711
|
+
def write_align_to_byte(self):
|
|
712
|
+
if self.bits_left > 0:
|
|
713
|
+
b = self.bits
|
|
714
|
+
if not self.bits_le:
|
|
715
|
+
b <<= 8 - self.bits_left
|
|
716
|
+
|
|
717
|
+
# We clear the `bits_left` and `bits` fields using align_to_byte()
|
|
718
|
+
# before writing the byte in the stream so that it happens even in
|
|
719
|
+
# case the write fails. The reason is that if the write fails, it
|
|
720
|
+
# would likely be a permanent issue that's not going to resolve
|
|
721
|
+
# itself when retrying the operation with the same stream state, and
|
|
722
|
+
# since seek() calls write_align_to_byte() at the beginning too, you
|
|
723
|
+
# wouldn't be even able to seek anywhere without getting the same
|
|
724
|
+
# exception again. So the stream could be in a broken state,
|
|
725
|
+
# throwing the same exception over and over again even though you've
|
|
726
|
+
# already processed it and you'd like to move on. And the only way
|
|
727
|
+
# to get rid of it would be to call align_to_byte() externally
|
|
728
|
+
# (given how it's currently implemented), but that's really just a
|
|
729
|
+
# coincidence - that's a method intended for reading (not writing)
|
|
730
|
+
# and it should never be necessary to call it from the outside (it's
|
|
731
|
+
# more like an internal method now).
|
|
732
|
+
#
|
|
733
|
+
# So it seems more reasonable to deliver the exception once and let
|
|
734
|
+
# the user application process it, but otherwise clear the bit
|
|
735
|
+
# buffer to make the stream ready for further operations and to
|
|
736
|
+
# avoid repeatedly delivering an exception for one past failed
|
|
737
|
+
# operation. The rationale behind this is that it's not really a
|
|
738
|
+
# failure of the "align to byte" operation, but the writing of some
|
|
739
|
+
# bits to the stream that was requested earlier.
|
|
740
|
+
self.align_to_byte()
|
|
741
|
+
self._write_bytes_not_aligned(KaitaiStream.byte_from_int(b))
|
|
742
|
+
|
|
743
|
+
def write_bits_int_be(self, n, val):
|
|
744
|
+
self.bits_le = False
|
|
745
|
+
self.bits_write_mode = True
|
|
746
|
+
|
|
747
|
+
mask = (
|
|
748
|
+
1 << n
|
|
749
|
+
) - 1 # no problem with this in Python (arbitrary precision integers)
|
|
750
|
+
val &= mask
|
|
751
|
+
|
|
752
|
+
bits_to_write = self.bits_left + n
|
|
753
|
+
bytes_needed = ((bits_to_write - 1) // 8) + 1 # `ceil(bits_to_write / 8)`
|
|
754
|
+
|
|
755
|
+
# Unlike self._io.tell(), pos() respects the `bits_left` field (it
|
|
756
|
+
# returns the stream position as if it were already aligned on a byte
|
|
757
|
+
# boundary), which ensures that we report the same numbers of bytes here
|
|
758
|
+
# as read_bits_int_*() methods would.
|
|
759
|
+
self._ensure_bytes_left_to_write(
|
|
760
|
+
bytes_needed - (1 if self.bits_left > 0 else 0), self.pos()
|
|
761
|
+
)
|
|
762
|
+
|
|
763
|
+
bytes_to_write = bits_to_write // 8
|
|
764
|
+
self.bits_left = bits_to_write % 8
|
|
765
|
+
|
|
766
|
+
if bytes_to_write > 0:
|
|
767
|
+
buf = bytearray(bytes_to_write)
|
|
768
|
+
|
|
769
|
+
mask = (1 << self.bits_left) - 1 # `bits_left` is in range 0..7
|
|
770
|
+
new_bits = val & mask
|
|
771
|
+
val = val >> self.bits_left | self.bits << (n - self.bits_left)
|
|
772
|
+
self.bits = new_bits
|
|
773
|
+
|
|
774
|
+
for i in range(bytes_to_write - 1, -1, -1):
|
|
775
|
+
buf[i] = val & 0xFF
|
|
776
|
+
val >>= 8
|
|
777
|
+
self._write_bytes_not_aligned(buf)
|
|
778
|
+
else:
|
|
779
|
+
self.bits = self.bits << n | val
|
|
780
|
+
|
|
781
|
+
def write_bits_int_le(self, n, val):
|
|
782
|
+
self.bits_le = True
|
|
783
|
+
self.bits_write_mode = True
|
|
784
|
+
|
|
785
|
+
bits_to_write = self.bits_left + n
|
|
786
|
+
bytes_needed = ((bits_to_write - 1) // 8) + 1 # `ceil(bits_to_write / 8)`
|
|
787
|
+
|
|
788
|
+
# Unlike self._io.tell(), pos() respects the `bits_left` field (it
|
|
789
|
+
# returns the stream position as if it were already aligned on a byte
|
|
790
|
+
# boundary), which ensures that we report the same numbers of bytes here
|
|
791
|
+
# as read_bits_int_*() methods would.
|
|
792
|
+
self._ensure_bytes_left_to_write(
|
|
793
|
+
bytes_needed - (1 if self.bits_left > 0 else 0), self.pos()
|
|
794
|
+
)
|
|
795
|
+
|
|
796
|
+
bytes_to_write = bits_to_write // 8
|
|
797
|
+
old_bits_left = self.bits_left
|
|
798
|
+
self.bits_left = bits_to_write % 8
|
|
799
|
+
|
|
800
|
+
if bytes_to_write > 0:
|
|
801
|
+
buf = bytearray(bytes_to_write)
|
|
802
|
+
|
|
803
|
+
new_bits = val >> (
|
|
804
|
+
n - self.bits_left
|
|
805
|
+
) # no problem with this in Python (arbitrary precision integers)
|
|
806
|
+
val = val << old_bits_left | self.bits
|
|
807
|
+
self.bits = new_bits
|
|
808
|
+
|
|
809
|
+
for i in range(bytes_to_write):
|
|
810
|
+
buf[i] = val & 0xFF
|
|
811
|
+
val >>= 8
|
|
812
|
+
self._write_bytes_not_aligned(buf)
|
|
813
|
+
else:
|
|
814
|
+
self.bits |= val << old_bits_left
|
|
815
|
+
|
|
816
|
+
mask = (1 << self.bits_left) - 1 # `bits_left` is in range 0..7
|
|
817
|
+
self.bits &= mask
|
|
818
|
+
|
|
819
|
+
# endregion
|
|
820
|
+
|
|
821
|
+
# region Byte arrays
|
|
822
|
+
|
|
823
|
+
def write_bytes(self, buf):
|
|
824
|
+
self.write_align_to_byte()
|
|
825
|
+
self._write_bytes_not_aligned(buf)
|
|
826
|
+
|
|
827
|
+
def _write_bytes_not_aligned(self, buf):
|
|
828
|
+
n = len(buf)
|
|
829
|
+
self._ensure_bytes_left_to_write(n, self._io.tell())
|
|
830
|
+
self._io.write(buf)
|
|
831
|
+
|
|
832
|
+
def write_bytes_limit(self, buf, size, term, pad_byte):
|
|
833
|
+
n = len(buf)
|
|
834
|
+
# Strictly speaking, this check is redundant because it is already
|
|
835
|
+
# done in the corresponding _check() method in the generated code, but
|
|
836
|
+
# it seems to make sense to include it here anyway so that this method
|
|
837
|
+
# itself does something reasonable for every set of arguments.
|
|
838
|
+
#
|
|
839
|
+
# However, it should never happen when operated correctly (and in
|
|
840
|
+
# this case, assigning inconsistent values to fields of a KS-generated
|
|
841
|
+
# object is considered correct operation if the user application calls
|
|
842
|
+
# the corresponding _check(), which we know would raise an error and
|
|
843
|
+
# thus the code should not reach _write() and this method at all). So
|
|
844
|
+
# it's by design that this throws ValueError, not any more specific
|
|
845
|
+
# error, because it's not intended to be caught in user applications,
|
|
846
|
+
# but avoided by calling all _check() methods correctly.
|
|
847
|
+
if n > size:
|
|
848
|
+
msg = f"writing {size} bytes, but {n} bytes were given"
|
|
849
|
+
raise ValueError(msg)
|
|
850
|
+
|
|
851
|
+
self.write_bytes(buf)
|
|
852
|
+
if n < size:
|
|
853
|
+
self.write_u1(term)
|
|
854
|
+
self.write_bytes(KaitaiStream.byte_from_int(pad_byte) * (size - n - 1))
|
|
855
|
+
|
|
856
|
+
# endregion
|
|
857
|
+
|
|
858
|
+
# endregion
|
|
859
|
+
|
|
860
|
+
# region Byte array processing
|
|
861
|
+
|
|
862
|
+
@staticmethod
|
|
863
|
+
def process_xor_one(data, key):
|
|
864
|
+
return bytes(v ^ key for v in data)
|
|
865
|
+
|
|
866
|
+
@staticmethod
|
|
867
|
+
def process_xor_many(data, key):
|
|
868
|
+
return bytes(a ^ b for a, b in zip(data, itertools.cycle(key)))
|
|
869
|
+
|
|
870
|
+
@staticmethod
|
|
871
|
+
def process_rotate_left(data, amount, group_size):
|
|
872
|
+
if group_size != 1:
|
|
873
|
+
msg = f"unable to rotate group of {group_size} bytes yet"
|
|
874
|
+
raise NotImplementedError(msg)
|
|
875
|
+
|
|
876
|
+
anti_amount = -amount % (group_size * 8)
|
|
877
|
+
|
|
878
|
+
r = bytearray(data)
|
|
879
|
+
for i, byte in enumerate(r):
|
|
880
|
+
r[i] = (byte << amount) & 0xFF | (byte >> anti_amount)
|
|
881
|
+
return bytes(r)
|
|
882
|
+
|
|
883
|
+
# endregion
|
|
884
|
+
|
|
885
|
+
# region Misc runtime operations
|
|
886
|
+
|
|
887
|
+
def substream(self, n):
|
|
888
|
+
if not self._io.seekable():
|
|
889
|
+
# Non-seekable stream => fall back to the traditional copying implementation
|
|
890
|
+
return KaitaiStream(BytesIO(self.read_bytes(n)))
|
|
891
|
+
|
|
892
|
+
self.align_to_byte()
|
|
893
|
+
|
|
894
|
+
if n < 0:
|
|
895
|
+
msg = f"requested invalid {n} amount of bytes"
|
|
896
|
+
raise InvalidArgumentError(msg)
|
|
897
|
+
|
|
898
|
+
pos = self.pos()
|
|
899
|
+
num_bytes_available = max(0, self.size() - pos)
|
|
900
|
+
if n > num_bytes_available:
|
|
901
|
+
msg = f"requested {n} bytes, but only {num_bytes_available} bytes available"
|
|
902
|
+
raise EndOfStreamError(msg, n, num_bytes_available)
|
|
903
|
+
|
|
904
|
+
sub = KaitaiStream(SubIO(self._io, pos, n))
|
|
905
|
+
self._io.seek(pos + n)
|
|
906
|
+
return sub
|
|
907
|
+
|
|
908
|
+
@staticmethod
|
|
909
|
+
def int_from_byte(v):
|
|
910
|
+
"""Convert a byte array item to an integer.
|
|
911
|
+
|
|
912
|
+
Deprecated and no longer used in code generated by KSC. It is only
|
|
913
|
+
available for backward compatibility and will be removed in the future.
|
|
914
|
+
|
|
915
|
+
This method only made sense to ensure compatibility with Python 2.
|
|
916
|
+
In Python 3, it's simply an identity function.
|
|
917
|
+
"""
|
|
918
|
+
warnings.warn(
|
|
919
|
+
"int_from_byte() is deprecated (in Python 3, it is an identity function)",
|
|
920
|
+
DeprecationWarning,
|
|
921
|
+
stacklevel=2,
|
|
922
|
+
)
|
|
923
|
+
return v
|
|
924
|
+
|
|
925
|
+
@staticmethod
|
|
926
|
+
def byte_from_int(i):
|
|
927
|
+
return KaitaiStream.packer_u1.pack(i)
|
|
928
|
+
|
|
929
|
+
@staticmethod
|
|
930
|
+
def byte_array_index(data, i):
|
|
931
|
+
"""Return the byte at index `i` in the byte array `data` as an integer.
|
|
932
|
+
|
|
933
|
+
Deprecated and no longer used in code generated by KSC. It is only
|
|
934
|
+
available for backward compatibility and will be removed in the future.
|
|
935
|
+
|
|
936
|
+
This method only made sense to ensure compatibility with Python 2.
|
|
937
|
+
In Python 3, `data[i]` should be used instead.
|
|
938
|
+
"""
|
|
939
|
+
warnings.warn(
|
|
940
|
+
"byte_array_index(data, i) is deprecated, use data[i] instead",
|
|
941
|
+
DeprecationWarning,
|
|
942
|
+
stacklevel=2,
|
|
943
|
+
)
|
|
944
|
+
return data[i]
|
|
945
|
+
|
|
946
|
+
@staticmethod
|
|
947
|
+
def byte_array_min(b):
|
|
948
|
+
"""Return the minimum byte in the byte array `data` as an integer.
|
|
949
|
+
|
|
950
|
+
Deprecated and no longer used in code generated by KSC. It is only
|
|
951
|
+
available for backward compatibility and will be removed in the future.
|
|
952
|
+
|
|
953
|
+
This method only made sense to ensure compatibility with Python 2.
|
|
954
|
+
In Python 3, `min(b)` should be used instead.
|
|
955
|
+
"""
|
|
956
|
+
warnings.warn(
|
|
957
|
+
"byte_array_min(b) is deprecated, use min(b) instead",
|
|
958
|
+
DeprecationWarning,
|
|
959
|
+
stacklevel=2,
|
|
960
|
+
)
|
|
961
|
+
return min(b)
|
|
962
|
+
|
|
963
|
+
@staticmethod
|
|
964
|
+
def byte_array_max(b):
|
|
965
|
+
"""Return the maximum byte in the byte array `data` as an integer.
|
|
966
|
+
|
|
967
|
+
Deprecated and no longer used in code generated by KSC. It is only
|
|
968
|
+
available for backward compatibility and will be removed in the future.
|
|
969
|
+
|
|
970
|
+
This method only made sense to ensure compatibility with Python 2.
|
|
971
|
+
In Python 3, `max(b)` should be used instead.
|
|
972
|
+
"""
|
|
973
|
+
warnings.warn(
|
|
974
|
+
"byte_array_max(b) is deprecated, use max(b) instead",
|
|
975
|
+
DeprecationWarning,
|
|
976
|
+
stacklevel=2,
|
|
977
|
+
)
|
|
978
|
+
return max(b)
|
|
979
|
+
|
|
980
|
+
@staticmethod
|
|
981
|
+
def byte_array_index_of(data, b):
|
|
982
|
+
return data.find(KaitaiStream.byte_from_int(b))
|
|
983
|
+
|
|
984
|
+
@staticmethod
|
|
985
|
+
def resolve_enum(enum_obj, value):
|
|
986
|
+
"""Convert an integer to the given enum if possible, otherwise return it back.
|
|
987
|
+
|
|
988
|
+
Enums in Python raise a `ValueError` exception when they encounter an unknown
|
|
989
|
+
value. This method works around this issue so that attempting to convert an
|
|
990
|
+
unknown integer value to an enum does not stop parsing by default.
|
|
991
|
+
|
|
992
|
+
If it is desired to stop parsing on unknown enum values, `valid/in-enum: true`
|
|
993
|
+
can be used in the .ksy specification on a specific `seq` or `instances` enum
|
|
994
|
+
field. This adds validation that the field contains one of the known (defined)
|
|
995
|
+
enum values, otherwise a `ValidationNotInEnumError` exception is raised.
|
|
996
|
+
"""
|
|
997
|
+
try:
|
|
998
|
+
return enum_obj(value)
|
|
999
|
+
except ValueError:
|
|
1000
|
+
return value
|
|
1001
|
+
|
|
1002
|
+
# endregion
|
|
1003
|
+
|
|
1004
|
+
def to_byte_array(self):
|
|
1005
|
+
pos = self.pos()
|
|
1006
|
+
self.seek(0)
|
|
1007
|
+
r = self.read_bytes_full()
|
|
1008
|
+
self.seek(pos)
|
|
1009
|
+
return r
|
|
1010
|
+
|
|
1011
|
+
class WriteBackHandler:
|
|
1012
|
+
def __init__(self, pos, handler):
|
|
1013
|
+
self.pos = pos
|
|
1014
|
+
self.handler = handler
|
|
1015
|
+
|
|
1016
|
+
def write_back(self, parent):
|
|
1017
|
+
parent.seek(self.pos)
|
|
1018
|
+
self.handler(parent)
|
|
1019
|
+
|
|
1020
|
+
def add_child_stream(self, child):
|
|
1021
|
+
self.child_streams.append(child)
|
|
1022
|
+
|
|
1023
|
+
def write_back_child_streams(self, parent=None):
|
|
1024
|
+
_pos = self.pos()
|
|
1025
|
+
for child in self.child_streams:
|
|
1026
|
+
child.write_back_child_streams(self)
|
|
1027
|
+
|
|
1028
|
+
self.child_streams.clear()
|
|
1029
|
+
self.seek(_pos)
|
|
1030
|
+
if parent is not None:
|
|
1031
|
+
self._write_back(parent)
|
|
1032
|
+
|
|
1033
|
+
def _write_back(self, parent):
|
|
1034
|
+
self.write_back_handler.write_back(parent)
|
|
1035
|
+
|
|
1036
|
+
|
|
1037
|
+
class KaitaiStructError(Exception):
|
|
1038
|
+
"""Common ancestor for all errors originating from correct Kaitai Struct usage.
|
|
1039
|
+
|
|
1040
|
+
Use this exception class in the `except` clause if you want to handle all
|
|
1041
|
+
parse errors and serialization errors.
|
|
1042
|
+
|
|
1043
|
+
"Correct usage" refers to errors that indicate a problem with user input,
|
|
1044
|
+
not errors indicating incorrect usage, which are not meant to be caught but
|
|
1045
|
+
fixed in the application code.
|
|
1046
|
+
|
|
1047
|
+
If available, the `src_path` attribute will contain the KSY source path
|
|
1048
|
+
pointing to the element where the error occurred. If it is not available,
|
|
1049
|
+
`src_path` will be `None`.
|
|
1050
|
+
"""
|
|
1051
|
+
|
|
1052
|
+
def __init__(self, msg, src_path):
|
|
1053
|
+
super().__init__(("" if src_path is None else src_path + ": ") + msg)
|
|
1054
|
+
self.src_path = src_path
|
|
1055
|
+
|
|
1056
|
+
|
|
1057
|
+
class InvalidArgumentError(KaitaiStructError, ValueError):
|
|
1058
|
+
"""Raised when an invalid argument is encountered during parsing or serialization.
|
|
1059
|
+
|
|
1060
|
+
This is a subclass of `ValueError`, which is the standard built-in exception
|
|
1061
|
+
class for invalid arguments in Python. It is also a subclass of
|
|
1062
|
+
`KaitaiStructError`, as it indicates invalid user input and therefore
|
|
1063
|
+
represents a parsing or serialization error.
|
|
1064
|
+
"""
|
|
1065
|
+
|
|
1066
|
+
def __init__(self, msg):
|
|
1067
|
+
super().__init__(msg, None)
|
|
1068
|
+
|
|
1069
|
+
|
|
1070
|
+
class EndOfStreamError(KaitaiStructError, EOFError):
|
|
1071
|
+
"""Raised when attempting to read or write beyond end of stream.
|
|
1072
|
+
|
|
1073
|
+
Provides the `bytes_needed` (number of bytes requested to read or write) and
|
|
1074
|
+
`bytes_available` (number of bytes remaining in the stream) attributes.
|
|
1075
|
+
"""
|
|
1076
|
+
|
|
1077
|
+
def __init__(self, msg, bytes_needed, bytes_available):
|
|
1078
|
+
super().__init__(msg, None)
|
|
1079
|
+
self.bytes_needed = bytes_needed
|
|
1080
|
+
self.bytes_available = bytes_available
|
|
1081
|
+
|
|
1082
|
+
|
|
1083
|
+
class NoTerminatorFoundError(EndOfStreamError):
|
|
1084
|
+
"""Raised when end of stream is reached before the required terminator is found.
|
|
1085
|
+
|
|
1086
|
+
This is a subclass of `EndOfStreamError` because it is a special type of
|
|
1087
|
+
reaching the end of the stream prematurely - see
|
|
1088
|
+
https://github.com/kaitai-io/kaitai_struct_python_runtime/issues/41 for an
|
|
1089
|
+
explanation.
|
|
1090
|
+
|
|
1091
|
+
If you want to tolerate a missing terminator, you can specify `eos-error: false`
|
|
1092
|
+
in the .ksy specification. Reaching the end of the stream will then be
|
|
1093
|
+
considered a valid end of the field, and this error will no longer be
|
|
1094
|
+
raised.
|
|
1095
|
+
|
|
1096
|
+
The `term` attribute contains a `bytes` object with the searched terminator.
|
|
1097
|
+
"""
|
|
1098
|
+
|
|
1099
|
+
def __init__(self, term, bytes_available):
|
|
1100
|
+
super().__init__(
|
|
1101
|
+
f"end of stream reached, but no terminator {term!r} found",
|
|
1102
|
+
len(term),
|
|
1103
|
+
bytes_available,
|
|
1104
|
+
)
|
|
1105
|
+
self.term = term
|
|
1106
|
+
|
|
1107
|
+
|
|
1108
|
+
class UndecidedEndiannessError(KaitaiStructError):
|
|
1109
|
+
"""Raised when the calculated default endianness cannot be determined.
|
|
1110
|
+
|
|
1111
|
+
The default endianness should have been decided with a switch, but no case
|
|
1112
|
+
matches (although the endianness switch suggests that the result should be
|
|
1113
|
+
positive).
|
|
1114
|
+
"""
|
|
1115
|
+
|
|
1116
|
+
def __init__(self, src_path):
|
|
1117
|
+
super().__init__("unable to decide on endianness for a type", src_path)
|
|
1118
|
+
|
|
1119
|
+
|
|
1120
|
+
class ValidationFailedError(KaitaiStructError):
|
|
1121
|
+
"""Common ancestor for all validation failures.
|
|
1122
|
+
|
|
1123
|
+
The `io` attribute stores the `KaitaiStream` object representing the I/O
|
|
1124
|
+
stream associated with the error. Validation exceptions raised from
|
|
1125
|
+
`_check()` methods do not have an I/O stream available, so their `io` will
|
|
1126
|
+
be `None`.
|
|
1127
|
+
"""
|
|
1128
|
+
|
|
1129
|
+
def __init__(self, msg, io, src_path):
|
|
1130
|
+
super().__init__(
|
|
1131
|
+
("" if io is None else f"at pos {io.pos()}: ")
|
|
1132
|
+
+ "validation failed: "
|
|
1133
|
+
+ msg,
|
|
1134
|
+
src_path,
|
|
1135
|
+
)
|
|
1136
|
+
self.io = io
|
|
1137
|
+
|
|
1138
|
+
|
|
1139
|
+
class ValidationNotEqualError(ValidationFailedError):
|
|
1140
|
+
"""Raised when validation specified using the `contents` or `valid/eq` keys fails.
|
|
1141
|
+
|
|
1142
|
+
This exception is the result of a validation failure: `actual` should have
|
|
1143
|
+
been equal to `expected`, but it was not.
|
|
1144
|
+
|
|
1145
|
+
The `expected` attribute contains the expected value specified in the
|
|
1146
|
+
`contents` or `valid/eq` key in .ksy specifications. Note that the syntax
|
|
1147
|
+
`valid/eq: <expression>` has a shorthand form `valid: <expression>`.
|
|
1148
|
+
|
|
1149
|
+
The `actual` attribute contains the actual value parsed from the stream.
|
|
1150
|
+
"""
|
|
1151
|
+
|
|
1152
|
+
def __init__(self, expected, actual, io, src_path):
|
|
1153
|
+
super().__init__(
|
|
1154
|
+
f"not equal, expected {expected!r}, but got {actual!r}", io, src_path
|
|
1155
|
+
)
|
|
1156
|
+
self.expected = expected
|
|
1157
|
+
self.actual = actual
|
|
1158
|
+
|
|
1159
|
+
|
|
1160
|
+
class ValidationLessThanError(ValidationFailedError):
|
|
1161
|
+
"""Raised when validation specified using the `valid/min` key fails.
|
|
1162
|
+
|
|
1163
|
+
This exception is the result of a validation failure: `actual` should have
|
|
1164
|
+
been greater than or equal to `min`, but it was not.
|
|
1165
|
+
|
|
1166
|
+
The `min` attribute contains the minimum value specified in the `valid/min`
|
|
1167
|
+
key in .ksy specifications.
|
|
1168
|
+
|
|
1169
|
+
The `actual` attribute contains the actual value parsed from the stream.
|
|
1170
|
+
"""
|
|
1171
|
+
|
|
1172
|
+
def __init__(self, min_bound, actual, io, src_path):
|
|
1173
|
+
super().__init__(
|
|
1174
|
+
f"not in range, min {min_bound!r}, but got {actual!r}", io, src_path
|
|
1175
|
+
)
|
|
1176
|
+
self.min = min_bound
|
|
1177
|
+
self.actual = actual
|
|
1178
|
+
|
|
1179
|
+
|
|
1180
|
+
class ValidationGreaterThanError(ValidationFailedError):
|
|
1181
|
+
"""Raised when validation specified using the `valid/max` key fails.
|
|
1182
|
+
|
|
1183
|
+
This exception is the result of a validation failure: `actual` should have
|
|
1184
|
+
been less than or equal to `max`, but it was not.
|
|
1185
|
+
|
|
1186
|
+
The `max` attribute contains the maximum value specified in the `valid/max`
|
|
1187
|
+
key in .ksy specifications.
|
|
1188
|
+
|
|
1189
|
+
The `actual` attribute contains the actual value parsed from the stream.
|
|
1190
|
+
"""
|
|
1191
|
+
|
|
1192
|
+
def __init__(self, max_bound, actual, io, src_path):
|
|
1193
|
+
super().__init__(
|
|
1194
|
+
f"not in range, max {max_bound!r}, but got {actual!r}", io, src_path
|
|
1195
|
+
)
|
|
1196
|
+
self.max = max_bound
|
|
1197
|
+
self.actual = actual
|
|
1198
|
+
|
|
1199
|
+
|
|
1200
|
+
class ValidationNotAnyOfError(ValidationFailedError):
|
|
1201
|
+
"""Raised when validation specified using the `valid/any-of` key fails.
|
|
1202
|
+
|
|
1203
|
+
This exception is the result of a validation failure: `actual` should have
|
|
1204
|
+
been any of the values listed in the `valid/any-of` key, but it was not.
|
|
1205
|
+
|
|
1206
|
+
The `actual` attribute contains the actual value parsed from the stream.
|
|
1207
|
+
"""
|
|
1208
|
+
|
|
1209
|
+
def __init__(self, actual, io, src_path):
|
|
1210
|
+
super().__init__(f"not any of the list, got {actual!r}", io, src_path)
|
|
1211
|
+
self.actual = actual
|
|
1212
|
+
|
|
1213
|
+
|
|
1214
|
+
class ValidationNotInEnumError(ValidationFailedError):
|
|
1215
|
+
"""Raised when validation specified using the `valid/in-enum` key fails.
|
|
1216
|
+
|
|
1217
|
+
This exception is the result of a validation failure: `actual` should have
|
|
1218
|
+
been a known value defined in the enum, but it was not.
|
|
1219
|
+
|
|
1220
|
+
The `actual` attribute contains the actual value parsed from the stream.
|
|
1221
|
+
"""
|
|
1222
|
+
|
|
1223
|
+
def __init__(self, actual, io, src_path):
|
|
1224
|
+
super().__init__(f"not in the enum, got {actual!r}", io, src_path)
|
|
1225
|
+
self.actual = actual
|
|
1226
|
+
|
|
1227
|
+
|
|
1228
|
+
class ValidationExprError(ValidationFailedError):
|
|
1229
|
+
"""Raised when validation specified using the `valid/expr` key fails.
|
|
1230
|
+
|
|
1231
|
+
This exception is the result of a validation failure: `actual` should have
|
|
1232
|
+
satisfied the validation expression in the `valid/expr` key, but it did not.
|
|
1233
|
+
|
|
1234
|
+
The `actual` attribute contains the actual value parsed from the stream.
|
|
1235
|
+
"""
|
|
1236
|
+
|
|
1237
|
+
def __init__(self, actual, io, src_path):
|
|
1238
|
+
super().__init__(f"not matching the expression, got {actual!r}", io, src_path)
|
|
1239
|
+
self.actual = actual
|
|
1240
|
+
|
|
1241
|
+
|
|
1242
|
+
class ConsistencyError(Exception):
|
|
1243
|
+
def __init__(self, attr_id, expected, actual):
|
|
1244
|
+
super().__init__(
|
|
1245
|
+
f"Check failed: {attr_id}, expected: {expected!r}, actual: {actual!r}"
|
|
1246
|
+
)
|
|
1247
|
+
self.id = attr_id
|
|
1248
|
+
self.expected = expected
|
|
1249
|
+
self.actual = actual
|
|
1250
|
+
|
|
1251
|
+
|
|
1252
|
+
class ConsistencyNotCheckedError(Exception):
|
|
1253
|
+
"""Raised when attempting to write an object with unchecked consistency."""
|
|
1254
|
+
|
|
1255
|
+
def __init__(self):
|
|
1256
|
+
super().__init__(
|
|
1257
|
+
"consistency not checked: _check() has not been called "
|
|
1258
|
+
"since the last modification of the object"
|
|
1259
|
+
)
|