|
7 | 7 | import sys |
8 | 8 | import types |
9 | 9 | import warnings |
| 10 | +from contextlib import contextmanager |
10 | 11 | from pathlib import Path |
11 | 12 | from typing import TYPE_CHECKING, Any, BinaryIO, Literal, TypeVar, cast |
12 | 13 |
|
|
31 | 32 | from dissect.cstruct.types.base import MetaType, normalize_endianness |
32 | 33 |
|
33 | 34 | if TYPE_CHECKING: |
34 | | - from collections.abc import Iterable |
| 35 | + from collections.abc import Iterable, Iterator |
35 | 36 | from typing import TypeAlias |
36 | 37 |
|
37 | 38 | from dissect.cstruct.types import ( |
@@ -222,9 +223,11 @@ def __copy__(self) -> cstruct: |
222 | 223 |
|
223 | 224 | # Update typedefs to point to the new cstruct instance |
224 | 225 | for name, type in self.typedefs.items(): |
| 226 | + # Skip all the default types |
225 | 227 | if name in cs.typedefs: |
226 | 228 | continue |
227 | 229 |
|
| 230 | + # Update the cstruct instance for all other types |
228 | 231 | if isinstance(type, MetaType): |
229 | 232 | new_type = copy.copy(type) |
230 | 233 | new_type.cs = cs |
@@ -389,6 +392,25 @@ def copy(self) -> cstruct: |
389 | 392 | """ |
390 | 393 | return copy.copy(self) |
391 | 394 |
|
| 395 | + @contextmanager |
| 396 | + def endianness(self, endian: AllowedEndianness) -> Iterator[cstruct]: |
| 397 | + """Context manager for temporarily changing the endianness of this cstruct instance.""" |
| 398 | + new = self.copy() |
| 399 | + new.endian = normalize_endianness(endian) |
| 400 | + yield new |
| 401 | + |
| 402 | + @contextmanager |
| 403 | + def big_endian(self) -> Iterator[cstruct]: |
| 404 | + """Context manager for temporarily changing the endianness to big endian.""" |
| 405 | + with self.endianness(">") as cs: |
| 406 | + yield cs |
| 407 | + |
| 408 | + @contextmanager |
| 409 | + def little_endian(self) -> Iterator[cstruct]: |
| 410 | + """Context manager for temporarily changing the endianness to little endian.""" |
| 411 | + with self.endianness("<") as cs: |
| 412 | + yield cs |
| 413 | + |
392 | 414 | def _make_type( |
393 | 415 | self, |
394 | 416 | name: str, |
|
0 commit comments