Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

distributions/uniform: fix panic in gen_range(0..=MAX) #1087

Commits on Jan 12, 2021

  1. 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.
    mautier committed Jan 12, 2021
    Copy the full SHA
    4e8c7a4 View commit details
    Browse the repository at this point in the history
  2. Copy the full SHA
    2c9085a View commit details
    Browse the repository at this point in the history