Skip to main content

tree_sitter_cli/fuzz/
random.rs

1use rand::{RngExt, SeedableRng, distr::Alphanumeric, rngs::StdRng};
2
3const OPERATORS: &[char] = &[
4    '+', '-', '<', '>', '(', ')', '*', '/', '&', '|', '!', ',', '.', '%',
5];
6
7pub struct Rand(StdRng);
8
9impl Rand {
10    #[must_use]
11    pub fn new(seed: usize) -> Self {
12        Self(StdRng::seed_from_u64(seed as u64))
13    }
14
15    pub fn unsigned(&mut self, max: usize) -> usize {
16        self.0.random_range(0..=max)
17    }
18
19    pub fn words(&mut self, max_count: usize) -> Vec<u8> {
20        let word_count = self.unsigned(max_count);
21        let mut result = Vec::with_capacity(2 * word_count);
22        for i in 0..word_count {
23            if i > 0 {
24                if self.unsigned(5) == 0 {
25                    result.push(b'\n');
26                } else {
27                    result.push(b' ');
28                }
29            }
30            if self.unsigned(3) == 0 {
31                let index = self.unsigned(OPERATORS.len() - 1);
32                result.push(OPERATORS[index] as u8);
33            } else {
34                for _ in 0..self.unsigned(8) {
35                    result.push(self.0.sample(Alphanumeric));
36                }
37            }
38        }
39        result
40    }
41}