|
| 1 | +# |
| 2 | +# This file is part of libdestruct (https://github.com/mrindeciso/libdestruct). |
| 3 | +# Copyright (c) 2024 Roberto Alessandro Bertolini. All rights reserved. |
| 4 | +# Licensed under the MIT license. See LICENSE file in the project root for details. |
| 5 | +# |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +from typing import TYPE_CHECKING |
| 10 | + |
| 11 | +from libdestruct.common.obj import obj |
| 12 | +from libdestruct.common.type_registry import TypeRegistry |
| 13 | + |
| 14 | +if TYPE_CHECKING: |
| 15 | + from collections.abc import MutableSequence |
| 16 | + from enum import Enum |
| 17 | + |
| 18 | + |
| 19 | +class enum(obj): |
| 20 | + """A generic enum.""" |
| 21 | + |
| 22 | + python_enum: type[Enum] |
| 23 | + """The backing Python enum.""" |
| 24 | + |
| 25 | + _backing_type: type[obj] |
| 26 | + """The backing type.""" |
| 27 | + |
| 28 | + lenient: bool |
| 29 | + """Whether the conversion is lenient or not.""" |
| 30 | + |
| 31 | + def __init__( |
| 32 | + self: enum, |
| 33 | + memory: MutableSequence, |
| 34 | + address: int | tuple[obj, int], |
| 35 | + python_enum: type[Enum], |
| 36 | + backing_type: type[obj], |
| 37 | + lenient: bool = True, |
| 38 | + ) -> None: |
| 39 | + """Initialize the enum object.""" |
| 40 | + super().__init__(memory, address) |
| 41 | + |
| 42 | + self.python_enum = python_enum |
| 43 | + self._backing_type = TypeRegistry().inflater_for(backing_type)(memory, address) |
| 44 | + self.lenient = lenient |
| 45 | + |
| 46 | + self.size = self._backing_type.size |
| 47 | + |
| 48 | + def get(self: enum) -> Enum: |
| 49 | + """Return the value of the enum.""" |
| 50 | + return self.python_enum(self._backing_type.get()) |
| 51 | + |
| 52 | + def _set(self: enum, value: Enum) -> None: |
| 53 | + """Set the value of the enum.""" |
| 54 | + self._backing_type.set(value.value) |
| 55 | + |
| 56 | + def to_bytes(self: enum) -> bytes: |
| 57 | + """Return the serialized representation of the enum.""" |
| 58 | + return self._backing_type.to_bytes() |
| 59 | + |
| 60 | + def to_str(self: obj, indent: int = 0) -> str: |
| 61 | + """Return a string representation of the object.""" |
| 62 | + return f"{' ' * indent}{self.get()!r}" |
0 commit comments