sql_splitter/render/
random.rs1use rand::Rng;
9use rand_chacha::ChaCha8Rng;
10
11const ALPHABET: &[u8; 63] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
16
17const BLOCK_SIZE: usize = 4096;
19
20pub struct RandomBlock {
27 rng: ChaCha8Rng,
28 buf: [u8; BLOCK_SIZE],
29 pos: usize,
30}
31
32impl RandomBlock {
33 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 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 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}