Coverage Report

Created: 2025-07-23 06:05

/rust/registry/src/index.crates.io-6f17d22bba15001f/regex-syntax-0.8.5/src/hir/interval.rs
Line
Count
Source (jump to first uncovered line)
1
use core::{char, cmp, fmt::Debug, slice};
2
3
use alloc::vec::Vec;
4
5
use crate::unicode;
6
7
// This module contains an *internal* implementation of interval sets.
8
//
9
// The primary invariant that interval sets guards is canonical ordering. That
10
// is, every interval set contains an ordered sequence of intervals where
11
// no two intervals are overlapping or adjacent. While this invariant is
12
// occasionally broken within the implementation, it should be impossible for
13
// callers to observe it.
14
//
15
// Since case folding (as implemented below) breaks that invariant, we roll
16
// that into this API even though it is a little out of place in an otherwise
17
// generic interval set. (Hence the reason why the `unicode` module is imported
18
// here.)
19
//
20
// Some of the implementation complexity here is a result of me wanting to
21
// preserve the sequential representation without using additional memory.
22
// In many cases, we do use linear extra memory, but it is at most 2x and it
23
// is amortized. If we relaxed the memory requirements, this implementation
24
// could become much simpler. The extra memory is honestly probably OK, but
25
// character classes (especially of the Unicode variety) can become quite
26
// large, and it would be nice to keep regex compilation snappy even in debug
27
// builds. (In the past, I have been careless with this area of code and it has
28
// caused slow regex compilations in debug mode, so this isn't entirely
29
// unwarranted.)
30
//
31
// Tests on this are relegated to the public API of HIR in src/hir.rs.
32
33
#[derive(Clone, Debug)]
34
pub struct IntervalSet<I> {
35
    /// A sorted set of non-overlapping ranges.
36
    ranges: Vec<I>,
37
    /// While not required at all for correctness, we keep track of whether an
38
    /// interval set has been case folded or not. This helps us avoid doing
39
    /// redundant work if, for example, a set has already been cased folded.
40
    /// And note that whether a set is folded or not is preserved through
41
    /// all of the pairwise set operations. That is, if both interval sets
42
    /// have been case folded, then any of difference, union, intersection or
43
    /// symmetric difference all produce a case folded set.
44
    ///
45
    /// Note that when this is true, it *must* be the case that the set is case
46
    /// folded. But when it's false, the set *may* be case folded. In other
47
    /// words, we only set this to true when we know it to be case, but we're
48
    /// okay with it being false if it would otherwise be costly to determine
49
    /// whether it should be true. This means code cannot assume that a false
50
    /// value necessarily indicates that the set is not case folded.
51
    ///
52
    /// Bottom line: this is a performance optimization.
53
    folded: bool,
54
}
55
56
impl<I: Interval> Eq for IntervalSet<I> {}
57
58
// We implement PartialEq manually so that we don't consider the set's internal
59
// 'folded' property to be part of its identity. The 'folded' property is
60
// strictly an optimization.
61
impl<I: Interval> PartialEq for IntervalSet<I> {
62
0
    fn eq(&self, other: &IntervalSet<I>) -> bool {
63
0
        self.ranges.eq(&other.ranges)
64
0
    }
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange> as core::cmp::PartialEq>::eq
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange> as core::cmp::PartialEq>::eq
65
}
66
67
impl<I: Interval> IntervalSet<I> {
68
    /// Create a new set from a sequence of intervals. Each interval is
69
    /// specified as a pair of bounds, where both bounds are inclusive.
70
    ///
71
    /// The given ranges do not need to be in any specific order, and ranges
72
    /// may overlap.
73
0
    pub fn new<T: IntoIterator<Item = I>>(intervals: T) -> IntervalSet<I> {
74
0
        let ranges: Vec<I> = intervals.into_iter().collect();
75
0
        // An empty set is case folded.
76
0
        let folded = ranges.is_empty();
77
0
        let mut set = IntervalSet { ranges, folded };
78
0
        set.canonicalize();
79
0
        set
80
0
    }
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::new::<[regex_syntax::hir::ClassBytesRange; 1]>
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::new::<[regex_syntax::hir::ClassBytesRange; 2]>
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::new::<[regex_syntax::hir::ClassBytesRange; 3]>
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::new::<alloc::vec::Vec<regex_syntax::hir::ClassBytesRange>>
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::new::<core::iter::adapters::map::Map<core::iter::adapters::copied::Copied<core::slice::iter::Iter<(u8, u8)>>, <regex_syntax::hir::translate::TranslatorI>::hir_ascii_byte_class::{closure#0}>>
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::new::<core::iter::adapters::map::Map<core::slice::iter::Iter<regex_syntax::hir::ClassUnicodeRange>, <regex_syntax::hir::ClassUnicode>::to_byte_class::{closure#0}>>
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::new::<core::iter::adapters::map::Map<alloc::vec::into_iter::IntoIter<u8>, <regex_syntax::hir::Hir>::alternation::{closure#1}>>
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::new::<[regex_syntax::hir::ClassUnicodeRange; 1]>
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::new::<[regex_syntax::hir::ClassUnicodeRange; 2]>
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::new::<[regex_syntax::hir::ClassUnicodeRange; 3]>
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::new::<alloc::vec::Vec<regex_syntax::hir::ClassUnicodeRange>>
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::new::<core::iter::adapters::map::Map<core::iter::adapters::map::Map<core::iter::adapters::copied::Copied<core::slice::iter::Iter<(u8, u8)>>, regex_syntax::hir::translate::ascii_class_as_chars::{closure#0}>, <regex_syntax::hir::translate::TranslatorI>::hir_ascii_unicode_class::{closure#0}>>
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::new::<core::iter::adapters::map::Map<core::slice::iter::Iter<regex_syntax::hir::ClassBytesRange>, <regex_syntax::hir::ClassBytes>::to_unicode_class::{closure#0}>>
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::new::<core::iter::adapters::map::Map<alloc::vec::into_iter::IntoIter<char>, <regex_syntax::hir::Hir>::alternation::{closure#0}>>
81
82
    /// Add a new interval to this set.
83
0
    pub fn push(&mut self, interval: I) {
84
0
        // TODO: This could be faster. e.g., Push the interval such that
85
0
        // it preserves canonicalization.
86
0
        self.ranges.push(interval);
87
0
        self.canonicalize();
88
0
        // We don't know whether the new interval added here is considered
89
0
        // case folded, so we conservatively assume that the entire set is
90
0
        // no longer case folded if it was previously.
91
0
        self.folded = false;
92
0
    }
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::push
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::push
93
94
    /// Return an iterator over all intervals in this set.
95
    ///
96
    /// The iterator yields intervals in ascending order.
97
0
    pub fn iter(&self) -> IntervalSetIter<'_, I> {
98
0
        IntervalSetIter(self.ranges.iter())
99
0
    }
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::iter
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::iter
100
101
    /// Return an immutable slice of intervals in this set.
102
    ///
103
    /// The sequence returned is in canonical ordering.
104
0
    pub fn intervals(&self) -> &[I] {
105
0
        &self.ranges
106
0
    }
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::intervals
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::intervals
107
108
    /// Expand this interval set such that it contains all case folded
109
    /// characters. For example, if this class consists of the range `a-z`,
110
    /// then applying case folding will result in the class containing both the
111
    /// ranges `a-z` and `A-Z`.
112
    ///
113
    /// This returns an error if the necessary case mapping data is not
114
    /// available.
115
0
    pub fn case_fold_simple(&mut self) -> Result<(), unicode::CaseFoldError> {
116
0
        if self.folded {
117
0
            return Ok(());
118
0
        }
119
0
        let len = self.ranges.len();
120
0
        for i in 0..len {
121
0
            let range = self.ranges[i];
122
0
            if let Err(err) = range.case_fold_simple(&mut self.ranges) {
123
0
                self.canonicalize();
124
0
                return Err(err);
125
0
            }
126
        }
127
0
        self.canonicalize();
128
0
        self.folded = true;
129
0
        Ok(())
130
0
    }
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::case_fold_simple
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::case_fold_simple
131
132
    /// Union this set with the given set, in place.
133
0
    pub fn union(&mut self, other: &IntervalSet<I>) {
134
0
        if other.ranges.is_empty() || self.ranges == other.ranges {
135
0
            return;
136
0
        }
137
0
        // This could almost certainly be done more efficiently.
138
0
        self.ranges.extend(&other.ranges);
139
0
        self.canonicalize();
140
0
        self.folded = self.folded && other.folded;
141
0
    }
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::union
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::union
142
143
    /// Intersect this set with the given set, in place.
144
0
    pub fn intersect(&mut self, other: &IntervalSet<I>) {
145
0
        if self.ranges.is_empty() {
146
0
            return;
147
0
        }
148
0
        if other.ranges.is_empty() {
149
0
            self.ranges.clear();
150
0
            // An empty set is case folded.
151
0
            self.folded = true;
152
0
            return;
153
0
        }
154
0
155
0
        // There should be a way to do this in-place with constant memory,
156
0
        // but I couldn't figure out a simple way to do it. So just append
157
0
        // the intersection to the end of this range, and then drain it before
158
0
        // we're done.
159
0
        let drain_end = self.ranges.len();
160
0
161
0
        let mut ita = 0..drain_end;
162
0
        let mut itb = 0..other.ranges.len();
163
0
        let mut a = ita.next().unwrap();
164
0
        let mut b = itb.next().unwrap();
165
        loop {
166
0
            if let Some(ab) = self.ranges[a].intersect(&other.ranges[b]) {
167
0
                self.ranges.push(ab);
168
0
            }
169
0
            let (it, aorb) =
170
0
                if self.ranges[a].upper() < other.ranges[b].upper() {
171
0
                    (&mut ita, &mut a)
172
                } else {
173
0
                    (&mut itb, &mut b)
174
                };
175
0
            match it.next() {
176
0
                Some(v) => *aorb = v,
177
0
                None => break,
178
0
            }
179
0
        }
180
0
        self.ranges.drain(..drain_end);
181
0
        self.folded = self.folded && other.folded;
182
0
    }
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::intersect
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::intersect
183
184
    /// Subtract the given set from this set, in place.
185
0
    pub fn difference(&mut self, other: &IntervalSet<I>) {
186
0
        if self.ranges.is_empty() || other.ranges.is_empty() {
187
0
            return;
188
0
        }
189
0
190
0
        // This algorithm is (to me) surprisingly complex. A search of the
191
0
        // interwebs indicate that this is a potentially interesting problem.
192
0
        // Folks seem to suggest interval or segment trees, but I'd like to
193
0
        // avoid the overhead (both runtime and conceptual) of that.
194
0
        //
195
0
        // The following is basically my Shitty First Draft. Therefore, in
196
0
        // order to grok it, you probably need to read each line carefully.
197
0
        // Simplifications are most welcome!
198
0
        //
199
0
        // Remember, we can assume the canonical format invariant here, which
200
0
        // says that all ranges are sorted, not overlapping and not adjacent in
201
0
        // each class.
202
0
        let drain_end = self.ranges.len();
203
0
        let (mut a, mut b) = (0, 0);
204
0
        'LOOP: while a < drain_end && b < other.ranges.len() {
205
            // Basically, the easy cases are when neither range overlaps with
206
            // each other. If the `b` range is less than our current `a`
207
            // range, then we can skip it and move on.
208
0
            if other.ranges[b].upper() < self.ranges[a].lower() {
209
0
                b += 1;
210
0
                continue;
211
0
            }
212
0
            // ... similarly for the `a` range. If it's less than the smallest
213
0
            // `b` range, then we can add it as-is.
214
0
            if self.ranges[a].upper() < other.ranges[b].lower() {
215
0
                let range = self.ranges[a];
216
0
                self.ranges.push(range);
217
0
                a += 1;
218
0
                continue;
219
0
            }
220
0
            // Otherwise, we have overlapping ranges.
221
0
            assert!(!self.ranges[a].is_intersection_empty(&other.ranges[b]));
222
223
            // This part is tricky and was non-obvious to me without looking
224
            // at explicit examples (see the tests). The trickiness stems from
225
            // two things: 1) subtracting a range from another range could
226
            // yield two ranges and 2) after subtracting a range, it's possible
227
            // that future ranges can have an impact. The loop below advances
228
            // the `b` ranges until they can't possible impact the current
229
            // range.
230
            //
231
            // For example, if our `a` range is `a-t` and our next three `b`
232
            // ranges are `a-c`, `g-i`, `r-t` and `x-z`, then we need to apply
233
            // subtraction three times before moving on to the next `a` range.
234
0
            let mut range = self.ranges[a];
235
0
            while b < other.ranges.len()
236
0
                && !range.is_intersection_empty(&other.ranges[b])
237
            {
238
0
                let old_range = range;
239
0
                range = match range.difference(&other.ranges[b]) {
240
                    (None, None) => {
241
                        // We lost the entire range, so move on to the next
242
                        // without adding this one.
243
0
                        a += 1;
244
0
                        continue 'LOOP;
245
                    }
246
0
                    (Some(range1), None) | (None, Some(range1)) => range1,
247
0
                    (Some(range1), Some(range2)) => {
248
0
                        self.ranges.push(range1);
249
0
                        range2
250
                    }
251
                };
252
                // It's possible that the `b` range has more to contribute
253
                // here. In particular, if it is greater than the original
254
                // range, then it might impact the next `a` range *and* it
255
                // has impacted the current `a` range as much as possible,
256
                // so we can quit. We don't bump `b` so that the next `a`
257
                // range can apply it.
258
0
                if other.ranges[b].upper() > old_range.upper() {
259
0
                    break;
260
0
                }
261
0
                // Otherwise, the next `b` range might apply to the current
262
0
                // `a` range.
263
0
                b += 1;
264
            }
265
0
            self.ranges.push(range);
266
0
            a += 1;
267
        }
268
0
        while a < drain_end {
269
0
            let range = self.ranges[a];
270
0
            self.ranges.push(range);
271
0
            a += 1;
272
0
        }
273
0
        self.ranges.drain(..drain_end);
274
0
        self.folded = self.folded && other.folded;
275
0
    }
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::difference
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::difference
276
277
    /// Compute the symmetric difference of the two sets, in place.
278
    ///
279
    /// This computes the symmetric difference of two interval sets. This
280
    /// removes all elements in this set that are also in the given set,
281
    /// but also adds all elements from the given set that aren't in this
282
    /// set. That is, the set will contain all elements in either set,
283
    /// but will not contain any elements that are in both sets.
284
0
    pub fn symmetric_difference(&mut self, other: &IntervalSet<I>) {
285
0
        // TODO(burntsushi): Fix this so that it amortizes allocation.
286
0
        let mut intersection = self.clone();
287
0
        intersection.intersect(other);
288
0
        self.union(other);
289
0
        self.difference(&intersection);
290
0
    }
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::symmetric_difference
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::symmetric_difference
291
292
    /// Negate this interval set.
293
    ///
294
    /// For all `x` where `x` is any element, if `x` was in this set, then it
295
    /// will not be in this set after negation.
296
0
    pub fn negate(&mut self) {
297
0
        if self.ranges.is_empty() {
298
0
            let (min, max) = (I::Bound::min_value(), I::Bound::max_value());
299
0
            self.ranges.push(I::create(min, max));
300
0
            // The set containing everything must case folded.
301
0
            self.folded = true;
302
0
            return;
303
0
        }
304
0
305
0
        // There should be a way to do this in-place with constant memory,
306
0
        // but I couldn't figure out a simple way to do it. So just append
307
0
        // the negation to the end of this range, and then drain it before
308
0
        // we're done.
309
0
        let drain_end = self.ranges.len();
310
0
311
0
        // We do checked arithmetic below because of the canonical ordering
312
0
        // invariant.
313
0
        if self.ranges[0].lower() > I::Bound::min_value() {
314
0
            let upper = self.ranges[0].lower().decrement();
315
0
            self.ranges.push(I::create(I::Bound::min_value(), upper));
316
0
        }
317
0
        for i in 1..drain_end {
318
0
            let lower = self.ranges[i - 1].upper().increment();
319
0
            let upper = self.ranges[i].lower().decrement();
320
0
            self.ranges.push(I::create(lower, upper));
321
0
        }
322
0
        if self.ranges[drain_end - 1].upper() < I::Bound::max_value() {
323
0
            let lower = self.ranges[drain_end - 1].upper().increment();
324
0
            self.ranges.push(I::create(lower, I::Bound::max_value()));
325
0
        }
326
0
        self.ranges.drain(..drain_end);
327
        // We don't need to update whether this set is folded or not, because
328
        // it is conservatively preserved through negation. Namely, if a set
329
        // is not folded, then it is possible that its negation is folded, for
330
        // example, [^☃]. But we're fine with assuming that the set is not
331
        // folded in that case. (`folded` permits false negatives but not false
332
        // positives.)
333
        //
334
        // But what about when a set is folded, is its negation also
335
        // necessarily folded? Yes. Because if a set is folded, then for every
336
        // character in the set, it necessarily included its equivalence class
337
        // of case folded characters. Negating it in turn means that all
338
        // equivalence classes in the set are negated, and any equivalence
339
        // class that was previously not in the set is now entirely in the set.
340
0
    }
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::negate
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::negate
341
342
    /// Converts this set into a canonical ordering.
343
0
    fn canonicalize(&mut self) {
344
0
        if self.is_canonical() {
345
0
            return;
346
0
        }
347
0
        self.ranges.sort();
348
0
        assert!(!self.ranges.is_empty());
349
350
        // Is there a way to do this in-place with constant memory? I couldn't
351
        // figure out a way to do it. So just append the canonicalization to
352
        // the end of this range, and then drain it before we're done.
353
0
        let drain_end = self.ranges.len();
354
0
        for oldi in 0..drain_end {
355
            // If we've added at least one new range, then check if we can
356
            // merge this range in the previously added range.
357
0
            if self.ranges.len() > drain_end {
358
0
                let (last, rest) = self.ranges.split_last_mut().unwrap();
359
0
                if let Some(union) = last.union(&rest[oldi]) {
360
0
                    *last = union;
361
0
                    continue;
362
0
                }
363
0
            }
364
0
            let range = self.ranges[oldi];
365
0
            self.ranges.push(range);
366
        }
367
0
        self.ranges.drain(..drain_end);
368
0
    }
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::canonicalize
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::canonicalize
369
370
    /// Returns true if and only if this class is in a canonical ordering.
371
0
    fn is_canonical(&self) -> bool {
372
0
        for pair in self.ranges.windows(2) {
373
0
            if pair[0] >= pair[1] {
374
0
                return false;
375
0
            }
376
0
            if pair[0].is_contiguous(&pair[1]) {
377
0
                return false;
378
0
            }
379
        }
380
0
        true
381
0
    }
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::is_canonical
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::is_canonical
382
}
383
384
/// An iterator over intervals.
385
#[derive(Debug)]
386
pub struct IntervalSetIter<'a, I>(slice::Iter<'a, I>);
387
388
impl<'a, I> Iterator for IntervalSetIter<'a, I> {
389
    type Item = &'a I;
390
391
0
    fn next(&mut self) -> Option<&'a I> {
392
0
        self.0.next()
393
0
    }
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSetIter<regex_syntax::hir::ClassBytesRange> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSetIter<regex_syntax::hir::ClassUnicodeRange> as core::iter::traits::iterator::Iterator>::next
394
}
395
396
pub trait Interval:
397
    Clone + Copy + Debug + Default + Eq + PartialEq + PartialOrd + Ord
398
{
399
    type Bound: Bound;
400
401
    fn lower(&self) -> Self::Bound;
402
    fn upper(&self) -> Self::Bound;
403
    fn set_lower(&mut self, bound: Self::Bound);
404
    fn set_upper(&mut self, bound: Self::Bound);
405
    fn case_fold_simple(
406
        &self,
407
        intervals: &mut Vec<Self>,
408
    ) -> Result<(), unicode::CaseFoldError>;
409
410
    /// Create a new interval.
411
0
    fn create(lower: Self::Bound, upper: Self::Bound) -> Self {
412
0
        let mut int = Self::default();
413
0
        if lower <= upper {
414
0
            int.set_lower(lower);
415
0
            int.set_upper(upper);
416
0
        } else {
417
0
            int.set_lower(upper);
418
0
            int.set_upper(lower);
419
0
        }
420
0
        int
421
0
    }
Unexecuted instantiation: <regex_syntax::hir::ClassBytesRange as regex_syntax::hir::interval::Interval>::create
Unexecuted instantiation: <regex_syntax::hir::ClassUnicodeRange as regex_syntax::hir::interval::Interval>::create
422
423
    /// Union the given overlapping range into this range.
424
    ///
425
    /// If the two ranges aren't contiguous, then this returns `None`.
426
0
    fn union(&self, other: &Self) -> Option<Self> {
427
0
        if !self.is_contiguous(other) {
428
0
            return None;
429
0
        }
430
0
        let lower = cmp::min(self.lower(), other.lower());
431
0
        let upper = cmp::max(self.upper(), other.upper());
432
0
        Some(Self::create(lower, upper))
433
0
    }
Unexecuted instantiation: <regex_syntax::hir::ClassBytesRange as regex_syntax::hir::interval::Interval>::union
Unexecuted instantiation: <regex_syntax::hir::ClassUnicodeRange as regex_syntax::hir::interval::Interval>::union
434
435
    /// Intersect this range with the given range and return the result.
436
    ///
437
    /// If the intersection is empty, then this returns `None`.
438
0
    fn intersect(&self, other: &Self) -> Option<Self> {
439
0
        let lower = cmp::max(self.lower(), other.lower());
440
0
        let upper = cmp::min(self.upper(), other.upper());
441
0
        if lower <= upper {
442
0
            Some(Self::create(lower, upper))
443
        } else {
444
0
            None
445
        }
446
0
    }
Unexecuted instantiation: <regex_syntax::hir::ClassBytesRange as regex_syntax::hir::interval::Interval>::intersect
Unexecuted instantiation: <regex_syntax::hir::ClassUnicodeRange as regex_syntax::hir::interval::Interval>::intersect
447
448
    /// Subtract the given range from this range and return the resulting
449
    /// ranges.
450
    ///
451
    /// If subtraction would result in an empty range, then no ranges are
452
    /// returned.
453
0
    fn difference(&self, other: &Self) -> (Option<Self>, Option<Self>) {
454
0
        if self.is_subset(other) {
455
0
            return (None, None);
456
0
        }
457
0
        if self.is_intersection_empty(other) {
458
0
            return (Some(self.clone()), None);
459
0
        }
460
0
        let add_lower = other.lower() > self.lower();
461
0
        let add_upper = other.upper() < self.upper();
462
0
        // We know this because !self.is_subset(other) and the ranges have
463
0
        // a non-empty intersection.
464
0
        assert!(add_lower || add_upper);
465
0
        let mut ret = (None, None);
466
0
        if add_lower {
467
0
            let upper = other.lower().decrement();
468
0
            ret.0 = Some(Self::create(self.lower(), upper));
469
0
        }
470
0
        if add_upper {
471
0
            let lower = other.upper().increment();
472
0
            let range = Self::create(lower, self.upper());
473
0
            if ret.0.is_none() {
474
0
                ret.0 = Some(range);
475
0
            } else {
476
0
                ret.1 = Some(range);
477
0
            }
478
0
        }
479
0
        ret
480
0
    }
Unexecuted instantiation: <regex_syntax::hir::ClassBytesRange as regex_syntax::hir::interval::Interval>::difference
Unexecuted instantiation: <regex_syntax::hir::ClassUnicodeRange as regex_syntax::hir::interval::Interval>::difference
481
482
    /// Returns true if and only if the two ranges are contiguous. Two ranges
483
    /// are contiguous if and only if the ranges are either overlapping or
484
    /// adjacent.
485
0
    fn is_contiguous(&self, other: &Self) -> bool {
486
0
        let lower1 = self.lower().as_u32();
487
0
        let upper1 = self.upper().as_u32();
488
0
        let lower2 = other.lower().as_u32();
489
0
        let upper2 = other.upper().as_u32();
490
0
        cmp::max(lower1, lower2) <= cmp::min(upper1, upper2).saturating_add(1)
491
0
    }
Unexecuted instantiation: <regex_syntax::hir::ClassBytesRange as regex_syntax::hir::interval::Interval>::is_contiguous
Unexecuted instantiation: <regex_syntax::hir::ClassUnicodeRange as regex_syntax::hir::interval::Interval>::is_contiguous
492
493
    /// Returns true if and only if the intersection of this range and the
494
    /// other range is empty.
495
0
    fn is_intersection_empty(&self, other: &Self) -> bool {
496
0
        let (lower1, upper1) = (self.lower(), self.upper());
497
0
        let (lower2, upper2) = (other.lower(), other.upper());
498
0
        cmp::max(lower1, lower2) > cmp::min(upper1, upper2)
499
0
    }
Unexecuted instantiation: <regex_syntax::hir::ClassBytesRange as regex_syntax::hir::interval::Interval>::is_intersection_empty
Unexecuted instantiation: <regex_syntax::hir::ClassUnicodeRange as regex_syntax::hir::interval::Interval>::is_intersection_empty
500
501
    /// Returns true if and only if this range is a subset of the other range.
502
0
    fn is_subset(&self, other: &Self) -> bool {
503
0
        let (lower1, upper1) = (self.lower(), self.upper());
504
0
        let (lower2, upper2) = (other.lower(), other.upper());
505
0
        (lower2 <= lower1 && lower1 <= upper2)
506
0
            && (lower2 <= upper1 && upper1 <= upper2)
507
0
    }
Unexecuted instantiation: <regex_syntax::hir::ClassBytesRange as regex_syntax::hir::interval::Interval>::is_subset
Unexecuted instantiation: <regex_syntax::hir::ClassUnicodeRange as regex_syntax::hir::interval::Interval>::is_subset
508
}
509
510
pub trait Bound:
511
    Copy + Clone + Debug + Eq + PartialEq + PartialOrd + Ord
512
{
513
    fn min_value() -> Self;
514
    fn max_value() -> Self;
515
    fn as_u32(self) -> u32;
516
    fn increment(self) -> Self;
517
    fn decrement(self) -> Self;
518
}
519
520
impl Bound for u8 {
521
0
    fn min_value() -> Self {
522
0
        u8::MIN
523
0
    }
524
0
    fn max_value() -> Self {
525
0
        u8::MAX
526
0
    }
527
0
    fn as_u32(self) -> u32 {
528
0
        u32::from(self)
529
0
    }
530
0
    fn increment(self) -> Self {
531
0
        self.checked_add(1).unwrap()
532
0
    }
533
0
    fn decrement(self) -> Self {
534
0
        self.checked_sub(1).unwrap()
535
0
    }
536
}
537
538
impl Bound for char {
539
0
    fn min_value() -> Self {
540
0
        '\x00'
541
0
    }
542
0
    fn max_value() -> Self {
543
0
        '\u{10FFFF}'
544
0
    }
545
0
    fn as_u32(self) -> u32 {
546
0
        u32::from(self)
547
0
    }
548
549
0
    fn increment(self) -> Self {
550
0
        match self {
551
0
            '\u{D7FF}' => '\u{E000}',
552
0
            c => char::from_u32(u32::from(c).checked_add(1).unwrap()).unwrap(),
553
        }
554
0
    }
555
556
0
    fn decrement(self) -> Self {
557
0
        match self {
558
0
            '\u{E000}' => '\u{D7FF}',
559
0
            c => char::from_u32(u32::from(c).checked_sub(1).unwrap()).unwrap(),
560
        }
561
0
    }
562
}
563
564
// Tests for interval sets are written in src/hir.rs against the public API.