Skip to content

refactor: improve int32 integration#902

Merged
mvadari merged 8 commits intomainfrom
int32
Feb 12, 2026
Merged

refactor: improve int32 integration#902
mvadari merged 8 commits intomainfrom
int32

Conversation

@mvadari
Copy link
Collaborator

@mvadari mvadari commented Feb 12, 2026

High Level Overview of Change

This PR improves the Int32 integration in the binary codec.

Context of Change

I already had this code in #818 and when I was merging from main, my implementation seemed cleaner and DRYer.

Type of Change

  • Refactor (non-breaking change that only restructures code)

Did you update CHANGELOG.md?

  • No, this change does not impact library users

Test Plan

CI passes.

@mvadari mvadari requested a review from ckeshava February 12, 2026 17:12
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 12, 2026

Warning

Rate limit exceeded

@mvadari has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 5 minutes and 1 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

Walkthrough

Adds a new signed Int type for the XRPL binary codec, refactors Int32 to inherit from Int and accept string or int inputs, and standardizes comparison error messages in UInt to use generic type-based wording.

Changes

Cohort / File(s) Summary
New Signed Integer Type
xrpl/core/binarycodec/types/int.py
Adds Int class (subclass of UInt) exposing a value property that interprets the internal buffer as a signed big-endian integer via int.from_bytes(..., signed=True).
Int32 Refactor & API changes
xrpl/core/binarycodec/types/int32.py
Int32 now inherits from Int; from_value accepts Union[str,int], validates numeric strings, converts to int/bytes, and raises explicit errors for invalid inputs; docstrings and imports updated; some Int32 instance-level APIs (value/to_json/comparison dunders) removed.
Comparison Error Message Standardization
xrpl/core/binarycodec/types/uint.py
Replaces UInt-specific messages in comparison dunder methods with a generic message: Cannot compare {type(self)} and {type(other)} across __eq__, __ne__, __lt__, __le__, __gt__, and __ge__.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

I’m a rabbit nibbling binary hay,
I shaped an Int to leap and sway,
Int32 joined in, strings turned to numbers,
Errors now speak plainly — no more slumbers,
Hop on, bytes! 🐇✨

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'refactor: improve int32 integration' directly relates to the main change—refactoring Int32 to inherit from the new Int class for improved code organization.
Description check ✅ Passed The description includes high-level overview, context, type of change, and CHANGELOG confirmation, but the Test Plan section only states 'CI passes' without specific test details.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Merge Conflict Detection ✅ Passed ✅ No merge conflicts detected when merging into main

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch int32

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

"""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

ckeshava
ckeshava previously approved these changes Feb 12, 2026
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In `@xrpl/core/binarycodec/types/int.py`:
- Around line 12-15: The Int class docstring incorrectly says "unsigned
integers"; update the docstring on class Int to state it is for serializing and
deserializing signed integers (matching the module behavior and signed=True),
keeping the link to the Int Fields documentation and preserving the existing
phrasing/formatting otherwise so the docstring accurately reflects the class
purpose.

In `@xrpl/core/binarycodec/types/int32.py`:
- Around line 57-61: The error message in the Int32 constructor (where
XRPLBinaryCodecException is raised) uses a string with a placeholder
{value.__class__.__name__} but is not an f-string, so the type name is not
interpolated; update that raise to use an f-string (or otherwise format the
string) so the actual class name of the variable value is included in the
message (retain the same descriptive text and reference XRPLBinaryCodecException
and value.__class__.__name__).
- Around line 67-71: The current string handling in Int32 (the branch that
checks isinstance(value, str) and value.isdigit()) rejects negative decimal
strings and accepts some Unicode digit characters; replace that logic by
attempting to convert the string to an int using int(value) inside a try/except
ValueError, then validate the resulting integer fits in signed 32-bit range (use
_WIDTH to compute bounds: -2**(8*_WIDTH-1) .. 2**(8*_WIDTH-1)-1), convert it
with int_val.to_bytes(_WIDTH, byteorder="big", signed=True), and return
cls(value_bytes); on ValueError or out-of-range, raise XRPLBinaryCodecException
as before.
🧹 Nitpick comments (2)
xrpl/core/binarycodec/types/int32.py (2)

63-65: Negative int values that overflow 4 bytes will raise an OverflowError, not the codec exception.

int.to_bytes raises OverflowError if the value doesn't fit in _WIDTH bytes. For a signed 32-bit integer, valid range is [-2147483648, 2147483647]. Consider wrapping in a try/except to provide a domain-specific error message. Same concern applies to line 68.

🛡️ Suggested overflow guard (applies to both int and str branches)
         if isinstance(value, int):
-            value_bytes = (value).to_bytes(_WIDTH, byteorder="big", signed=True)
-            return cls(value_bytes)
+            try:
+                value_bytes = value.to_bytes(_WIDTH, byteorder="big", signed=True)
+            except OverflowError:
+                raise XRPLBinaryCodecException(
+                    f"Cannot construct Int32: value {value} out of range."
+                )
+            return cls(value_bytes)

32-40: Minor grammar nit: "a Int32" → "an Int32" in multiple docstrings.

Lines 36, 49, 55, and 59 use "a Int32" — should be "an Int32" since "Int" starts with a vowel sound.

Also applies to: 44-56

@mvadari mvadari requested a review from Patel-Raj11 February 12, 2026 18:00
Patel-Raj11
Patel-Raj11 previously approved these changes Feb 12, 2026
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@xrpl/core/binarycodec/types/int32.py`:
- Around line 1-3: The module-level docstring incorrectly references "UInt
Fields" for a signed type; update the module docstring string (top of
xrpl/core/binarycodec/types/int32.py) to say "Int Fields" and, if applicable,
change the link text or target to the Int Fields section (match the class-level
docstring for Int32) so the description consistently refers to signed Int fields
and the correct XRPL serialization URL; ensure the wording mirrors the class
docstring for Int32.
🧹 Nitpick comments (4)
xrpl/core/binarycodec/types/int32.py (4)

67-74: Use raise ... from to preserve exception context (Ruff B904).

When re-raising inside an except block, chain the exception so the original traceback is preserved for debugging.

Also, int_value.to_bytes(...) on line 74 can raise OverflowError if the parsed integer exceeds the signed 32-bit range — the same applies to line 64. Consider catching OverflowError alongside ValueError to wrap it in XRPLBinaryCodecException for consistent error reporting.

Proposed fix
         if isinstance(value, str):
             try:
                 int_value = int(value)
-            except ValueError:
+            except ValueError as err:
                 raise XRPLBinaryCodecException(
                     f"Cannot construct Int32 from given value: {value!r}"
-                )
-            return cls(int_value.to_bytes(_WIDTH, byteorder="big", signed=True))
+                ) 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

63-65: OverflowError from to_bytes is uncaught for out-of-range int values.

If value falls outside the signed 32-bit range (−2³¹ to 2³¹−1), int.to_bytes raises OverflowError. Wrapping it would give callers a consistent XRPLBinaryCodecException.

Proposed fix
         if isinstance(value, int):
-            value_bytes = (value).to_bytes(_WIDTH, byteorder="big", signed=True)
-            return cls(value_bytes)
+            try:
+                value_bytes = 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
+            return cls(value_bytes)

76-76: Unreachable code.

After the guard on line 57 (which raises for anything other than str or int), the isinstance checks on lines 63 and 67 exhaustively cover both remaining types. This line can never execute.

Proposed fix
-
-        raise XRPLBinaryCodecException("Cannot construct Int32 from given value")

36-36: Grammar nit: "a Int32" → "an Int32" in several docstrings and messages.

The article before a vowel sound should be "an". This appears on lines 36, 49, 55, and 59.

Also applies to: 49-49, 55-55, 59-59

@mvadari mvadari merged commit 9fd1ca6 into main Feb 12, 2026
17 checks passed
@mvadari mvadari deleted the int32 branch February 12, 2026 19:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants