aboutsummaryrefslogtreecommitdiffstats
path: root/src/regex/byte_range.rs
blob: d549a55b2bdb1996b5a619b90b3f3d4c4e2ac414 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
use std::ops::RangeInclusive;

#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct ByteRange {
    /// inclusive
    from: u8,
    /// inclusive
    to: u8,
}

impl From<RangeInclusive<u8>> for ByteRange {
    fn from(value: RangeInclusive<u8>) -> Self {
        Self::new_range(*value.start(), *value.end())
    }
}

impl ByteRange {
    pub fn new_range(from: u8, to: u8) -> Self {
        assert!(from <= to, "{from} <= {to}");
        Self { from, to }
    }

    pub fn new_single(c: u8) -> Self {
        Self::new_range(c, c)
    }

    pub fn all() -> Self {
        Self::new_range(0, 255)
    }

    pub fn contains(&self, c: u8) -> bool {
        self.from <= c && c <= self.to
    }

    pub fn overlaps(&self, other: Self) -> bool {
        self.from.max(other.from) <= self.to.min(other.to)
    }

    pub fn split_to_disjoint(ranges: Vec<ByteRange>) -> Vec<ByteRange> {
        if ranges.is_empty() {
            return vec![];
        }

        let mut points: Vec<u16> = Vec::new();
        for r in &ranges {
            points.push(r.from as u16);
            points.push((r.to as u16) + 1);
        }

        points.sort_unstable();
        points.dedup();

        let mut out = Vec::new();

        for window in points.windows(2) {
            let start = window[0];
            let end_exclusive = window[1];

            if start >= end_exclusive {
                continue;
            }

            let mut active = false;

            for r in &ranges {
                if r.from as u16 <= start && start <= r.to as u16 {
                    active = true;
                    break;
                }
            }

            if active {
                out.push(ByteRange {
                    from: start as u8,
                    to: (end_exclusive - 1) as u8,
                });
            }
        }

        out
    }
}

#[test]
fn byterange_test() {
    assert_eq!(
        ByteRange::split_to_disjoint(vec![
            ByteRange::new_range(b'a', b'z'),
            ByteRange::new_single(b'm')
        ]),
        vec![
            ByteRange::new_range(b'a', b'l'),
            ByteRange::new_single(b'm'),
            ByteRange::new_range(b'n', b'z'),
        ]
    );
}

#[test]
fn byterange_test_0_128() {
    assert_eq!(
        ByteRange::split_to_disjoint(vec![ByteRange::new_range(0, 128)]),
        vec![ByteRange::new_range(0, 128)]
    );
}

#[test]
fn byterange_test_0_255() {
    assert_eq!(
        ByteRange::split_to_disjoint(vec![ByteRange::new_range(0, 255)]),
        vec![ByteRange::new_range(0, 255)]
    );
}

impl std::fmt::Debug for ByteRange {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.from == self.to {
            write!(f, "{}", [self.from].escape_ascii())
        } else {
            write!(
                f,
                "{}-{}",
                [self.from].escape_ascii(),
                [self.to].escape_ascii()
            )
        }
    }
}

#[cfg(test)]
mod non_overlapping_tests {
    use std::ops::RangeInclusive;

    use super::ByteRange;

    fn middle(r: ByteRange) -> u8 {
        let a = r.from as u8;
        let b = r.to as u8;
        (a + (b - a) / 2) as u8
    }

    fn prev(c: u8) -> u8 {
        c - 1
    }

    fn next(c: u8) -> u8 {
        c + 1
    }

    fn run(ranges: Vec<RangeInclusive<u8>>) {
        let ranges1: Vec<ByteRange> = ranges.into_iter().map(Into::into).collect();
        let ranges2 = ByteRange::split_to_disjoint(ranges1.clone());

        let r1 = |c| ranges1.iter().any(|cr| cr.contains(c));
        let r2 = |c| ranges2.iter().any(|cr| cr.contains(c));

        for &range in ranges1.iter() {
            assert!(r1(range.from));
            assert!(r1(range.to));
            assert!(r1(middle(range)));

            assert!(r2(range.from));
            assert!(r2(range.to));
            assert!(r2(middle(range)));

            assert_eq!(r1(prev(range.from)), r2(prev(range.from)));
            assert_eq!(r1(next(range.from)), r2(next(range.from)));
        }

        for i in 0..ranges2.len() {
            for j in 0..i {
                assert!(
                    !ranges2[i].overlaps(ranges2[j]),
                    "{i} and {j} overlap: {:?}, {:?}",
                    ranges2[i],
                    ranges2[j]
                );
            }
        }
    }

    #[test]
    fn overlap_correct() {
        assert!(ByteRange::new_range(b'a', b'g').overlaps(ByteRange::new_single(b'f')));
        assert!(!ByteRange::new_range(b'a', b'g').overlaps(ByteRange::new_single(b'h')));
    }

    #[test]
    fn empty() {
        run(vec![]);
    }

    #[test]
    fn singleton() {
        run(vec![b'0'..=b'9']);
    }

    #[test]
    fn contained1() {
        run(vec![b'0'..=b'9', b'5'..=b'6']);
    }

    #[test]
    fn contained2() {
        run(vec![b'5'..=b'6', b'0'..=b'9']);
    }

    #[test]
    fn overlap2() {
        run(vec![b'1'..=b'6', b'4'..=b'9'])
    }

    #[test]
    fn overlap3() {
        run(vec![b'a'..=b'f', b'd'..=b'j', b'g'..=b'm'])
    }

    #[test]
    fn overlap4() {
        run(vec![b'a'..=b'f', b'd'..=b'j', b'g'..=b'm', b'k'..=b'q'])
    }
}