1# fastrand 2 3[]( 4https://github.com/smol-rs/fastrand/actions) 5[]( 6https://github.com/smol-rs/fastrand) 7[]( 8https://crates.io/crates/fastrand) 9[]( 10https://docs.rs/fastrand) 11 12A simple and fast random number generator. 13 14The implementation uses [Wyrand](https://github.com/wangyi-fudan/wyhash), a simple and fast 15generator but **not** cryptographically secure. 16 17## Examples 18 19Flip a coin: 20 21```rust 22if fastrand::bool() { 23 println!("heads"); 24} else { 25 println!("tails"); 26} 27``` 28 29Generate a random `i32`: 30 31```rust 32let num = fastrand::i32(..); 33``` 34 35Choose a random element in an array: 36 37```rust 38let v = vec![1, 2, 3, 4, 5]; 39let i = fastrand::usize(..v.len()); 40let elem = v[i]; 41``` 42 43Shuffle an array: 44 45```rust 46let mut v = vec![1, 2, 3, 4, 5]; 47fastrand::shuffle(&mut v); 48``` 49 50Generate a random `Vec` or `String`: 51 52```rust 53use std::iter::repeat_with; 54 55let v: Vec<i32> = repeat_with(|| fastrand::i32(..)).take(10).collect(); 56let s: String = repeat_with(fastrand::alphanumeric).take(10).collect(); 57``` 58 59To get reproducible results on every run, initialize the generator with a seed: 60 61```rust 62// Pick an arbitrary number as seed. 63fastrand::seed(7); 64 65// Now this prints the same number on every run: 66println!("{}", fastrand::u32(..)); 67``` 68 69To be more efficient, create a new `Rng` instance instead of using the thread-local 70generator: 71 72```rust 73use std::iter::repeat_with; 74 75let rng = fastrand::Rng::new(); 76let mut bytes: Vec<u8> = repeat_with(|| rng.u8(..)).take(10_000).collect(); 77``` 78 79## License 80 81Licensed under either of 82 83 * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 84 * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 85 86at your option. 87 88#### Contribution 89 90Unless you explicitly state otherwise, any contribution intentionally submitted 91for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 92dual licensed as above, without any additional terms or conditions. 93