Skip to content

Commit 7f321fa

Browse files
qohvks
authored andcommitted
Impl Distribution<u8> for Alphanumeric
Sampling a random alphanumeric string by collecting chars (that are known to be ASCII) into a String involves re-allocation as String is encoding to UTF-8, via the example: ```rust let chars: String = iter::repeat(()) .map(|()| rng.sample(Alphanumeric)) .take(7) .collect(); ``` I wanted to get rid of the clearly unnecessary re-allocations in my applications, so I needed to be able to access to the ASCII characters as simple bytes. It seems like that was already what was going on inside Alphanumeric however, it was just internal. This PR changes the `Distribution<char>` impl to provide `u8`s (which it generates internally) instead, and implements the previous `Distribution<char>` using it. One could then, for example, do this: ```rust let mut rng = thread_rng(); let bytes = (0..7).map(|_| rng.sample(ByteAlphanumeric)).collect(); let chars = unsafe { String::from_utf8_unchecked(bytes) }; ```
1 parent dca9cb5 commit 7f321fa

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

src/distributions/other.rs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use serde::{Serialize, Deserialize};
1919

2020
// ----- Sampling distributions -----
2121

22-
/// Sample a `char`, uniformly distributed over ASCII letters and numbers:
22+
/// Sample a `char` or `u8`, uniformly distributed over ASCII letters and numbers:
2323
/// a-z, A-Z and 0-9.
2424
///
2525
/// # Example
@@ -83,6 +83,13 @@ impl Distribution<char> for Standard {
8383

8484
impl Distribution<char> for Alphanumeric {
8585
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> char {
86+
let byte: u8 = self.sample(rng);
87+
byte as char
88+
}
89+
}
90+
91+
impl Distribution<u8> for Alphanumeric {
92+
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> u8 {
8693
const RANGE: u32 = 26 + 26 + 10;
8794
const GEN_ASCII_STR_CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
8895
abcdefghijklmnopqrstuvwxyz\
@@ -94,7 +101,7 @@ impl Distribution<char> for Alphanumeric {
94101
loop {
95102
let var = rng.next_u32() >> (32 - 6);
96103
if var < RANGE {
97-
return GEN_ASCII_STR_CHARSET[var as usize] as char;
104+
return GEN_ASCII_STR_CHARSET[var as usize];
98105
}
99106
}
100107
}

0 commit comments

Comments
 (0)