Skip to main content

sql_splitter/render/
random.rs

1//! Block-buffered, unbiased sampling from a fixed alphanumeric alphabet.
2//!
3//! Drawing one `ChaCha8Rng` value per character is the dominant cost of
4//! simple-mode generation. `RandomBlock` instead fills a fixed-size buffer in
5//! one call and hands out bytes from it, refilling only once the buffer is
6//! exhausted.
7
8use rand::Rng;
9use rand_chacha::ChaCha8Rng;
10
11/// The 63-character alphabet random strings are drawn from: lowercase,
12/// uppercase, digits, and a trailing space. This matches the alphabet used
13/// by `test_data_gen`'s streaming generator so seeded output stays
14/// comparable across the two implementations.
15const ALPHABET: &[u8; 63] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
16
17/// Size of the buffer refilled from the underlying RNG in one call.
18const BLOCK_SIZE: usize = 4096;
19
20/// A block-buffered source of unbiased, alphabet-restricted random bytes.
21///
22/// Each buffered byte's low six bits select one of 64 possible values; the
23/// alphabet has only 63 characters, so a byte whose low six bits equal 63 is
24/// rejected and redrawn. Rejecting rather than reducing modulo 63 keeps every
25/// alphabet character equally likely.
26pub struct RandomBlock {
27    rng: ChaCha8Rng,
28    buf: [u8; BLOCK_SIZE],
29    pos: usize,
30}
31
32impl RandomBlock {
33    /// Create a block sampler backed by `rng`, filling the first block
34    /// immediately.
35    pub fn new(mut rng: ChaCha8Rng) -> Self {
36        let mut buf = [0u8; BLOCK_SIZE];
37        rng.fill_bytes(&mut buf);
38        Self { rng, buf, pos: 0 }
39    }
40
41    /// Return the next raw buffered byte, refilling the block first if it is
42    /// exhausted.
43    fn next_byte(&mut self) -> u8 {
44        if self.pos >= self.buf.len() {
45            self.rng.fill_bytes(&mut self.buf);
46            self.pos = 0;
47        }
48        let byte = self.buf[self.pos];
49        self.pos += 1;
50        byte
51    }
52
53    /// Sample a single character from the 63-character alphanumeric
54    /// alphabet, uniformly at random.
55    pub fn next_alphanumeric(&mut self) -> u8 {
56        loop {
57            let idx = self.next_byte() & 0b0011_1111;
58            if idx != 63 {
59                return ALPHABET[idx as usize];
60            }
61        }
62    }
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68    use rand_chacha::rand_core::SeedableRng;
69
70    #[test]
71    fn samples_stay_in_alphabet_and_are_seed_reproducible() {
72        let mut a = RandomBlock::new(ChaCha8Rng::from_seed([7u8; 32]));
73        let mut b = RandomBlock::new(ChaCha8Rng::from_seed([7u8; 32]));
74
75        let bytes_a: Vec<u8> = (0..10_000).map(|_| a.next_alphanumeric()).collect();
76        let bytes_b: Vec<u8> = (0..10_000).map(|_| b.next_alphanumeric()).collect();
77
78        assert!(bytes_a.iter().all(|byte| ALPHABET.contains(byte)));
79        assert_eq!(bytes_a, bytes_b);
80    }
81
82    #[test]
83    fn different_seeds_diverge() {
84        let mut a = RandomBlock::new(ChaCha8Rng::from_seed([1u8; 32]));
85        let mut b = RandomBlock::new(ChaCha8Rng::from_seed([2u8; 32]));
86        assert_ne!(a.next_alphanumeric(), b.next_alphanumeric());
87    }
88}