Skip to content

Commit

Permalink
Merge pull request #80 from e00E/fix-int-in-range
Browse files Browse the repository at this point in the history
Fix int_in_range using more bytes than necessary
  • Loading branch information
fitzgen committed May 19, 2021
2 parents fab54ed + 7b85d6c commit d14dbe5
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/unstructured.rs
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 @@ -699,4 +699,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 d14dbe5

Please sign in to comment.