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 43Sample values from an array with `O(n)` complexity (`n` is the length of array): 44 45```rust 46fastrand::choose_multiple(vec![1, 4, 5].iter(), 2); 47fastrand::choose_multiple(0..20, 12); 48``` 49 50Shuffle an array: 51 52```rust 53let mut v = vec![1, 2, 3, 4, 5]; 54fastrand::shuffle(&mut v); 55``` 56 57Generate a random `Vec` or `String`: 58 59```rust 60use std::iter::repeat_with; 61 62let v: Vec<i32> = repeat_with(|| fastrand::i32(..)).take(10).collect(); 63let s: String = repeat_with(fastrand::alphanumeric).take(10).collect(); 64``` 65 66To get reproducible results on every run, initialize the generator with a seed: 67 68```rust 69// Pick an arbitrary number as seed. 70fastrand::seed(7); 71 72// Now this prints the same number on every run: 73println!("{}", fastrand::u32(..)); 74``` 75 76To be more efficient, create a new `Rng` instance instead of using the thread-local 77generator: 78 79```rust 80use std::iter::repeat_with; 81 82let rng = fastrand::Rng::new(); 83let mut bytes: Vec<u8> = repeat_with(|| rng.u8(..)).take(10_000).collect(); 84``` 85 86This crate aims to expose a core set of useful randomness primitives. For more niche algorithms, consider using the [`fastrand-contrib`] crate alongside this one. 87 88# Features 89 90- `std` (enabled by default): Enables the `std` library. This is required for the global 91 generator and global entropy. Without this feature, [`Rng`] can only be instantiated using 92 the [`with_seed`](https://docs.rs/fastrand/latest/fastrand/struct.Rng.html#method.with_seed) method. 93- `js`: Assumes that WebAssembly targets are being run in a JavaScript environment. 94 95[`fastrand-contrib`]: https://crates.io/crates/fastrand-contrib 96 97## License 98 99Licensed under either of 100 101 * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 102 * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 103 104at your option. 105 106#### Contribution 107 108Unless you explicitly state otherwise, any contribution intentionally submitted 109for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 110dual licensed as above, without any additional terms or conditions. 111