Skip to content

Commit bb51ab5

Browse files
committed
Implement Alphabetic with a branchless jump
This still barely got a faster benchmark despite being one of the quickest solutions on theory
1 parent e5e59ba commit bb51ab5

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

src/distr/other.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -155,10 +155,11 @@ impl Distribution<u8> for Alphanumeric {
155155
impl Distribution<u8> for Alphabetic {
156156
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> u8 {
157157
const RANGE: u8 = 26 + 26;
158-
const GEN_ASCII_STR_CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
159-
abcdefghijklmnopqrstuvwxyz";
160158

161-
GEN_ASCII_STR_CHARSET[rng.random_range(0..RANGE) as usize]
159+
let offset = rng.random_range(0..RANGE) + b'A';
160+
161+
// Account for upper-cases
162+
offset + (offset > b'Z') as u8 * (b'a' - b'Z' - 1)
162163
}
163164
}
164165

@@ -300,6 +301,8 @@ where
300301

301302
#[cfg(test)]
302303
mod tests {
304+
use std::dbg;
305+
303306
use super::*;
304307
use crate::RngCore;
305308

@@ -350,6 +353,7 @@ mod tests {
350353
for _ in 0..100 {
351354
let c: char = rng.sample(Alphabetic).into();
352355
incorrect |= !c.is_ascii_alphabetic();
356+
dbg!(c);
353357
}
354358
assert!(!incorrect);
355359
}

0 commit comments

Comments
 (0)