Skip to content

Commit 4e8c7a4

Browse files
committed
distributions/uniform: fix panic in gen_range(0..=MAX)
This commit fixes a panic when generating a single sample in an inclusive range that spans the entire integer range, eg for u8: ```rust rng.gen_range(0..=u8::MAX) // panicked at 'attempt to add with overflow', src/distributions/uniform.rs:529:42 ``` [Playground example](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&code=use%20rand%3A%3ARng%3B%0A%0Afn%20main()%20%7B%0A%20%20%20%20rand%3A%3Athread_rng().gen_range(0u8..%3D255u8)%3B%0A%7D). The cause is a discrepancy between the "single sample" and the "many samples" codepaths: ```rust // Ok UniformSampler::new_inclusive(u8::MIN, u8::MAX).sample(&mut rng); // Panic UniformSampler::sample_single_inclusive(u8::MIN, u8::MAX, &mut rng); ``` In `sample`, a `range` of 0 is interpreted to mean "sample from the whole range". In `sample_range_inclusive`, no check is performed, which leads to overflow when computing the `ints_to_reject`. **Testing** - Added a test case. - Old code panics, new code passes.
1 parent bda9974 commit 4e8c7a4

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

src/distributions/uniform.rs

+11
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)