From 7b85d6c4409ad5a3aad7c824a5f655d56cc13553 Mon Sep 17 00:00:00 2001 From: Valentin Kettner Date: Tue, 18 May 2021 00:20:38 +0200 Subject: [PATCH] Fix int_in_range using more bytes than necessary `offset` counts the number of bytes but the range is shifted as if it counted the number of bits. This causes int_in_range to consume more bytes than necessary. The `int_in_range::(0..=u8::MAX)` case from the new test fails without this commit. --- src/unstructured.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/unstructured.rs b/src/unstructured.rs index 9e2f497..ea3b7f1 100644 --- a/src/unstructured.rs +++ b/src/unstructured.rs @@ -322,7 +322,7 @@ impl<'a> Unstructured<'a> { let mut offset: usize = 0; while offset < mem::size_of::() - && (range >> T::Widest::from_usize(offset)) > T::Widest::ZERO + && (range >> T::Widest::from_usize(offset * 8)) > T::Widest::ZERO { let byte = bytes.next().ok_or(Error::NotEnoughData)?; result = (result << 8) | T::Widest::from_u8(byte); @@ -701,4 +701,16 @@ mod tests { let choice = *u.choose(&[42]).unwrap(); assert_eq!(choice, 42) } + + #[test] + fn int_in_range_uses_minimal_amount_of_bytes() { + let mut u = Unstructured::new(&[1]); + u.int_in_range::(0..=u8::MAX).unwrap(); + + let mut u = Unstructured::new(&[1]); + u.int_in_range::(0..=u8::MAX as u32).unwrap(); + + let mut u = Unstructured::new(&[1]); + u.int_in_range::(0..=u8::MAX as u32 + 1).unwrap_err(); + } }