Skip to content

Commit

Permalink
Fix int_in_range using more bytes than necessary
Browse files Browse the repository at this point in the history
`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::<u32>(0..=u8::MAX)` case from the new test fails
without this commit.
  • Loading branch information
e00E committed May 17, 2021
1 parent a2ce10b commit 7b85d6c
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/unstructured.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ impl<'a> Unstructured<'a> {
let mut offset: usize = 0;

while offset < mem::size_of::<T>()
&& (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);
Expand Down Expand Up @@ -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::<u8>(0..=u8::MAX).unwrap();

let mut u = Unstructured::new(&[1]);
u.int_in_range::<u32>(0..=u8::MAX as u32).unwrap();

let mut u = Unstructured::new(&[1]);
u.int_in_range::<u32>(0..=u8::MAX as u32 + 1).unwrap_err();
}
}

0 comments on commit 7b85d6c

Please sign in to comment.