Skip to content

Commit 59a3e3e

Browse files
authored
Merge pull request #2305 from bit-aloo/2026-08-18-return-unclaimed-error
return unclaimed bytes and not remove them
2 parents d1808b1 + 84c356d commit 59a3e3e

2 files changed

Lines changed: 22 additions & 4 deletions

File tree

sv2/binary-sv2/src/lib.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -87,11 +87,14 @@ pub fn to_bytes<T: Encodable + GetSize>(src: T) -> Result<Vec<u8>, Error> {
8787
Ok(result)
8888
}
8989

90-
/// Encodes the SV2 data type to the provided byte slice.
90+
/// Encodes the SV2 data type to the provided byte slice and returns the number of bytes
91+
/// written.
92+
///
93+
/// `dst` may be larger than the encoded value; the bytes past the returned length are left
94+
/// untouched, so a caller reusing a buffer must only transmit `&dst[..written]`.
9195
#[allow(clippy::wrong_self_convention)]
92-
pub fn to_writer<T: Encodable>(src: T, dst: &mut [u8]) -> Result<(), Error> {
93-
src.to_bytes(dst)?;
94-
Ok(())
96+
pub fn to_writer<T: Encodable>(src: T, dst: &mut [u8]) -> Result<usize, Error> {
97+
src.to_bytes(dst)
9598
}
9699

97100
/// Decodes an SV2-encoded byte slice into the specified data type.

sv2/binary-sv2/tests/test.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -732,3 +732,18 @@ mod test_b064k_length_prefix {
732732
);
733733
}
734734
}
735+
736+
mod test_to_writer_len {
737+
use super::*;
738+
739+
#[test]
740+
fn to_writer_reports_bytes_written_into_oversized_buffer() {
741+
let mut oversized = [0xAAu8; 16];
742+
743+
let written = to_writer(0x0102_0304_u32, &mut oversized[..]).unwrap();
744+
745+
assert_eq!(written, 4);
746+
assert_eq!(&oversized[..written], &[0x04, 0x03, 0x02, 0x01]);
747+
assert!(oversized[written..].iter().all(|b| *b == 0xAA));
748+
}
749+
}

0 commit comments

Comments
 (0)