dd_sds/
encoding.rs

1/// Specifies how indices are calculated for rule matches
2pub trait Encoding: Sized {
3    type Index: Sized + 'static;
4    type IndexShift: Sized;
5
6    fn zero_index() -> Self::Index;
7    fn zero_shift() -> Self::IndexShift;
8
9    fn get_index(value: &Self::Index, utf8_index: usize) -> usize;
10    fn get_shift(value: &Self::IndexShift, utf8_shift: isize) -> isize;
11
12    /// A iterator of indices. You are given the UTF-8 indices, and need to calculate the "custom" indices.
13    /// The UTF-8 indices are guaranteed to be sorted in ascending order by the start index.
14    fn calculate_indices<'a>(
15        content: &str,
16        match_visitor: impl Iterator<Item = EncodeIndices<'a, Self>>,
17    );
18
19    /// Calculates the change of an index from replacing `before` with `after`
20    fn adjust_shift(shift: &mut Self::IndexShift, before: &str, after: &str);
21}
22
23pub struct Utf8Encoding;
24
25impl Encoding for Utf8Encoding {
26    type Index = ();
27    type IndexShift = ();
28
29    fn zero_index() -> Self::Index { /* do nothing */
30    }
31    fn zero_shift() -> Self::IndexShift { /* do nothing */
32    }
33
34    fn get_index(_value: &Self::Index, utf8_index: usize) -> usize {
35        utf8_index
36    }
37
38    fn get_shift(_value: &Self::IndexShift, utf8_shift: isize) -> isize {
39        utf8_shift
40    }
41
42    fn calculate_indices<'a>(
43        _content: &str,
44        _match_visitor: impl Iterator<Item = EncodeIndices<'a, Self>>,
45    ) {
46        // do nothing, indices are already correct
47    }
48
49    fn adjust_shift(_shift: &mut Self::IndexShift, _before: &str, _after: &str) {
50        // do nothing
51    }
52}
53
54pub struct EncodeIndices<'a, E: Encoding> {
55    // Input
56    pub utf8_start: usize,
57    pub utf8_end: usize,
58
59    // Output
60    pub custom_start: &'a mut E::Index,
61    pub custom_end: &'a mut E::Index,
62}