Skip to content

fix(binarycodec): propagate error from write_length_encoded instead of panicking - #343

Open
e-desouza wants to merge 2 commits into
mainfrom
fix/issue-268-serializer-unwrap
Open

fix(binarycodec): propagate error from write_length_encoded instead of panicking#343
e-desouza wants to merge 2 commits into
mainfrom
fix/issue-268-serializer-unwrap

Conversation

@e-desouza

Copy link
Copy Markdown
Collaborator

Why

BinarySerializer::write_length_encoded returned &Self (infallible) and called _encode_variable_length_prefix(...).unwrap(). When a caller serialized a VL-encoded field larger than MAX_LENGTH_VALUE (918,744 bytes), this panicked instead of returning an error. The method contained a // TODO Handle unwrap better comment acknowledging the gap.

Fixes #268.

What changed

  • write_length_encoded and write_field_and_value signatures changed from -> &Self to -> XRPLCoreResult<&Self>.
  • .unwrap() replaced with ?; callers updated to propagate with ?.
  • Doc examples updated to call .unwrap() in the example context.

How to validate

cargo test --release

Regression test test_write_length_encoded_too_large_returns_error verifies Err(InvalidVariableLengthTooLarge { max: 918744 }) is returned instead of a panic.

Note: Serialization is a pub trait; this is a breaking API change. Downstream crates implementing the trait must update their signatures. Recommend a version bump.

@codecov

codecov Bot commented Jul 12, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.65217% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 86.73%. Comparing base (c83df4f) to head (4bdcf7b).

Files with missing lines Patch % Lines
src/core/binarycodec/types/mod.rs 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #343      +/-   ##
==========================================
+ Coverage   86.71%   86.73%   +0.01%     
==========================================
  Files         252      252              
  Lines       32630    32645      +15     
==========================================
+ Hits        28296    28314      +18     
+ Misses       4334     4331       -3     
Flag Coverage Δ
integration 71.32% <ø> (ø)
unit 87.34% <95.65%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/core/binarycodec/binary_wrappers.rs 90.63% <100.00%> (+0.98%) ⬆️
src/core/binarycodec/types/mod.rs 73.61% <0.00%> (-0.20%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes a panic in the XRPL binary codec serializer by making VL-length encoding (write_length_encoded) return an error when the input exceeds MAX_LENGTH_VALUE rather than calling unwrap() and panicking. This improves robustness when serializing large variable-length fields and aligns behavior with XRPLCoreResult-based error handling across the codec.

Changes:

  • Changed Serialization::{write_length_encoded, write_field_and_value} to return XRPLCoreResult<&Self> and propagated errors via ? instead of panicking.
  • Updated downstream call site(s) to use ? for propagation and updated doc examples to unwrap() in doctest context.
  • Added a regression test ensuring oversized VL values return InvalidVariableLengthTooLarge instead of panicking.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
src/core/binarycodec/types/mod.rs Propagates write_field_and_value failures from STObject serialization using ?.
src/core/binarycodec/binary_wrappers.rs Makes length-encoded writes fallible (Result), replaces unwrap() with ?, updates tests/docs, and adds regression coverage for oversized inputs.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/core/binarycodec/binary_wrappers.rs Outdated
Comment on lines 445 to 453
let mut byte_object: Vec<u8> = Vec::new();
if encode_value {
// write value to byte_object
byte_object.extend_from_slice(value);
}
// TODO Handle unwrap better
let length_prefix = _encode_variable_length_prefix(&byte_object.len()).unwrap();
let length_prefix = _encode_variable_length_prefix(&byte_object.len())?;

self.extend_from_slice(&length_prefix);
self.extend_from_slice(&byte_object);
Comment thread src/core/binarycodec/binary_wrappers.rs Outdated
Comment on lines 388 to 392
/// let mut test_bytes: Vec<u8> = [0, 17, 34].to_vec();
/// let mut serializer: BinarySerializer = BinarySerializer::new();
///
/// serializer.write_length_encoded(&mut test_bytes, true);
/// serializer.write_length_encoded(&mut test_bytes, true).unwrap();
/// assert_eq!(expected, serializer);
…f unwrap (#268)

Replace the `.unwrap()` on `_encode_variable_length_prefix` in
`write_length_encoded` with `?`, changing the return type from `&Self`
to `XRPLCoreResult<&Self>`. Propagate the Result through
`write_field_and_value` and its call site in `STObject::try_from_value`.

Adds a regression test that asserts an `Err` is returned when the
value length exceeds `MAX_LENGTH_VALUE` (918744 bytes) rather than
panicking at runtime.
…ngth_encoded

Compute the length prefix directly from value.len() instead of
copying into an intermediate Vec<u8> first. write value straight
into self when encode_value is true, removing one allocation and
one copy per call.

Also drop the unnecessary mut binding and &mut borrow in the doc
example — the method signature takes &[u8] and never mutates the
input.
@e-desouza
e-desouza force-pushed the fix/issue-268-serializer-unwrap branch from 4bdcf7b to 214f7d5 Compare July 15, 2026 16:41
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.

_encode_variable_length_prefix(..).unwrap() in write_length_encoded

2 participants