|
| 1 | +# |
| 2 | +# This file is part of libdestruct (https://github.com/mrindeciso/libdestruct). |
| 3 | +# Copyright (c) 2026 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 | +import struct |
| 10 | + |
| 11 | +from libdestruct.common.obj import obj |
| 12 | + |
| 13 | + |
| 14 | +class c_float(obj): |
| 15 | + """A C float (IEEE 754 single-precision, 32-bit).""" |
| 16 | + |
| 17 | + size: int = 4 |
| 18 | + """The size of a float in bytes.""" |
| 19 | + |
| 20 | + _frozen_value: float | None = None |
| 21 | + """The frozen value of the float.""" |
| 22 | + |
| 23 | + def _format_char(self: c_float) -> str: |
| 24 | + return "<f" if self.endianness == "little" else ">f" |
| 25 | + |
| 26 | + def get(self: c_float) -> float: |
| 27 | + """Return the value of the float.""" |
| 28 | + return struct.unpack(self._format_char(), self.resolver.resolve(self.size, 0))[0] |
| 29 | + |
| 30 | + def _set(self: c_float, value: float) -> None: |
| 31 | + """Set the value of the float.""" |
| 32 | + self.resolver.modify(self.size, 0, struct.pack(self._format_char(), value)) |
| 33 | + |
| 34 | + def to_bytes(self: c_float) -> bytes: |
| 35 | + """Return the serialized representation of the float.""" |
| 36 | + if self._frozen: |
| 37 | + return struct.pack(self._format_char(), self._frozen_value) |
| 38 | + return self.resolver.resolve(self.size, 0) |
| 39 | + |
| 40 | + def __float__(self: c_float) -> float: |
| 41 | + """Return the value as a Python float.""" |
| 42 | + return self.get() |
| 43 | + |
| 44 | + |
| 45 | +class c_double(obj): |
| 46 | + """A C double (IEEE 754 double-precision, 64-bit).""" |
| 47 | + |
| 48 | + size: int = 8 |
| 49 | + """The size of a double in bytes.""" |
| 50 | + |
| 51 | + _frozen_value: float | None = None |
| 52 | + """The frozen value of the double.""" |
| 53 | + |
| 54 | + def _format_char(self: c_double) -> str: |
| 55 | + return "<d" if self.endianness == "little" else ">d" |
| 56 | + |
| 57 | + def get(self: c_double) -> float: |
| 58 | + """Return the value of the double.""" |
| 59 | + return struct.unpack(self._format_char(), self.resolver.resolve(self.size, 0))[0] |
| 60 | + |
| 61 | + def _set(self: c_double, value: float) -> None: |
| 62 | + """Set the value of the double.""" |
| 63 | + self.resolver.modify(self.size, 0, struct.pack(self._format_char(), value)) |
| 64 | + |
| 65 | + def to_bytes(self: c_double) -> bytes: |
| 66 | + """Return the serialized representation of the double.""" |
| 67 | + if self._frozen: |
| 68 | + return struct.pack(self._format_char(), self._frozen_value) |
| 69 | + return self.resolver.resolve(self.size, 0) |
| 70 | + |
| 71 | + def __float__(self: c_double) -> float: |
| 72 | + """Return the value as a Python float.""" |
| 73 | + return self.get() |
0 commit comments