9 releases

Uses new Rust 2021

0.1.8 Nov 3, 2022
0.1.7 Mar 18, 2022
0.1.6 Apr 22, 2021
0.1.4 Mar 11, 2021
0.1.2 Jun 27, 2020

#131 in Rust patterns

Download history 2574/week @ 2022-08-15 2278/week @ 2022-08-22 2693/week @ 2022-08-29 3032/week @ 2022-09-05 2432/week @ 2022-09-12 2318/week @ 2022-09-19 2939/week @ 2022-09-26 2356/week @ 2022-10-03 2575/week @ 2022-10-10 2205/week @ 2022-10-17 2666/week @ 2022-10-24 3396/week @ 2022-10-31 2949/week @ 2022-11-07 3165/week @ 2022-11-14 3087/week @ 2022-11-21 2291/week @ 2022-11-28

11,887 downloads per month
Used in 13 crates (4 directly)

MIT license

30KB
426 lines

Random Number

CI

Generate random numbers quickly.

The random! Marco

use random_number::random;

let n: u8 = random!();
println!("{}", n); // 0 ~ 255

let n: f64 = random!();
println!("{}", n); // 0.0 ~ 1.0

let n: u8 = random!(..=10);
println!("{}", n); // 0 ~ 10

let n: u8 = random!(..=9);
println!("{}", n); // 0 ~ 9

let n: u8 = random!(10..);
println!("{}", n); // 10 ~ 255

let n: i8 = random!(-2..=12);
println!("{}", n); // -2 ~ 12

let n: u8 = random!(12, 20);
println!("{}", n); // 12 ~ 20

let n: u8 = random!(20, 12);
println!("{}", n); // 12 ~ 20

The random number generator can be reused by adding it to the random! macro as the last argument.

use random_number::random;

let mut rng = random_number::rand::thread_rng();

let n: u8 = random!(rng);
println!("{}", n); // 0 ~ 255

let n: u8 = random!(..=10, rng);
println!("{}", n); // 0 ~ 10

let n: u8 = random!(20, 12, rng);
println!("{}", n); // 12 ~ 20

The random_ranged Function

If the range is not literal, for example, a variable, var_range, storing an instance that implements the RangeBounds trait, the var_range variable cannot be used in the random! macro.

let var_range = 1..=10;

let n: u8 = random_number::random!(var_range); // compile error

In this case, use the random_ranged function instead.

let var_range = 1..=10;

let n: u8 = random_number::random_ranged(var_range);
println!("{}", n); // 1 ~ 10

The random_fill! Marco

The random_fill! marco can be used to fill a slice with random numbers. The usage is like the random! macro. Just add a slice as the first argument when using the random_fill! macro.

let mut a = [0i8; 32];
random_number::random_fill!(a, -2..=12);

println!("{:?}", a);

The random_fill_ranged Function

let var_range = 1..=10;

let mut a = [0u8; 32];
random_number::random_fill_ranged(&mut a, var_range);

println!("{:?}", a);

Crates.io

https://crates.io/crates/random-number

Documentation

https://docs.rs/random-number

License

MIT

Dependencies

~0.5–1MB
~20K SLoC