From 99e3d6b333ecbbf9b44298e831e0ccb053466dff Mon Sep 17 00:00:00 2001 From: lzutao Date: Tue, 16 Apr 2019 11:13:45 +0700 Subject: [PATCH] Use gen_range instead of rand::choose (#527) --- src/algorithms/randomness/rand-choose.md | 25 ++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/src/algorithms/randomness/rand-choose.md b/src/algorithms/randomness/rand-choose.md index acf0bed..8a95c63 100644 --- a/src/algorithms/randomness/rand-choose.md +++ b/src/algorithms/randomness/rand-choose.md @@ -2,25 +2,30 @@ [![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 extern crate rand; -use rand::seq::SliceRandom; - fn main() { - const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ - abcdefghijklmnopqrstuvwxyz\ - 0123456789)(*&^%$#@!~"; - + use rand::Rng; + const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ + abcdefghijklmnopqrstuvwxyz\ + 0123456789)(*&^%$#@!~"; + const PASSWORD_LEN: usize = 30; let mut rng = rand::thread_rng(); - let password: Option = (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(); 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