Skip to content

Commit

Permalink
Merge pull request #1087 from GautierMinster/fix_uniform_int_panic_on…
Browse files Browse the repository at this point in the history
…_full_inclusive_range

distributions/uniform: fix panic in gen_range(0..=MAX)
  • Loading branch information
dhardy authored Jan 13, 2021
2 parents bda9974 + 2c9085a commit 6a6b9fd
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ A [separate changelog is kept for rand_core](rand_core/CHANGELOG.md).

You may also find the [Upgrade Guide](https://rust-random.github.io/book/update.html) useful.

## [0.8.2] - 2021-01-12
### Fixes
- Fix panic in `UniformInt::sample_single_inclusive` and `Rng::gen_range` when
providing a full integer range (eg `0..=MAX`) (#1087)

## [0.8.1] - 2020-12-31
### Other
- Enable all stable features in the playground (#1081)
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "rand"
version = "0.8.1"
version = "0.8.2"
authors = ["The Rand Project Developers", "The Rust Project Developers"]
license = "MIT OR Apache-2.0"
readme = "README.md"
Expand Down
11 changes: 11 additions & 0 deletions src/distributions/uniform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,12 @@ macro_rules! uniform_int_impl {
let high = *high_b.borrow();
assert!(low <= high, "UniformSampler::sample_single_inclusive: low > high");
let range = high.wrapping_sub(low).wrapping_add(1) as $unsigned as $u_large;
// If the above resulted in wrap-around to 0, the range is $ty::MIN..=$ty::MAX,
// and any integer will do.
if range == 0 {
return rng.gen();
}

let zone = if ::core::$unsigned::MAX <= ::core::u16::MAX as $unsigned {
// Using a modulus is faster than the approximation for
// i8 and i16. I suppose we trade the cost of one
Expand Down Expand Up @@ -1235,6 +1241,11 @@ mod tests {
let v = <$ty as SampleUniform>::Sampler::sample_single(low, high, &mut rng);
assert!($le(low, v) && $lt(v, high));
}

for _ in 0..1000 {
let v = <$ty as SampleUniform>::Sampler::sample_single_inclusive(low, high, &mut rng);
assert!($le(low, v) && $le(v, high));
}
}
}};

Expand Down

0 comments on commit 6a6b9fd

Please sign in to comment.