Skip to content

rewrite gen_range to take any range type instead of low, high#21

Open
cyrgani wants to merge 1 commit intonot-fl3:masterfrom
cyrgani:range-type-arguments
Open

rewrite gen_range to take any range type instead of low, high#21
cyrgani wants to merge 1 commit intonot-fl3:masterfrom
cyrgani:range-type-arguments

Conversation

@cyrgani
Copy link
Copy Markdown
Contributor

@cyrgani cyrgani commented Apr 14, 2025

This is a breaking change and requires the next released version to be 0.3.0.

This PR rewrites gen_range and gen_range_with_state to take one argument that is any range type (impl RangeBounds<T>) instead of two arguments low and high. It also adds an example to show that all core range types are supported.

This has several advantages:

  1. Right now, there is no easy way to get "a random byte" / "a random u8", since quad_rand::gen_range(0, 255) is never going to return 255, as this program demonstrates:
fn main() {
    for _ in 0..1_000_000 {
        let r: u8 = quad_rand::gen_range(0, 255);
        assert!(r != 255);
    }
}

With this PR, one would simply write quad_rand::gen_range(0..=255) (or just quad_rand::gen_range(..) as long as the type of the range elements can be inferred) and get an u8 that can be 255 too.
2. It is currently not always clear to a user whether the high argument is inclusive or exclusive, which has caused confusion and bugs in the past (e.g. #13). The new API solves that problem by making inclusive ranges explicitly low..=high and exclusive ones low..high.

It is also more consistent with other ecosystem crates like rand.

Fixes not-fl3/macroquad#403.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Have macroquad::rand::gen_range function take range expressions

1 participant