tree_sitter_cli/fuzz/
edits.rs

1use super::random::Rand;
2
3#[derive(Debug)]
4pub struct Edit {
5    pub position: usize,
6    pub deleted_length: usize,
7    pub inserted_text: Vec<u8>,
8}
9
10#[must_use]
11pub fn invert_edit(input: &[u8], edit: &Edit) -> Edit {
12    let position = edit.position;
13    let removed_content = &input[position..(position + edit.deleted_length)];
14    Edit {
15        position,
16        deleted_length: edit.inserted_text.len(),
17        inserted_text: removed_content.to_vec(),
18    }
19}
20
21pub fn get_random_edit(rand: &mut Rand, input: &[u8]) -> Edit {
22    let choice = rand.unsigned(10);
23    if choice < 2 {
24        // Insert text at end
25        let inserted_text = rand.words(3);
26        Edit {
27            position: input.len(),
28            deleted_length: 0,
29            inserted_text,
30        }
31    } else if choice < 5 {
32        // Delete text from the end
33        let deleted_length = rand.unsigned(30).min(input.len());
34        Edit {
35            position: input.len() - deleted_length,
36            deleted_length,
37            inserted_text: vec![],
38        }
39    } else if choice < 8 {
40        // Insert at a random position
41        let position = rand.unsigned(input.len());
42        let word_count = 1 + rand.unsigned(3);
43        let inserted_text = rand.words(word_count);
44        Edit {
45            position,
46            deleted_length: 0,
47            inserted_text,
48        }
49    } else {
50        // Replace at random position
51        let position = rand.unsigned(input.len());
52        let deleted_length = rand.unsigned(input.len() - position);
53        let word_count = 1 + rand.unsigned(3);
54        let inserted_text = rand.words(word_count);
55        Edit {
56            position,
57            deleted_length,
58            inserted_text,
59        }
60    }
61}