mirror of
https://github.com/rust-lang-nursery/rust-cookbook
synced 2025-02-16 12:18:27 +00:00
Use gen_range instead of rand::choose (#527)
This commit is contained in:
parent
353ccf46cc
commit
99e3d6b333
1 changed files with 15 additions and 10 deletions
|
@ -2,25 +2,30 @@
|
||||||
|
|
||||||
[![rand-badge]][rand] [![cat-os-badge]][cat-os]
|
[![rand-badge]][rand] [![cat-os-badge]][cat-os]
|
||||||
|
|
||||||
Randomly generates a string of given length ASCII characters with custom user-defined bytestring, with [`choose`].
|
Randomly generates a string of given length ASCII characters with custom
|
||||||
|
user-defined bytestring, with [`gen_range`].
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
extern crate rand;
|
extern crate rand;
|
||||||
|
|
||||||
use rand::seq::SliceRandom;
|
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
|
use rand::Rng;
|
||||||
abcdefghijklmnopqrstuvwxyz\
|
const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
|
||||||
0123456789)(*&^%$#@!~";
|
abcdefghijklmnopqrstuvwxyz\
|
||||||
|
0123456789)(*&^%$#@!~";
|
||||||
|
const PASSWORD_LEN: usize = 30;
|
||||||
let mut rng = rand::thread_rng();
|
let mut rng = rand::thread_rng();
|
||||||
let password: Option<String> = (0..30)
|
|
||||||
.map(|_| Some(*CHARSET.choose(&mut rng)? as char))
|
let password: String = (0..PASSWORD_LEN)
|
||||||
|
.map(|_| {
|
||||||
|
let idx = rng.gen_range(0, CHARSET.len());
|
||||||
|
// This is safe because `idx` is in range of `CHARSET`
|
||||||
|
char::from(unsafe { *CHARSET.get_unchecked(idx) })
|
||||||
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
println!("{:?}", password);
|
println!("{:?}", password);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
[`choose`]: https://docs.rs/rand/*/rand/trait.Rng.html#method.choose
|
[`gen_range`]: https://docs.rs/rand/*/rand/trait.Rng.html#method.gen_range
|
||||||
|
|
Loading…
Add table
Reference in a new issue