Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Impl Distribution<u8> for Alphanumeric #935

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 9 additions & 2 deletions src/distributions/other.rs
Expand Up @@ -16,7 +16,7 @@ use crate::Rng;

// ----- Sampling distributions -----

/// Sample a `char`, uniformly distributed over ASCII letters and numbers:
/// Sample a `char` or `u8`, uniformly distributed over ASCII letters and numbers:
/// a-z, A-Z and 0-9.
///
/// # Example
Expand Down Expand Up @@ -62,6 +62,13 @@ impl Distribution<char> for Standard {

impl Distribution<char> for Alphanumeric {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> char {
let byte: u8 = self.sample(rng);
byte as char
}
}

impl Distribution<u8> for Alphanumeric {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> u8 {
const RANGE: u32 = 26 + 26 + 10;
const GEN_ASCII_STR_CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz\
Expand All @@ -73,7 +80,7 @@ impl Distribution<char> for Alphanumeric {
loop {
let var = rng.next_u32() >> (32 - 6);
if var < RANGE {
return GEN_ASCII_STR_CHARSET[var as usize] as char;
return GEN_ASCII_STR_CHARSET[var as usize];
}
}
}
Expand Down