-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstruct.py
More file actions
39 lines (29 loc) · 1.36 KB
/
struct.py
File metadata and controls
39 lines (29 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#
# This file is part of libdestruct (https://github.com/mrindeciso/libdestruct).
# Copyright (c) 2024 Roberto Alessandro Bertolini. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Literal
from libdestruct.common.obj import obj
from libdestruct.common.type_registry import TypeRegistry
from libdestruct.libdestruct import inflater
if TYPE_CHECKING: # pragma: no cover
from libdestruct.common.struct.struct_impl import struct_impl
class struct(obj):
"""A C struct."""
def __init__(self: struct) -> None:
"""Initialize the struct."""
raise RuntimeError("This type should not be directly instantiated.")
def __new__(cls: type[struct], *args: Any, **kwargs: Any) -> struct: # noqa: PYI034
"""Create a new struct."""
# Look for an inflater for this struct
type_impl = TypeRegistry().inflater_for(cls)
return type_impl(*args, **kwargs)
@classmethod
def from_bytes(cls: type[struct], data: bytes, endianness: Literal["little", "big"] = "little") -> struct_impl:
"""Create a struct from a serialized representation."""
type_inflater = inflater(data, endianness=endianness)
result = type_inflater.inflate(cls, 0)
result.freeze()
return result