|
| 1 | +"""Class for serializing and deserializing a signed 32-bit integer.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from typing import Optional, Type |
| 6 | + |
| 7 | +from typing_extensions import Final, Self |
| 8 | + |
| 9 | +from xrpl.core.binarycodec.binary_wrappers.binary_parser import BinaryParser |
| 10 | +from xrpl.core.binarycodec.exceptions import XRPLBinaryCodecException |
| 11 | +from xrpl.core.binarycodec.types.serialized_type import SerializedType |
| 12 | + |
| 13 | +_WIDTH: Final[int] = 4 # 32 / 8 |
| 14 | + |
| 15 | + |
| 16 | +class Int32(SerializedType): |
| 17 | + """Class for serializing and deserializing a signed 32-bit integer.""" |
| 18 | + |
| 19 | + def __init__(self: Self, buffer: bytes = bytes(_WIDTH)) -> None: |
| 20 | + """Construct a new Int32 type from a ``bytes`` value.""" |
| 21 | + super().__init__(buffer) |
| 22 | + |
| 23 | + @property |
| 24 | + def value(self: Self) -> int: |
| 25 | + """Get the value of the Int32 represented by `self.buffer`.""" |
| 26 | + return int.from_bytes(self.buffer, byteorder="big", signed=True) |
| 27 | + |
| 28 | + @classmethod |
| 29 | + def from_parser( |
| 30 | + cls: Type[Self], parser: BinaryParser, _length_hint: Optional[int] = None |
| 31 | + ) -> Self: |
| 32 | + """Construct a new Int32 type from a BinaryParser.""" |
| 33 | + return cls(parser.read(_WIDTH)) |
| 34 | + |
| 35 | + @classmethod |
| 36 | + def from_value(cls: Type[Self], value: int) -> Self: |
| 37 | + """Construct a new Int32 type from an integer.""" |
| 38 | + if not isinstance(value, int): |
| 39 | + raise XRPLBinaryCodecException( |
| 40 | + f"Invalid type to construct Int32: expected int, " |
| 41 | + f"received {value.__class__.__name__}." |
| 42 | + ) |
| 43 | + return cls(value.to_bytes(_WIDTH, byteorder="big", signed=True)) |
| 44 | + |
| 45 | + def to_json(self: Self) -> int: |
| 46 | + """Convert the Int32 to JSON (returns the integer value).""" |
| 47 | + return self.value |
| 48 | + |
| 49 | + def __eq__(self: Self, other: object) -> bool: |
| 50 | + """Determine whether two Int32 objects are equal.""" |
| 51 | + if isinstance(other, int): |
| 52 | + return self.value == other |
| 53 | + if isinstance(other, Int32): |
| 54 | + return self.value == other.value |
| 55 | + return NotImplemented |
| 56 | + |
| 57 | + def __lt__(self: Self, other: object) -> bool: |
| 58 | + """Determine whether this Int32 is less than another.""" |
| 59 | + if isinstance(other, int): |
| 60 | + return self.value < other |
| 61 | + if isinstance(other, Int32): |
| 62 | + return self.value < other.value |
| 63 | + return NotImplemented |
| 64 | + |
| 65 | + def __gt__(self: Self, other: object) -> bool: |
| 66 | + """Determine whether this Int32 is greater than another.""" |
| 67 | + if isinstance(other, int): |
| 68 | + return self.value > other |
| 69 | + if isinstance(other, Int32): |
| 70 | + return self.value > other.value |
| 71 | + return NotImplemented |
0 commit comments