From ea33f37fbf5bdd344d19738ad99ca0e2716961db Mon Sep 17 00:00:00 2001 From: Prince Jain Date: Wed, 21 Oct 2026 15:28:47 +0530 Subject: [PATCH] Assert nbytes <= 8 in sign_extend (#832) Add a debug_assert!(nbytes <= 8) check in sign_extend so out-of-range byte counts fail immediately in debug builds instead of underflowing 8 - nbytes, while keeping the nbytes == 0 branch intact. --- src/buf/buf_impl.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/buf/buf_impl.rs b/src/buf/buf_impl.rs index 2497a78ff..af5f90c00 100644 --- a/src/buf/buf_impl.rs +++ b/src/buf/buf_impl.rs @@ -86,6 +86,7 @@ macro_rules! buf_get_impl { // https://en.wikipedia.org/wiki/Sign_extension fn sign_extend(val: u64, nbytes: usize) -> i64 { + debug_assert!(nbytes <= 8, "nbytes must be in [0, 8]"); if nbytes == 0 { // avoid `val << 64` panic 0 @@ -2965,3 +2966,20 @@ impl> Buf for std::io::Cursor { // The existence of this function makes the compiler catch if the Buf // trait is "object-safe" or not. fn _assert_trait_object(_b: &dyn Buf) {} + +#[cfg(test)] +mod tests { + use super::sign_extend; + + #[test] + fn sign_extend_zero_bytes() { + assert_eq!(sign_extend(u64::MAX, 0), 0); + } + + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "nbytes must be in [0, 8]")] + fn sign_extend_more_than_eight_bytes_panics_in_debug() { + sign_extend(0, 9); + } +}