Skip to content

Commit 9fd1ca6

Browse files
authored
refactor: improve int32 integration (#902)
* improve int32 integration * clean up * improve error message * fix linting * fix typo * respond to coderabbit * one more typo * more minor fixes
1 parent 8f74e2d commit 9fd1ca6

File tree

3 files changed

+85
-53
lines changed

3 files changed

+85
-53
lines changed

xrpl/core/binarycodec/types/int.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"""Base class for serializing and deserializing signed integers.
2+
See `Int Fields <https://xrpl.org/serialization.html#int-fields>`_
3+
"""
4+
5+
from __future__ import annotations
6+
7+
from typing_extensions import Self
8+
9+
from xrpl.core.binarycodec.types.uint import UInt
10+
11+
12+
class Int(UInt):
13+
"""Base class for serializing and deserializing signed integers.
14+
See `Int Fields <https://xrpl.org/serialization.html#int-fields>`_
15+
"""
16+
17+
@property
18+
def value(self: Self) -> int:
19+
"""
20+
Get the value of the Int represented by `self.buffer`.
21+
22+
Returns:
23+
The int value of the Int.
24+
"""
25+
return int.from_bytes(self.buffer, byteorder="big", signed=True)
Lines changed: 54 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,71 +1,78 @@
1-
"""Class for serializing and deserializing a signed 32-bit integer."""
1+
"""Class for serializing and deserializing a signed 32-bit integer.
2+
See `Int Fields <https://xrpl.org/serialization.html#int-fields>`_
3+
"""
24

35
from __future__ import annotations
46

5-
from typing import Optional, Type
7+
from typing import Optional, Type, Union
68

79
from typing_extensions import Final, Self
810

911
from xrpl.core.binarycodec.binary_wrappers.binary_parser import BinaryParser
1012
from xrpl.core.binarycodec.exceptions import XRPLBinaryCodecException
11-
from xrpl.core.binarycodec.types.serialized_type import SerializedType
13+
from xrpl.core.binarycodec.types.int import Int
1214

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

1517

16-
class Int32(SerializedType):
17-
"""Class for serializing and deserializing a signed 32-bit integer."""
18+
class Int32(Int):
19+
"""
20+
Class for serializing and deserializing a signed 32-bit integer.
21+
See `Int Fields <https://xrpl.org/serialization.html#int-fields>`_
22+
"""
1823

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

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-
2828
@classmethod
2929
def from_parser(
3030
cls: Type[Self], parser: BinaryParser, _length_hint: Optional[int] = None
3131
) -> Self:
32-
"""Construct a new Int32 type from a BinaryParser."""
32+
"""
33+
Construct a new Int32 type from a BinaryParser.
34+
35+
Args:
36+
parser: A BinaryParser to construct an Int32 from.
37+
38+
Returns:
39+
The Int32 constructed from parser.
40+
"""
3341
return cls(parser.read(_WIDTH))
3442

3543
@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
44+
def from_value(cls: Type[Self], value: Union[str, int]) -> Self:
45+
"""
46+
Construct a new Int32 type from a number.
47+
48+
Args:
49+
value: The number to construct an Int32 from.
50+
51+
Returns:
52+
The Int32 constructed from value.
53+
54+
Raises:
55+
XRPLBinaryCodecException: If an Int32 could not be constructed from value.
56+
"""
57+
if isinstance(value, int):
58+
value_bytes = (value).to_bytes(_WIDTH, byteorder="big", signed=True)
59+
return cls(value_bytes)
60+
61+
if isinstance(value, str):
62+
try:
63+
int_value = int(value)
64+
except ValueError as err:
65+
raise XRPLBinaryCodecException(
66+
f"Cannot construct Int32 from given value: {value!r}"
67+
) from err
68+
try:
69+
return cls(int_value.to_bytes(_WIDTH, byteorder="big", signed=True))
70+
except OverflowError as err:
71+
raise XRPLBinaryCodecException(
72+
f"Cannot construct Int32 from given value: {value!r}"
73+
) from err
74+
75+
raise XRPLBinaryCodecException(
76+
"Invalid type to construct an Int32: expected str or int,"
77+
f" received {value.__class__.__name__}."
78+
)

xrpl/core/binarycodec/types/uint.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,47 +37,47 @@ def __eq__(self: Self, other: object) -> bool:
3737
return self.value == other
3838
if isinstance(other, UInt):
3939
return self.value == other.value
40-
raise XRPLBinaryCodecException(f"Cannot compare UInt and {type(other)}")
40+
raise XRPLBinaryCodecException(f"Cannot compare {type(self)} and {type(other)}")
4141

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

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

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

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

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

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

0 commit comments

Comments
 (0)