Skip to content

Commit 6a6b9fd

Browse files
authored
Merge pull request #1087 from GautierMinster/fix_uniform_int_panic_on_full_inclusive_range
distributions/uniform: fix panic in gen_range(0..=MAX)
2 parents bda9974 + 2c9085a commit 6a6b9fd

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@ A [separate changelog is kept for rand_core](rand_core/CHANGELOG.md).
88

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

11+
## [0.8.2] - 2021-01-12
12+
### Fixes
13+
- Fix panic in `UniformInt::sample_single_inclusive` and `Rng::gen_range` when
14+
providing a full integer range (eg `0..=MAX`) (#1087)
15+
1116
## [0.8.1] - 2020-12-31
1217
### Other
1318
- Enable all stable features in the playground (#1081)

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "rand"
3-
version = "0.8.1"
3+
version = "0.8.2"
44
authors = ["The Rand Project Developers", "The Rust Project Developers"]
55
license = "MIT OR Apache-2.0"
66
readme = "README.md"

src/distributions/uniform.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -521,6 +521,12 @@ macro_rules! uniform_int_impl {
521521
let high = *high_b.borrow();
522522
assert!(low <= high, "UniformSampler::sample_single_inclusive: low > high");
523523
let range = high.wrapping_sub(low).wrapping_add(1) as $unsigned as $u_large;
524+
// If the above resulted in wrap-around to 0, the range is $ty::MIN..=$ty::MAX,
525+
// and any integer will do.
526+
if range == 0 {
527+
return rng.gen();
528+
}
529+
524530
let zone = if ::core::$unsigned::MAX <= ::core::u16::MAX as $unsigned {
525531
// Using a modulus is faster than the approximation for
526532
// i8 and i16. I suppose we trade the cost of one
@@ -1235,6 +1241,11 @@ mod tests {
12351241
let v = <$ty as SampleUniform>::Sampler::sample_single(low, high, &mut rng);
12361242
assert!($le(low, v) && $lt(v, high));
12371243
}
1244+
1245+
for _ in 0..1000 {
1246+
let v = <$ty as SampleUniform>::Sampler::sample_single_inclusive(low, high, &mut rng);
1247+
assert!($le(low, v) && $le(v, high));
1248+
}
12381249
}
12391250
}};
12401251

0 commit comments

Comments
 (0)