Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions xrpl/core/binarycodec/types/int.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""Base class for serializing and deserializing signed integers.
See `Int Fields <https://xrpl.org/serialization.html#int-fields>`_
"""

from __future__ import annotations

from typing_extensions import Self

from xrpl.core.binarycodec.types.uint import UInt


class Int(UInt):
"""Base class for serializing and deserializing signed integers.
See `Int Fields <https://xrpl.org/serialization.html#int-fields>`_
"""

@property
def value(self: Self) -> int:
"""
Get the value of the Int represented by `self.buffer`.

Returns:
The int value of the Int.
"""
return int.from_bytes(self.buffer, byteorder="big", signed=True)
101 changes: 54 additions & 47 deletions xrpl/core/binarycodec/types/int32.py
Original file line number Diff line number Diff line change
@@ -1,71 +1,78 @@
"""Class for serializing and deserializing a signed 32-bit integer."""
"""Class for serializing and deserializing a signed 32-bit integer.
See `Int Fields <https://xrpl.org/serialization.html#int-fields>`_
"""

from __future__ import annotations

from typing import Optional, Type
from typing import Optional, Type, Union

from typing_extensions import Final, Self

from xrpl.core.binarycodec.binary_wrappers.binary_parser import BinaryParser
from xrpl.core.binarycodec.exceptions import XRPLBinaryCodecException
from xrpl.core.binarycodec.types.serialized_type import SerializedType
from xrpl.core.binarycodec.types.int import Int

_WIDTH: Final[int] = 4 # 32 / 8


class Int32(SerializedType):
"""Class for serializing and deserializing a signed 32-bit integer."""
class Int32(Int):
"""
Class for serializing and deserializing a signed 32-bit integer.
See `Int Fields <https://xrpl.org/serialization.html#int-fields>`_
"""

def __init__(self: Self, buffer: bytes = bytes(_WIDTH)) -> None:
"""Construct a new Int32 type from a ``bytes`` value."""
super().__init__(buffer)

@property
def value(self: Self) -> int:
"""Get the value of the Int32 represented by `self.buffer`."""
return int.from_bytes(self.buffer, byteorder="big", signed=True)

@classmethod
def from_parser(
cls: Type[Self], parser: BinaryParser, _length_hint: Optional[int] = None
) -> Self:
"""Construct a new Int32 type from a BinaryParser."""
"""
Construct a new Int32 type from a BinaryParser.
Args:
parser: A BinaryParser to construct an Int32 from.
Returns:
The Int32 constructed from parser.
"""
return cls(parser.read(_WIDTH))

@classmethod
def from_value(cls: Type[Self], value: int) -> Self:
"""Construct a new Int32 type from an integer."""
if not isinstance(value, int):
raise XRPLBinaryCodecException(
f"Invalid type to construct Int32: expected int, "
f"received {value.__class__.__name__}."
)
return cls(value.to_bytes(_WIDTH, byteorder="big", signed=True))

def to_json(self: Self) -> int:
"""Convert the Int32 to JSON (returns the integer value)."""
return self.value

def __eq__(self: Self, other: object) -> bool:
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All of these dunder methods are inherited from UInt, so they are no longer needed here

"""Determine whether two Int32 objects are equal."""
if isinstance(other, int):
return self.value == other
if isinstance(other, Int32):
return self.value == other.value
return NotImplemented

def __lt__(self: Self, other: object) -> bool:
"""Determine whether this Int32 is less than another."""
if isinstance(other, int):
return self.value < other
if isinstance(other, Int32):
return self.value < other.value
return NotImplemented

def __gt__(self: Self, other: object) -> bool:
"""Determine whether this Int32 is greater than another."""
if isinstance(other, int):
return self.value > other
if isinstance(other, Int32):
return self.value > other.value
return NotImplemented
def from_value(cls: Type[Self], value: Union[str, int]) -> Self:
"""
Construct a new Int32 type from a number.
Args:
value: The number to construct an Int32 from.
Returns:
The Int32 constructed from value.
Raises:
XRPLBinaryCodecException: If an Int32 could not be constructed from value.
"""
if isinstance(value, int):
value_bytes = (value).to_bytes(_WIDTH, byteorder="big", signed=True)
return cls(value_bytes)

if isinstance(value, str):
try:
int_value = int(value)
except ValueError as err:
raise XRPLBinaryCodecException(
f"Cannot construct Int32 from given value: {value!r}"
) from err
try:
return cls(int_value.to_bytes(_WIDTH, byteorder="big", signed=True))
except OverflowError as err:
raise XRPLBinaryCodecException(
f"Cannot construct Int32 from given value: {value!r}"
) from err

raise XRPLBinaryCodecException(
"Invalid type to construct an Int32: expected str or int,"
f" received {value.__class__.__name__}."
)
12 changes: 6 additions & 6 deletions xrpl/core/binarycodec/types/uint.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,47 +37,47 @@ def __eq__(self: Self, other: object) -> bool:
return self.value == other
if isinstance(other, UInt):
return self.value == other.value
raise XRPLBinaryCodecException(f"Cannot compare UInt and {type(other)}")
raise XRPLBinaryCodecException(f"Cannot compare {type(self)} and {type(other)}")

def __ne__(self: Self, other: object) -> bool:
"""Determine whether two UInt objects are unequal."""
if isinstance(other, int):
return self.value != other
if isinstance(other, UInt):
return self.value != other.value
raise XRPLBinaryCodecException(f"Cannot compare UInt and {type(other)}")
raise XRPLBinaryCodecException(f"Cannot compare {type(self)} and {type(other)}")

def __lt__(self: Self, other: object) -> bool:
"""Determine whether one UInt object is less than another."""
if isinstance(other, int):
return self.value < other
if isinstance(other, UInt):
return self.value < other.value
raise XRPLBinaryCodecException(f"Cannot compare UInt and {type(other)}")
raise XRPLBinaryCodecException(f"Cannot compare {type(self)} and {type(other)}")

def __le__(self: Self, other: object) -> bool:
"""Determine whether one UInt object is less than or equal to another."""
if isinstance(other, int):
return self.value <= other
if isinstance(other, UInt):
return self.value <= other.value
raise XRPLBinaryCodecException(f"Cannot compare UInt and {type(other)}")
raise XRPLBinaryCodecException(f"Cannot compare {type(self)} and {type(other)}")

def __gt__(self: Self, other: object) -> bool:
"""Determine whether one UInt object is greater than another."""
if isinstance(other, int):
return self.value > other
if isinstance(other, UInt):
return self.value > other.value
raise XRPLBinaryCodecException(f"Cannot compare UInt and {type(other)}")
raise XRPLBinaryCodecException(f"Cannot compare {type(self)} and {type(other)}")

def __ge__(self: Self, other: object) -> bool:
"""Determine whether one UInt object is greater than or equal to another."""
if isinstance(other, int):
return self.value >= other
if isinstance(other, UInt):
return self.value >= other.value
raise XRPLBinaryCodecException(f"Cannot compare UInt and {type(other)}")
raise XRPLBinaryCodecException(f"Cannot compare {type(self)} and {type(other)}")

def to_json(self: Self) -> Union[str, int]:
"""
Expand Down