Coverage Report

Created: 2025-02-21 07:11

/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
8.12k
    fn eq(&self, other: &IntervalSet<I>) -> bool {
63
8.12k
        self.ranges.eq(&other.ranges)
64
8.12k
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange> as core::cmp::PartialEq>::eq
Line
Count
Source
62
1.46k
    fn eq(&self, other: &IntervalSet<I>) -> bool {
63
1.46k
        self.ranges.eq(&other.ranges)
64
1.46k
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange> as core::cmp::PartialEq>::eq
Line
Count
Source
62
6.65k
    fn eq(&self, other: &IntervalSet<I>) -> bool {
63
6.65k
        self.ranges.eq(&other.ranges)
64
6.65k
    }
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
4.40M
    pub fn new<T: IntoIterator<Item = I>>(intervals: T) -> IntervalSet<I> {
74
4.40M
        let ranges: Vec<I> = intervals.into_iter().collect();
75
4.40M
        // An empty set is case folded.
76
4.40M
        let folded = ranges.is_empty();
77
4.40M
        let mut set = IntervalSet { ranges, folded };
78
4.40M
        set.canonicalize();
79
4.40M
        set
80
4.40M
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::new::<[regex_syntax::hir::ClassBytesRange; 1]>
Line
Count
Source
73
221k
    pub fn new<T: IntoIterator<Item = I>>(intervals: T) -> IntervalSet<I> {
74
221k
        let ranges: Vec<I> = intervals.into_iter().collect();
75
221k
        // An empty set is case folded.
76
221k
        let folded = ranges.is_empty();
77
221k
        let mut set = IntervalSet { ranges, folded };
78
221k
        set.canonicalize();
79
221k
        set
80
221k
    }
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]>
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::new::<alloc::vec::Vec<regex_syntax::hir::ClassBytesRange>>
Line
Count
Source
73
1.00M
    pub fn new<T: IntoIterator<Item = I>>(intervals: T) -> IntervalSet<I> {
74
1.00M
        let ranges: Vec<I> = intervals.into_iter().collect();
75
1.00M
        // An empty set is case folded.
76
1.00M
        let folded = ranges.is_empty();
77
1.00M
        let mut set = IntervalSet { ranges, folded };
78
1.00M
        set.canonicalize();
79
1.00M
        set
80
1.00M
    }
<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}>>
Line
Count
Source
73
238
    pub fn new<T: IntoIterator<Item = I>>(intervals: T) -> IntervalSet<I> {
74
238
        let ranges: Vec<I> = intervals.into_iter().collect();
75
238
        // An empty set is case folded.
76
238
        let folded = ranges.is_empty();
77
238
        let mut set = IntervalSet { ranges, folded };
78
238
        set.canonicalize();
79
238
        set
80
238
    }
<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}>>
Line
Count
Source
73
5.26k
    pub fn new<T: IntoIterator<Item = I>>(intervals: T) -> IntervalSet<I> {
74
5.26k
        let ranges: Vec<I> = intervals.into_iter().collect();
75
5.26k
        // An empty set is case folded.
76
5.26k
        let folded = ranges.is_empty();
77
5.26k
        let mut set = IntervalSet { ranges, folded };
78
5.26k
        set.canonicalize();
79
5.26k
        set
80
5.26k
    }
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}>>
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::new::<[regex_syntax::hir::ClassUnicodeRange; 1]>
Line
Count
Source
73
1.20M
    pub fn new<T: IntoIterator<Item = I>>(intervals: T) -> IntervalSet<I> {
74
1.20M
        let ranges: Vec<I> = intervals.into_iter().collect();
75
1.20M
        // An empty set is case folded.
76
1.20M
        let folded = ranges.is_empty();
77
1.20M
        let mut set = IntervalSet { ranges, folded };
78
1.20M
        set.canonicalize();
79
1.20M
        set
80
1.20M
    }
Unexecuted instantiation: <regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::new::<[regex_syntax::hir::ClassUnicodeRange; 2]>
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::new::<[regex_syntax::hir::ClassUnicodeRange; 3]>
Line
Count
Source
73
319
    pub fn new<T: IntoIterator<Item = I>>(intervals: T) -> IntervalSet<I> {
74
319
        let ranges: Vec<I> = intervals.into_iter().collect();
75
319
        // An empty set is case folded.
76
319
        let folded = ranges.is_empty();
77
319
        let mut set = IntervalSet { ranges, folded };
78
319
        set.canonicalize();
79
319
        set
80
319
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::new::<alloc::vec::Vec<regex_syntax::hir::ClassUnicodeRange>>
Line
Count
Source
73
1.95M
    pub fn new<T: IntoIterator<Item = I>>(intervals: T) -> IntervalSet<I> {
74
1.95M
        let ranges: Vec<I> = intervals.into_iter().collect();
75
1.95M
        // An empty set is case folded.
76
1.95M
        let folded = ranges.is_empty();
77
1.95M
        let mut set = IntervalSet { ranges, folded };
78
1.95M
        set.canonicalize();
79
1.95M
        set
80
1.95M
    }
<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}>>
Line
Count
Source
73
615
    pub fn new<T: IntoIterator<Item = I>>(intervals: T) -> IntervalSet<I> {
74
615
        let ranges: Vec<I> = intervals.into_iter().collect();
75
615
        // An empty set is case folded.
76
615
        let folded = ranges.is_empty();
77
615
        let mut set = IntervalSet { ranges, folded };
78
615
        set.canonicalize();
79
615
        set
80
615
    }
<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}>>
Line
Count
Source
73
2.11k
    pub fn new<T: IntoIterator<Item = I>>(intervals: T) -> IntervalSet<I> {
74
2.11k
        let ranges: Vec<I> = intervals.into_iter().collect();
75
2.11k
        // An empty set is case folded.
76
2.11k
        let folded = ranges.is_empty();
77
2.11k
        let mut set = IntervalSet { ranges, folded };
78
2.11k
        set.canonicalize();
79
2.11k
        set
80
2.11k
    }
<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}>>
Line
Count
Source
73
3.65k
    pub fn new<T: IntoIterator<Item = I>>(intervals: T) -> IntervalSet<I> {
74
3.65k
        let ranges: Vec<I> = intervals.into_iter().collect();
75
3.65k
        // An empty set is case folded.
76
3.65k
        let folded = ranges.is_empty();
77
3.65k
        let mut set = IntervalSet { ranges, folded };
78
3.65k
        set.canonicalize();
79
3.65k
        set
80
3.65k
    }
81
82
    /// Add a new interval to this set.
83
7.67M
    pub fn push(&mut self, interval: I) {
84
7.67M
        // TODO: This could be faster. e.g., Push the interval such that
85
7.67M
        // it preserves canonicalization.
86
7.67M
        self.ranges.push(interval);
87
7.67M
        self.canonicalize();
88
7.67M
        // We don't know whether the new interval added here is considered
89
7.67M
        // case folded, so we conservatively assume that the entire set is
90
7.67M
        // no longer case folded if it was previously.
91
7.67M
        self.folded = false;
92
7.67M
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::push
Line
Count
Source
83
6.07M
    pub fn push(&mut self, interval: I) {
84
6.07M
        // TODO: This could be faster. e.g., Push the interval such that
85
6.07M
        // it preserves canonicalization.
86
6.07M
        self.ranges.push(interval);
87
6.07M
        self.canonicalize();
88
6.07M
        // We don't know whether the new interval added here is considered
89
6.07M
        // case folded, so we conservatively assume that the entire set is
90
6.07M
        // no longer case folded if it was previously.
91
6.07M
        self.folded = false;
92
6.07M
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::push
Line
Count
Source
83
1.60M
    pub fn push(&mut self, interval: I) {
84
1.60M
        // TODO: This could be faster. e.g., Push the interval such that
85
1.60M
        // it preserves canonicalization.
86
1.60M
        self.ranges.push(interval);
87
1.60M
        self.canonicalize();
88
1.60M
        // We don't know whether the new interval added here is considered
89
1.60M
        // case folded, so we conservatively assume that the entire set is
90
1.60M
        // no longer case folded if it was previously.
91
1.60M
        self.folded = false;
92
1.60M
    }
93
94
    /// Return an iterator over all intervals in this set.
95
    ///
96
    /// The iterator yields intervals in ascending order.
97
11.5M
    pub fn iter(&self) -> IntervalSetIter<'_, I> {
98
11.5M
        IntervalSetIter(self.ranges.iter())
99
11.5M
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::iter
Line
Count
Source
97
2.64M
    pub fn iter(&self) -> IntervalSetIter<'_, I> {
98
2.64M
        IntervalSetIter(self.ranges.iter())
99
2.64M
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::iter
Line
Count
Source
97
8.92M
    pub fn iter(&self) -> IntervalSetIter<'_, I> {
98
8.92M
        IntervalSetIter(self.ranges.iter())
99
8.92M
    }
100
101
    /// Return an immutable slice of intervals in this set.
102
    ///
103
    /// The sequence returned is in canonical ordering.
104
30.2M
    pub fn intervals(&self) -> &[I] {
105
30.2M
        &self.ranges
106
30.2M
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::intervals
Line
Count
Source
104
5.23M
    pub fn intervals(&self) -> &[I] {
105
5.23M
        &self.ranges
106
5.23M
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::intervals
Line
Count
Source
104
25.0M
    pub fn intervals(&self) -> &[I] {
105
25.0M
        &self.ranges
106
25.0M
    }
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
2.53M
    pub fn case_fold_simple(&mut self) -> Result<(), unicode::CaseFoldError> {
116
2.53M
        if self.folded {
117
93.8k
            return Ok(());
118
2.44M
        }
119
2.44M
        let len = self.ranges.len();
120
20.8M
        for i in 0..len {
121
20.8M
            let range = self.ranges[i];
122
20.8M
            if let Err(err) = range.case_fold_simple(&mut self.ranges) {
123
0
                self.canonicalize();
124
0
                return Err(err);
125
20.8M
            }
126
        }
127
2.44M
        self.canonicalize();
128
2.44M
        self.folded = true;
129
2.44M
        Ok(())
130
2.53M
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::case_fold_simple
Line
Count
Source
115
898k
    pub fn case_fold_simple(&mut self) -> Result<(), unicode::CaseFoldError> {
116
898k
        if self.folded {
117
64.5k
            return Ok(());
118
833k
        }
119
833k
        let len = self.ranges.len();
120
17.0M
        for i in 0..len {
121
17.0M
            let range = self.ranges[i];
122
17.0M
            if let Err(err) = range.case_fold_simple(&mut self.ranges) {
123
0
                self.canonicalize();
124
0
                return Err(err);
125
17.0M
            }
126
        }
127
833k
        self.canonicalize();
128
833k
        self.folded = true;
129
833k
        Ok(())
130
898k
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::case_fold_simple
Line
Count
Source
115
1.63M
    pub fn case_fold_simple(&mut self) -> Result<(), unicode::CaseFoldError> {
116
1.63M
        if self.folded {
117
29.3k
            return Ok(());
118
1.60M
        }
119
1.60M
        let len = self.ranges.len();
120
3.72M
        for i in 0..len {
121
3.72M
            let range = self.ranges[i];
122
3.72M
            if let Err(err) = range.case_fold_simple(&mut self.ranges) {
123
0
                self.canonicalize();
124
0
                return Err(err);
125
3.72M
            }
126
        }
127
1.60M
        self.canonicalize();
128
1.60M
        self.folded = true;
129
1.60M
        Ok(())
130
1.63M
    }
131
132
    /// Union this set with the given set, in place.
133
1.01M
    pub fn union(&mut self, other: &IntervalSet<I>) {
134
1.01M
        if other.ranges.is_empty() || self.ranges == other.ranges {
135
62.5k
            return;
136
949k
        }
137
949k
        // This could almost certainly be done more efficiently.
138
949k
        self.ranges.extend(&other.ranges);
139
949k
        self.canonicalize();
140
949k
        self.folded = self.folded && other.folded;
141
1.01M
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::union
Line
Count
Source
133
776k
    pub fn union(&mut self, other: &IntervalSet<I>) {
134
776k
        if other.ranges.is_empty() || self.ranges == other.ranges {
135
17.2k
            return;
136
758k
        }
137
758k
        // This could almost certainly be done more efficiently.
138
758k
        self.ranges.extend(&other.ranges);
139
758k
        self.canonicalize();
140
758k
        self.folded = self.folded && other.folded;
141
776k
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::union
Line
Count
Source
133
236k
    pub fn union(&mut self, other: &IntervalSet<I>) {
134
236k
        if other.ranges.is_empty() || self.ranges == other.ranges {
135
45.2k
            return;
136
191k
        }
137
191k
        // This could almost certainly be done more efficiently.
138
191k
        self.ranges.extend(&other.ranges);
139
191k
        self.canonicalize();
140
191k
        self.folded = self.folded && other.folded;
141
236k
    }
142
143
    /// Intersect this set with the given set, in place.
144
79.2k
    pub fn intersect(&mut self, other: &IntervalSet<I>) {
145
79.2k
        if self.ranges.is_empty() {
146
16.9k
            return;
147
62.2k
        }
148
62.2k
        if other.ranges.is_empty() {
149
21.7k
            self.ranges.clear();
150
21.7k
            // An empty set is case folded.
151
21.7k
            self.folded = true;
152
21.7k
            return;
153
40.5k
        }
154
40.5k
155
40.5k
        // There should be a way to do this in-place with constant memory,
156
40.5k
        // but I couldn't figure out a simple way to do it. So just append
157
40.5k
        // the intersection to the end of this range, and then drain it before
158
40.5k
        // we're done.
159
40.5k
        let drain_end = self.ranges.len();
160
40.5k
161
40.5k
        let mut ita = 0..drain_end;
162
40.5k
        let mut itb = 0..other.ranges.len();
163
40.5k
        let mut a = ita.next().unwrap();
164
40.5k
        let mut b = itb.next().unwrap();
165
        loop {
166
2.38M
            if let Some(ab) = self.ranges[a].intersect(&other.ranges[b]) {
167
840k
                self.ranges.push(ab);
168
1.54M
            }
169
2.38M
            let (it, aorb) =
170
2.38M
                if self.ranges[a].upper() < other.ranges[b].upper() {
171
1.08M
                    (&mut ita, &mut a)
172
                } else {
173
1.30M
                    (&mut itb, &mut b)
174
                };
175
2.38M
            match it.next() {
176
2.34M
                Some(v) => *aorb = v,
177
40.5k
                None => break,
178
40.5k
            }
179
40.5k
        }
180
40.5k
        self.ranges.drain(..drain_end);
181
40.5k
        self.folded = self.folded && other.folded;
182
79.2k
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::intersect
Line
Count
Source
144
34.2k
    pub fn intersect(&mut self, other: &IntervalSet<I>) {
145
34.2k
        if self.ranges.is_empty() {
146
2.24k
            return;
147
32.0k
        }
148
32.0k
        if other.ranges.is_empty() {
149
9.30k
            self.ranges.clear();
150
9.30k
            // An empty set is case folded.
151
9.30k
            self.folded = true;
152
9.30k
            return;
153
22.7k
        }
154
22.7k
155
22.7k
        // There should be a way to do this in-place with constant memory,
156
22.7k
        // but I couldn't figure out a simple way to do it. So just append
157
22.7k
        // the intersection to the end of this range, and then drain it before
158
22.7k
        // we're done.
159
22.7k
        let drain_end = self.ranges.len();
160
22.7k
161
22.7k
        let mut ita = 0..drain_end;
162
22.7k
        let mut itb = 0..other.ranges.len();
163
22.7k
        let mut a = ita.next().unwrap();
164
22.7k
        let mut b = itb.next().unwrap();
165
        loop {
166
419k
            if let Some(ab) = self.ranges[a].intersect(&other.ranges[b]) {
167
107k
                self.ranges.push(ab);
168
312k
            }
169
419k
            let (it, aorb) =
170
419k
                if self.ranges[a].upper() < other.ranges[b].upper() {
171
234k
                    (&mut ita, &mut a)
172
                } else {
173
185k
                    (&mut itb, &mut b)
174
                };
175
419k
            match it.next() {
176
396k
                Some(v) => *aorb = v,
177
22.7k
                None => break,
178
22.7k
            }
179
22.7k
        }
180
22.7k
        self.ranges.drain(..drain_end);
181
22.7k
        self.folded = self.folded && other.folded;
182
34.2k
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::intersect
Line
Count
Source
144
44.9k
    pub fn intersect(&mut self, other: &IntervalSet<I>) {
145
44.9k
        if self.ranges.is_empty() {
146
14.7k
            return;
147
30.2k
        }
148
30.2k
        if other.ranges.is_empty() {
149
12.3k
            self.ranges.clear();
150
12.3k
            // An empty set is case folded.
151
12.3k
            self.folded = true;
152
12.3k
            return;
153
17.8k
        }
154
17.8k
155
17.8k
        // There should be a way to do this in-place with constant memory,
156
17.8k
        // but I couldn't figure out a simple way to do it. So just append
157
17.8k
        // the intersection to the end of this range, and then drain it before
158
17.8k
        // we're done.
159
17.8k
        let drain_end = self.ranges.len();
160
17.8k
161
17.8k
        let mut ita = 0..drain_end;
162
17.8k
        let mut itb = 0..other.ranges.len();
163
17.8k
        let mut a = ita.next().unwrap();
164
17.8k
        let mut b = itb.next().unwrap();
165
        loop {
166
1.96M
            if let Some(ab) = self.ranges[a].intersect(&other.ranges[b]) {
167
733k
                self.ranges.push(ab);
168
1.23M
            }
169
1.96M
            let (it, aorb) =
170
1.96M
                if self.ranges[a].upper() < other.ranges[b].upper() {
171
846k
                    (&mut ita, &mut a)
172
                } else {
173
1.12M
                    (&mut itb, &mut b)
174
                };
175
1.96M
            match it.next() {
176
1.95M
                Some(v) => *aorb = v,
177
17.8k
                None => break,
178
17.8k
            }
179
17.8k
        }
180
17.8k
        self.ranges.drain(..drain_end);
181
17.8k
        self.folded = self.folded && other.folded;
182
44.9k
    }
183
184
    /// Subtract the given set from this set, in place.
185
123k
    pub fn difference(&mut self, other: &IntervalSet<I>) {
186
123k
        if self.ranges.is_empty() || other.ranges.is_empty() {
187
56.3k
            return;
188
66.6k
        }
189
66.6k
190
66.6k
        // This algorithm is (to me) surprisingly complex. A search of the
191
66.6k
        // interwebs indicate that this is a potentially interesting problem.
192
66.6k
        // Folks seem to suggest interval or segment trees, but I'd like to
193
66.6k
        // avoid the overhead (both runtime and conceptual) of that.
194
66.6k
        //
195
66.6k
        // The following is basically my Shitty First Draft. Therefore, in
196
66.6k
        // order to grok it, you probably need to read each line carefully.
197
66.6k
        // Simplifications are most welcome!
198
66.6k
        //
199
66.6k
        // Remember, we can assume the canonical format invariant here, which
200
66.6k
        // says that all ranges are sorted, not overlapping and not adjacent in
201
66.6k
        // each class.
202
66.6k
        let drain_end = self.ranges.len();
203
66.6k
        let (mut a, mut b) = (0, 0);
204
2.05M
        '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
1.99M
            if other.ranges[b].upper() < self.ranges[a].lower() {
209
627k
                b += 1;
210
627k
                continue;
211
1.36M
            }
212
1.36M
            // ... similarly for the `a` range. If it's less than the smallest
213
1.36M
            // `b` range, then we can add it as-is.
214
1.36M
            if self.ranges[a].upper() < other.ranges[b].lower() {
215
586k
                let range = self.ranges[a];
216
586k
                self.ranges.push(range);
217
586k
                a += 1;
218
586k
                continue;
219
778k
            }
220
778k
            // Otherwise, we have overlapping ranges.
221
778k
            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
778k
            let mut range = self.ranges[a];
235
1.21M
            while b < other.ranges.len()
236
1.18M
                && !range.is_intersection_empty(&other.ranges[b])
237
            {
238
1.04M
                let old_range = range;
239
1.04M
                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
607k
                        a += 1;
244
607k
                        continue 'LOOP;
245
                    }
246
159k
                    (Some(range1), None) | (None, Some(range1)) => range1,
247
276k
                    (Some(range1), Some(range2)) => {
248
276k
                        self.ranges.push(range1);
249
276k
                        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
436k
                if other.ranges[b].upper() > old_range.upper() {
259
1.35k
                    break;
260
434k
                }
261
434k
                // Otherwise, the next `b` range might apply to the current
262
434k
                // `a` range.
263
434k
                b += 1;
264
            }
265
170k
            self.ranges.push(range);
266
170k
            a += 1;
267
        }
268
926k
        while a < drain_end {
269
860k
            let range = self.ranges[a];
270
860k
            self.ranges.push(range);
271
860k
            a += 1;
272
860k
        }
273
66.6k
        self.ranges.drain(..drain_end);
274
66.6k
        self.folded = self.folded && other.folded;
275
123k
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::difference
Line
Count
Source
185
52.9k
    pub fn difference(&mut self, other: &IntervalSet<I>) {
186
52.9k
        if self.ranges.is_empty() || other.ranges.is_empty() {
187
17.7k
            return;
188
35.2k
        }
189
35.2k
190
35.2k
        // This algorithm is (to me) surprisingly complex. A search of the
191
35.2k
        // interwebs indicate that this is a potentially interesting problem.
192
35.2k
        // Folks seem to suggest interval or segment trees, but I'd like to
193
35.2k
        // avoid the overhead (both runtime and conceptual) of that.
194
35.2k
        //
195
35.2k
        // The following is basically my Shitty First Draft. Therefore, in
196
35.2k
        // order to grok it, you probably need to read each line carefully.
197
35.2k
        // Simplifications are most welcome!
198
35.2k
        //
199
35.2k
        // Remember, we can assume the canonical format invariant here, which
200
35.2k
        // says that all ranges are sorted, not overlapping and not adjacent in
201
35.2k
        // each class.
202
35.2k
        let drain_end = self.ranges.len();
203
35.2k
        let (mut a, mut b) = (0, 0);
204
398k
        '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
363k
            if other.ranges[b].upper() < self.ranges[a].lower() {
209
78.0k
                b += 1;
210
78.0k
                continue;
211
284k
            }
212
284k
            // ... similarly for the `a` range. If it's less than the smallest
213
284k
            // `b` range, then we can add it as-is.
214
284k
            if self.ranges[a].upper() < other.ranges[b].lower() {
215
158k
                let range = self.ranges[a];
216
158k
                self.ranges.push(range);
217
158k
                a += 1;
218
158k
                continue;
219
126k
            }
220
126k
            // Otherwise, we have overlapping ranges.
221
126k
            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
126k
            let mut range = self.ranges[a];
235
278k
            while b < other.ranges.len()
236
256k
                && !range.is_intersection_empty(&other.ranges[b])
237
            {
238
224k
                let old_range = range;
239
224k
                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
70.9k
                        a += 1;
244
70.9k
                        continue 'LOOP;
245
                    }
246
51.1k
                    (Some(range1), None) | (None, Some(range1)) => range1,
247
102k
                    (Some(range1), Some(range2)) => {
248
102k
                        self.ranges.push(range1);
249
102k
                        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
153k
                if other.ranges[b].upper() > old_range.upper() {
259
576
                    break;
260
152k
                }
261
152k
                // Otherwise, the next `b` range might apply to the current
262
152k
                // `a` range.
263
152k
                b += 1;
264
            }
265
55.0k
            self.ranges.push(range);
266
55.0k
            a += 1;
267
        }
268
77.0k
        while a < drain_end {
269
41.8k
            let range = self.ranges[a];
270
41.8k
            self.ranges.push(range);
271
41.8k
            a += 1;
272
41.8k
        }
273
35.2k
        self.ranges.drain(..drain_end);
274
35.2k
        self.folded = self.folded && other.folded;
275
52.9k
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::difference
Line
Count
Source
185
70.0k
    pub fn difference(&mut self, other: &IntervalSet<I>) {
186
70.0k
        if self.ranges.is_empty() || other.ranges.is_empty() {
187
38.6k
            return;
188
31.4k
        }
189
31.4k
190
31.4k
        // This algorithm is (to me) surprisingly complex. A search of the
191
31.4k
        // interwebs indicate that this is a potentially interesting problem.
192
31.4k
        // Folks seem to suggest interval or segment trees, but I'd like to
193
31.4k
        // avoid the overhead (both runtime and conceptual) of that.
194
31.4k
        //
195
31.4k
        // The following is basically my Shitty First Draft. Therefore, in
196
31.4k
        // order to grok it, you probably need to read each line carefully.
197
31.4k
        // Simplifications are most welcome!
198
31.4k
        //
199
31.4k
        // Remember, we can assume the canonical format invariant here, which
200
31.4k
        // says that all ranges are sorted, not overlapping and not adjacent in
201
31.4k
        // each class.
202
31.4k
        let drain_end = self.ranges.len();
203
31.4k
        let (mut a, mut b) = (0, 0);
204
1.65M
        '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
1.62M
            if other.ranges[b].upper() < self.ranges[a].lower() {
209
548k
                b += 1;
210
548k
                continue;
211
1.07M
            }
212
1.07M
            // ... similarly for the `a` range. If it's less than the smallest
213
1.07M
            // `b` range, then we can add it as-is.
214
1.07M
            if self.ranges[a].upper() < other.ranges[b].lower() {
215
427k
                let range = self.ranges[a];
216
427k
                self.ranges.push(range);
217
427k
                a += 1;
218
427k
                continue;
219
652k
            }
220
652k
            // Otherwise, we have overlapping ranges.
221
652k
            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
652k
            let mut range = self.ranges[a];
235
934k
            while b < other.ranges.len()
236
925k
                && !range.is_intersection_empty(&other.ranges[b])
237
            {
238
820k
                let old_range = range;
239
820k
                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
536k
                        a += 1;
244
536k
                        continue 'LOOP;
245
                    }
246
108k
                    (Some(range1), None) | (None, Some(range1)) => range1,
247
174k
                    (Some(range1), Some(range2)) => {
248
174k
                        self.ranges.push(range1);
249
174k
                        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
283k
                if other.ranges[b].upper() > old_range.upper() {
259
781
                    break;
260
282k
                }
261
282k
                // Otherwise, the next `b` range might apply to the current
262
282k
                // `a` range.
263
282k
                b += 1;
264
            }
265
115k
            self.ranges.push(range);
266
115k
            a += 1;
267
        }
268
849k
        while a < drain_end {
269
818k
            let range = self.ranges[a];
270
818k
            self.ranges.push(range);
271
818k
            a += 1;
272
818k
        }
273
31.4k
        self.ranges.drain(..drain_end);
274
31.4k
        self.folded = self.folded && other.folded;
275
70.0k
    }
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
74.8k
    pub fn symmetric_difference(&mut self, other: &IntervalSet<I>) {
285
74.8k
        // TODO(burntsushi): Fix this so that it amortizes allocation.
286
74.8k
        let mut intersection = self.clone();
287
74.8k
        intersection.intersect(other);
288
74.8k
        self.union(other);
289
74.8k
        self.difference(&intersection);
290
74.8k
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::symmetric_difference
Line
Count
Source
284
32.7k
    pub fn symmetric_difference(&mut self, other: &IntervalSet<I>) {
285
32.7k
        // TODO(burntsushi): Fix this so that it amortizes allocation.
286
32.7k
        let mut intersection = self.clone();
287
32.7k
        intersection.intersect(other);
288
32.7k
        self.union(other);
289
32.7k
        self.difference(&intersection);
290
32.7k
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::symmetric_difference
Line
Count
Source
284
42.1k
    pub fn symmetric_difference(&mut self, other: &IntervalSet<I>) {
285
42.1k
        // TODO(burntsushi): Fix this so that it amortizes allocation.
286
42.1k
        let mut intersection = self.clone();
287
42.1k
        intersection.intersect(other);
288
42.1k
        self.union(other);
289
42.1k
        self.difference(&intersection);
290
42.1k
    }
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
1.21M
    pub fn negate(&mut self) {
297
1.21M
        if self.ranges.is_empty() {
298
3.45k
            let (min, max) = (I::Bound::min_value(), I::Bound::max_value());
299
3.45k
            self.ranges.push(I::create(min, max));
300
3.45k
            // The set containing everything must case folded.
301
3.45k
            self.folded = true;
302
3.45k
            return;
303
1.21M
        }
304
1.21M
305
1.21M
        // There should be a way to do this in-place with constant memory,
306
1.21M
        // but I couldn't figure out a simple way to do it. So just append
307
1.21M
        // the negation to the end of this range, and then drain it before
308
1.21M
        // we're done.
309
1.21M
        let drain_end = self.ranges.len();
310
1.21M
311
1.21M
        // We do checked arithmetic below because of the canonical ordering
312
1.21M
        // invariant.
313
1.21M
        if self.ranges[0].lower() > I::Bound::min_value() {
314
1.20M
            let upper = self.ranges[0].lower().decrement();
315
1.20M
            self.ranges.push(I::create(I::Bound::min_value(), upper));
316
1.20M
        }
317
1.21M
        for i in 1..drain_end {
318
905k
            let lower = self.ranges[i - 1].upper().increment();
319
905k
            let upper = self.ranges[i].lower().decrement();
320
905k
            self.ranges.push(I::create(lower, upper));
321
905k
        }
322
1.21M
        if self.ranges[drain_end - 1].upper() < I::Bound::max_value() {
323
1.20M
            let lower = self.ranges[drain_end - 1].upper().increment();
324
1.20M
            self.ranges.push(I::create(lower, I::Bound::max_value()));
325
1.20M
        }
326
1.21M
        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
1.21M
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::negate
Line
Count
Source
296
274
    pub fn negate(&mut self) {
297
274
        if self.ranges.is_empty() {
298
3
            let (min, max) = (I::Bound::min_value(), I::Bound::max_value());
299
3
            self.ranges.push(I::create(min, max));
300
3
            // The set containing everything must case folded.
301
3
            self.folded = true;
302
3
            return;
303
271
        }
304
271
305
271
        // There should be a way to do this in-place with constant memory,
306
271
        // but I couldn't figure out a simple way to do it. So just append
307
271
        // the negation to the end of this range, and then drain it before
308
271
        // we're done.
309
271
        let drain_end = self.ranges.len();
310
271
311
271
        // We do checked arithmetic below because of the canonical ordering
312
271
        // invariant.
313
271
        if self.ranges[0].lower() > I::Bound::min_value() {
314
196
            let upper = self.ranges[0].lower().decrement();
315
196
            self.ranges.push(I::create(I::Bound::min_value(), upper));
316
196
        }
317
3.58k
        for i in 1..drain_end {
318
3.58k
            let lower = self.ranges[i - 1].upper().increment();
319
3.58k
            let upper = self.ranges[i].lower().decrement();
320
3.58k
            self.ranges.push(I::create(lower, upper));
321
3.58k
        }
322
271
        if self.ranges[drain_end - 1].upper() < I::Bound::max_value() {
323
271
            let lower = self.ranges[drain_end - 1].upper().increment();
324
271
            self.ranges.push(I::create(lower, I::Bound::max_value()));
325
271
        }
326
271
        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
274
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::negate
Line
Count
Source
296
1.21M
    pub fn negate(&mut self) {
297
1.21M
        if self.ranges.is_empty() {
298
3.44k
            let (min, max) = (I::Bound::min_value(), I::Bound::max_value());
299
3.44k
            self.ranges.push(I::create(min, max));
300
3.44k
            // The set containing everything must case folded.
301
3.44k
            self.folded = true;
302
3.44k
            return;
303
1.21M
        }
304
1.21M
305
1.21M
        // There should be a way to do this in-place with constant memory,
306
1.21M
        // but I couldn't figure out a simple way to do it. So just append
307
1.21M
        // the negation to the end of this range, and then drain it before
308
1.21M
        // we're done.
309
1.21M
        let drain_end = self.ranges.len();
310
1.21M
311
1.21M
        // We do checked arithmetic below because of the canonical ordering
312
1.21M
        // invariant.
313
1.21M
        if self.ranges[0].lower() > I::Bound::min_value() {
314
1.20M
            let upper = self.ranges[0].lower().decrement();
315
1.20M
            self.ranges.push(I::create(I::Bound::min_value(), upper));
316
1.20M
        }
317
1.21M
        for i in 1..drain_end {
318
902k
            let lower = self.ranges[i - 1].upper().increment();
319
902k
            let upper = self.ranges[i].lower().decrement();
320
902k
            self.ranges.push(I::create(lower, upper));
321
902k
        }
322
1.21M
        if self.ranges[drain_end - 1].upper() < I::Bound::max_value() {
323
1.20M
            let lower = self.ranges[drain_end - 1].upper().increment();
324
1.20M
            self.ranges.push(I::create(lower, I::Bound::max_value()));
325
1.20M
        }
326
1.21M
        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
1.21M
    }
341
342
    /// Converts this set into a canonical ordering.
343
15.4M
    fn canonicalize(&mut self) {
344
15.4M
        if self.is_canonical() {
345
6.13M
            return;
346
9.33M
        }
347
9.33M
        self.ranges.sort();
348
9.33M
        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
9.33M
        let drain_end = self.ranges.len();
354
194M
        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
194M
            if self.ranges.len() > drain_end {
358
185M
                let (last, rest) = self.ranges.split_last_mut().unwrap();
359
185M
                if let Some(union) = last.union(&rest[oldi]) {
360
28.7M
                    *last = union;
361
28.7M
                    continue;
362
156M
                }
363
9.33M
            }
364
166M
            let range = self.ranges[oldi];
365
166M
            self.ranges.push(range);
366
        }
367
9.33M
        self.ranges.drain(..drain_end);
368
15.4M
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::canonicalize
Line
Count
Source
343
8.90M
    fn canonicalize(&mut self) {
344
8.90M
        if self.is_canonical() {
345
2.33M
            return;
346
6.57M
        }
347
6.57M
        self.ranges.sort();
348
6.57M
        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
6.57M
        let drain_end = self.ranges.len();
354
139M
        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
139M
            if self.ranges.len() > drain_end {
358
132M
                let (last, rest) = self.ranges.split_last_mut().unwrap();
359
132M
                if let Some(union) = last.union(&rest[oldi]) {
360
15.6M
                    *last = union;
361
15.6M
                    continue;
362
116M
                }
363
6.57M
            }
364
123M
            let range = self.ranges[oldi];
365
123M
            self.ranges.push(range);
366
        }
367
6.57M
        self.ranges.drain(..drain_end);
368
8.90M
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::canonicalize
Line
Count
Source
343
6.56M
    fn canonicalize(&mut self) {
344
6.56M
        if self.is_canonical() {
345
3.80M
            return;
346
2.76M
        }
347
2.76M
        self.ranges.sort();
348
2.76M
        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
2.76M
        let drain_end = self.ranges.len();
354
55.9M
        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
55.9M
            if self.ranges.len() > drain_end {
358
53.1M
                let (last, rest) = self.ranges.split_last_mut().unwrap();
359
53.1M
                if let Some(union) = last.union(&rest[oldi]) {
360
13.0M
                    *last = union;
361
13.0M
                    continue;
362
40.0M
                }
363
2.76M
            }
364
42.8M
            let range = self.ranges[oldi];
365
42.8M
            self.ranges.push(range);
366
        }
367
2.76M
        self.ranges.drain(..drain_end);
368
6.56M
    }
369
370
    /// Returns true if and only if this class is in a canonical ordering.
371
15.4M
    fn is_canonical(&self) -> bool {
372
163M
        for pair in self.ranges.windows(2) {
373
163M
            if pair[0] >= pair[1] {
374
9.27M
                return false;
375
154M
            }
376
154M
            if pair[0].is_contiguous(&pair[1]) {
377
61.1k
                return false;
378
154M
            }
379
        }
380
6.13M
        true
381
15.4M
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassBytesRange>>::is_canonical
Line
Count
Source
371
8.90M
    fn is_canonical(&self) -> bool {
372
108M
        for pair in self.ranges.windows(2) {
373
108M
            if pair[0] >= pair[1] {
374
6.53M
                return false;
375
102M
            }
376
102M
            if pair[0].is_contiguous(&pair[1]) {
377
39.1k
                return false;
378
102M
            }
379
        }
380
2.33M
        true
381
8.90M
    }
<regex_syntax::hir::interval::IntervalSet<regex_syntax::hir::ClassUnicodeRange>>::is_canonical
Line
Count
Source
371
6.56M
    fn is_canonical(&self) -> bool {
372
55.0M
        for pair in self.ranges.windows(2) {
373
55.0M
            if pair[0] >= pair[1] {
374
2.74M
                return false;
375
52.3M
            }
376
52.3M
            if pair[0].is_contiguous(&pair[1]) {
377
21.9k
                return false;
378
52.2M
            }
379
        }
380
3.80M
        true
381
6.56M
    }
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
69.7M
    fn next(&mut self) -> Option<&'a I> {
392
69.7M
        self.0.next()
393
69.7M
    }
<regex_syntax::hir::interval::IntervalSetIter<regex_syntax::hir::ClassBytesRange> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
391
14.6M
    fn next(&mut self) -> Option<&'a I> {
392
14.6M
        self.0.next()
393
14.6M
    }
<regex_syntax::hir::interval::IntervalSetIter<regex_syntax::hir::ClassUnicodeRange> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
391
55.0M
    fn next(&mut self) -> Option<&'a I> {
392
55.0M
        self.0.next()
393
55.0M
    }
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
112M
    fn create(lower: Self::Bound, upper: Self::Bound) -> Self {
412
112M
        let mut int = Self::default();
413
112M
        if lower <= upper {
414
112M
            int.set_lower(lower);
415
112M
            int.set_upper(upper);
416
112M
        } else {
417
0
            int.set_lower(upper);
418
0
            int.set_upper(lower);
419
0
        }
420
112M
        int
421
112M
    }
<regex_syntax::hir::ClassBytesRange as regex_syntax::hir::interval::Interval>::create
Line
Count
Source
411
66.6M
    fn create(lower: Self::Bound, upper: Self::Bound) -> Self {
412
66.6M
        let mut int = Self::default();
413
66.6M
        if lower <= upper {
414
66.6M
            int.set_lower(lower);
415
66.6M
            int.set_upper(upper);
416
66.6M
        } else {
417
0
            int.set_lower(upper);
418
0
            int.set_upper(lower);
419
0
        }
420
66.6M
        int
421
66.6M
    }
<regex_syntax::hir::ClassUnicodeRange as regex_syntax::hir::interval::Interval>::create
Line
Count
Source
411
45.4M
    fn create(lower: Self::Bound, upper: Self::Bound) -> Self {
412
45.4M
        let mut int = Self::default();
413
45.4M
        if lower <= upper {
414
45.4M
            int.set_lower(lower);
415
45.4M
            int.set_upper(upper);
416
45.4M
        } else {
417
0
            int.set_lower(upper);
418
0
            int.set_upper(lower);
419
0
        }
420
45.4M
        int
421
45.4M
    }
422
423
    /// Union the given overlapping range into this range.
424
    ///
425
    /// If the two ranges aren't contiguous, then this returns `None`.
426
185M
    fn union(&self, other: &Self) -> Option<Self> {
427
185M
        if !self.is_contiguous(other) {
428
156M
            return None;
429
28.7M
        }
430
28.7M
        let lower = cmp::min(self.lower(), other.lower());
431
28.7M
        let upper = cmp::max(self.upper(), other.upper());
432
28.7M
        Some(Self::create(lower, upper))
433
185M
    }
<regex_syntax::hir::ClassBytesRange as regex_syntax::hir::interval::Interval>::union
Line
Count
Source
426
132M
    fn union(&self, other: &Self) -> Option<Self> {
427
132M
        if !self.is_contiguous(other) {
428
116M
            return None;
429
15.6M
        }
430
15.6M
        let lower = cmp::min(self.lower(), other.lower());
431
15.6M
        let upper = cmp::max(self.upper(), other.upper());
432
15.6M
        Some(Self::create(lower, upper))
433
132M
    }
<regex_syntax::hir::ClassUnicodeRange as regex_syntax::hir::interval::Interval>::union
Line
Count
Source
426
53.1M
    fn union(&self, other: &Self) -> Option<Self> {
427
53.1M
        if !self.is_contiguous(other) {
428
40.0M
            return None;
429
13.0M
        }
430
13.0M
        let lower = cmp::min(self.lower(), other.lower());
431
13.0M
        let upper = cmp::max(self.upper(), other.upper());
432
13.0M
        Some(Self::create(lower, upper))
433
53.1M
    }
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
2.38M
    fn intersect(&self, other: &Self) -> Option<Self> {
439
2.38M
        let lower = cmp::max(self.lower(), other.lower());
440
2.38M
        let upper = cmp::min(self.upper(), other.upper());
441
2.38M
        if lower <= upper {
442
840k
            Some(Self::create(lower, upper))
443
        } else {
444
1.54M
            None
445
        }
446
2.38M
    }
<regex_syntax::hir::ClassBytesRange as regex_syntax::hir::interval::Interval>::intersect
Line
Count
Source
438
419k
    fn intersect(&self, other: &Self) -> Option<Self> {
439
419k
        let lower = cmp::max(self.lower(), other.lower());
440
419k
        let upper = cmp::min(self.upper(), other.upper());
441
419k
        if lower <= upper {
442
107k
            Some(Self::create(lower, upper))
443
        } else {
444
312k
            None
445
        }
446
419k
    }
<regex_syntax::hir::ClassUnicodeRange as regex_syntax::hir::interval::Interval>::intersect
Line
Count
Source
438
1.96M
    fn intersect(&self, other: &Self) -> Option<Self> {
439
1.96M
        let lower = cmp::max(self.lower(), other.lower());
440
1.96M
        let upper = cmp::min(self.upper(), other.upper());
441
1.96M
        if lower <= upper {
442
733k
            Some(Self::create(lower, upper))
443
        } else {
444
1.23M
            None
445
        }
446
1.96M
    }
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
1.04M
    fn difference(&self, other: &Self) -> (Option<Self>, Option<Self>) {
454
1.04M
        if self.is_subset(other) {
455
607k
            return (None, None);
456
436k
        }
457
436k
        if self.is_intersection_empty(other) {
458
0
            return (Some(self.clone()), None);
459
436k
        }
460
436k
        let add_lower = other.lower() > self.lower();
461
436k
        let add_upper = other.upper() < self.upper();
462
436k
        // We know this because !self.is_subset(other) and the ranges have
463
436k
        // a non-empty intersection.
464
436k
        assert!(add_lower || add_upper);
465
436k
        let mut ret = (None, None);
466
436k
        if add_lower {
467
356k
            let upper = other.lower().decrement();
468
356k
            ret.0 = Some(Self::create(self.lower(), upper));
469
356k
        }
470
436k
        if add_upper {
471
357k
            let lower = other.upper().increment();
472
357k
            let range = Self::create(lower, self.upper());
473
357k
            if ret.0.is_none() {
474
80.2k
                ret.0 = Some(range);
475
276k
            } else {
476
276k
                ret.1 = Some(range);
477
276k
            }
478
79.1k
        }
479
436k
        ret
480
1.04M
    }
<regex_syntax::hir::ClassBytesRange as regex_syntax::hir::interval::Interval>::difference
Line
Count
Source
453
224k
    fn difference(&self, other: &Self) -> (Option<Self>, Option<Self>) {
454
224k
        if self.is_subset(other) {
455
70.9k
            return (None, None);
456
153k
        }
457
153k
        if self.is_intersection_empty(other) {
458
0
            return (Some(self.clone()), None);
459
153k
        }
460
153k
        let add_lower = other.lower() > self.lower();
461
153k
        let add_upper = other.upper() < self.upper();
462
153k
        // We know this because !self.is_subset(other) and the ranges have
463
153k
        // a non-empty intersection.
464
153k
        assert!(add_lower || add_upper);
465
153k
        let mut ret = (None, None);
466
153k
        if add_lower {
467
127k
            let upper = other.lower().decrement();
468
127k
            ret.0 = Some(Self::create(self.lower(), upper));
469
127k
        }
470
153k
        if add_upper {
471
127k
            let lower = other.upper().increment();
472
127k
            let range = Self::create(lower, self.upper());
473
127k
            if ret.0.is_none() {
474
25.6k
                ret.0 = Some(range);
475
102k
            } else {
476
102k
                ret.1 = Some(range);
477
102k
            }
478
25.4k
        }
479
153k
        ret
480
224k
    }
<regex_syntax::hir::ClassUnicodeRange as regex_syntax::hir::interval::Interval>::difference
Line
Count
Source
453
820k
    fn difference(&self, other: &Self) -> (Option<Self>, Option<Self>) {
454
820k
        if self.is_subset(other) {
455
536k
            return (None, None);
456
283k
        }
457
283k
        if self.is_intersection_empty(other) {
458
0
            return (Some(self.clone()), None);
459
283k
        }
460
283k
        let add_lower = other.lower() > self.lower();
461
283k
        let add_upper = other.upper() < self.upper();
462
283k
        // We know this because !self.is_subset(other) and the ranges have
463
283k
        // a non-empty intersection.
464
283k
        assert!(add_lower || add_upper);
465
283k
        let mut ret = (None, None);
466
283k
        if add_lower {
467
228k
            let upper = other.lower().decrement();
468
228k
            ret.0 = Some(Self::create(self.lower(), upper));
469
228k
        }
470
283k
        if add_upper {
471
229k
            let lower = other.upper().increment();
472
229k
            let range = Self::create(lower, self.upper());
473
229k
            if ret.0.is_none() {
474
54.5k
                ret.0 = Some(range);
475
174k
            } else {
476
174k
                ret.1 = Some(range);
477
174k
            }
478
53.7k
        }
479
283k
        ret
480
820k
    }
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
340M
    fn is_contiguous(&self, other: &Self) -> bool {
486
340M
        let lower1 = self.lower().as_u32();
487
340M
        let upper1 = self.upper().as_u32();
488
340M
        let lower2 = other.lower().as_u32();
489
340M
        let upper2 = other.upper().as_u32();
490
340M
        cmp::max(lower1, lower2) <= cmp::min(upper1, upper2).saturating_add(1)
491
340M
    }
<regex_syntax::hir::ClassBytesRange as regex_syntax::hir::interval::Interval>::is_contiguous
Line
Count
Source
485
234M
    fn is_contiguous(&self, other: &Self) -> bool {
486
234M
        let lower1 = self.lower().as_u32();
487
234M
        let upper1 = self.upper().as_u32();
488
234M
        let lower2 = other.lower().as_u32();
489
234M
        let upper2 = other.upper().as_u32();
490
234M
        cmp::max(lower1, lower2) <= cmp::min(upper1, upper2).saturating_add(1)
491
234M
    }
<regex_syntax::hir::ClassUnicodeRange as regex_syntax::hir::interval::Interval>::is_contiguous
Line
Count
Source
485
105M
    fn is_contiguous(&self, other: &Self) -> bool {
486
105M
        let lower1 = self.lower().as_u32();
487
105M
        let upper1 = self.upper().as_u32();
488
105M
        let lower2 = other.lower().as_u32();
489
105M
        let upper2 = other.upper().as_u32();
490
105M
        cmp::max(lower1, lower2) <= cmp::min(upper1, upper2).saturating_add(1)
491
105M
    }
492
493
    /// Returns true if and only if the intersection of this range and the
494
    /// other range is empty.
495
36.5M
    fn is_intersection_empty(&self, other: &Self) -> bool {
496
36.5M
        let (lower1, upper1) = (self.lower(), self.upper());
497
36.5M
        let (lower2, upper2) = (other.lower(), other.upper());
498
36.5M
        cmp::max(lower1, lower2) > cmp::min(upper1, upper2)
499
36.5M
    }
<regex_syntax::hir::ClassBytesRange as regex_syntax::hir::interval::Interval>::is_intersection_empty
Line
Count
Source
495
34.7M
    fn is_intersection_empty(&self, other: &Self) -> bool {
496
34.7M
        let (lower1, upper1) = (self.lower(), self.upper());
497
34.7M
        let (lower2, upper2) = (other.lower(), other.upper());
498
34.7M
        cmp::max(lower1, lower2) > cmp::min(upper1, upper2)
499
34.7M
    }
<regex_syntax::hir::ClassUnicodeRange as regex_syntax::hir::interval::Interval>::is_intersection_empty
Line
Count
Source
495
1.86M
    fn is_intersection_empty(&self, other: &Self) -> bool {
496
1.86M
        let (lower1, upper1) = (self.lower(), self.upper());
497
1.86M
        let (lower2, upper2) = (other.lower(), other.upper());
498
1.86M
        cmp::max(lower1, lower2) > cmp::min(upper1, upper2)
499
1.86M
    }
500
501
    /// Returns true if and only if this range is a subset of the other range.
502
1.04M
    fn is_subset(&self, other: &Self) -> bool {
503
1.04M
        let (lower1, upper1) = (self.lower(), self.upper());
504
1.04M
        let (lower2, upper2) = (other.lower(), other.upper());
505
1.04M
        (lower2 <= lower1 && lower1 <= upper2)
506
688k
            && (lower2 <= upper1 && upper1 <= upper2)
507
1.04M
    }
<regex_syntax::hir::ClassBytesRange as regex_syntax::hir::interval::Interval>::is_subset
Line
Count
Source
502
224k
    fn is_subset(&self, other: &Self) -> bool {
503
224k
        let (lower1, upper1) = (self.lower(), self.upper());
504
224k
        let (lower2, upper2) = (other.lower(), other.upper());
505
224k
        (lower2 <= lower1 && lower1 <= upper2)
506
96.6k
            && (lower2 <= upper1 && upper1 <= upper2)
507
224k
    }
<regex_syntax::hir::ClassUnicodeRange as regex_syntax::hir::interval::Interval>::is_subset
Line
Count
Source
502
820k
    fn is_subset(&self, other: &Self) -> bool {
503
820k
        let (lower1, upper1) = (self.lower(), self.upper());
504
820k
        let (lower2, upper2) = (other.lower(), other.upper());
505
820k
        (lower2 <= lower1 && lower1 <= upper2)
506
591k
            && (lower2 <= upper1 && upper1 <= upper2)
507
820k
    }
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
470
    fn min_value() -> Self {
522
470
        u8::MIN
523
470
    }
524
545
    fn max_value() -> Self {
525
545
        u8::MAX
526
545
    }
527
938M
    fn as_u32(self) -> u32 {
528
938M
        u32::from(self)
529
938M
    }
530
131k
    fn increment(self) -> Self {
531
131k
        self.checked_add(1).unwrap()
532
131k
    }
533
131k
    fn decrement(self) -> Self {
534
131k
        self.checked_sub(1).unwrap()
535
131k
    }
536
}
537
538
impl Bound for char {
539
2.42M
    fn min_value() -> Self {
540
2.42M
        '\x00'
541
2.42M
    }
542
2.42M
    fn max_value() -> Self {
543
2.42M
        '\u{10FFFF}'
544
2.42M
    }
545
421M
    fn as_u32(self) -> u32 {
546
421M
        u32::from(self)
547
421M
    }
548
549
2.33M
    fn increment(self) -> Self {
550
2.33M
        match self {
551
0
            '\u{D7FF}' => '\u{E000}',
552
2.33M
            c => char::from_u32(u32::from(c).checked_add(1).unwrap()).unwrap(),
553
        }
554
2.33M
    }
555
556
2.33M
    fn decrement(self) -> Self {
557
2.33M
        match self {
558
0
            '\u{E000}' => '\u{D7FF}',
559
2.33M
            c => char::from_u32(u32::from(c).checked_sub(1).unwrap()).unwrap(),
560
        }
561
2.33M
    }
562
}
563
564
// Tests for interval sets are written in src/hir.rs against the public API.