rangemap/
operations.rs

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

/// Trait to determine the ordering of the start and end of a range.
trait RangeOrder {
    /// Ordering of start value
    fn order_start(&self, other: &Self) -> Ordering;

    /// Ordering of end value
    fn order_end(&self, other: &Self) -> Ordering;
}

impl<T: Ord> RangeOrder for Range<T> {
    fn order_start(&self, other: &Self) -> Ordering {
        self.start.cmp(&other.start)
    }

    fn order_end(&self, other: &Self) -> Ordering {
        self.end.cmp(&other.end)
    }
}

impl<T: Ord> RangeOrder for RangeInclusive<T> {
    fn order_start(&self, other: &Self) -> Ordering {
        self.start().cmp(other.start())
    }

    fn order_end(&self, other: &Self) -> Ordering {
        self.end().cmp(other.end())
    }
}

/// Range which can be merged with a next range if they overlap.
trait RangeMerge: Sized {
    /// Merges this range and the next range, if they overlap.
    fn merge(&mut self, next: &Self) -> bool;
}

impl<T: Ord + Clone> RangeMerge for Range<T> {
    fn merge(&mut self, other: &Self) -> bool {
        if !self.contains(&other.start) {
            return false;
        }

        if other.end > self.end {
            self.end = other.end.clone();
        }

        true
    }
}

impl<T: Ord + Clone> RangeMerge for RangeInclusive<T> {
    fn merge(&mut self, other: &Self) -> bool {
        if !self.contains(other.start()) {
            return false;
        }

        if other.end() > self.end() {
            *self = RangeInclusive::new(self.start().clone(), other.end().clone());
        }

        true
    }
}

/// Range which can be merged with a next range if they overlap.
trait RangeIntersect: Sized {
    /// Attempt to merge the next range into the current range, if they overlap.
    fn intersect(&self, next: &Self) -> Option<Self>;
}

impl<T: Ord + Clone> RangeIntersect for Range<T> {
    fn intersect(&self, other: &Self) -> Option<Self> {
        let start = (&self.start).max(&other.start);
        let end = (&self.end).min(&other.end);

        if start >= end {
            return None;
        }

        Some(start.clone()..end.clone())
    }
}

impl<T: Ord + Clone> RangeIntersect for RangeInclusive<T> {
    fn intersect(&self, other: &Self) -> Option<Self> {
        let start = self.start().max(other.start());
        let end = self.end().min(other.end());

        if start > end {
            return None;
        }

        Some(start.clone()..=end.clone())
    }
}

#[test]
fn test_intersect() {
    assert_eq!((0..5).intersect(&(0..3)), Some(0..3));
    assert_eq!((0..3).intersect(&(0..5)), Some(0..3));
    assert_eq!((0..3).intersect(&(3..3)), None);
}

/// Iterator that produces the union of two iterators of sorted ranges.
pub struct Union<'a, T, L, R = L>
where
    T: 'a,
    L: Iterator<Item = &'a T>,
    R: Iterator<Item = &'a T>,
{
    left: Peekable<L>,
    right: Peekable<R>,
}

impl<'a, T, L, R> Union<'a, T, L, R>
where
    T: 'a,
    L: Iterator<Item = &'a T>,
    R: Iterator<Item = &'a T>,
{
    /// Create new Union iterator.
    ///
    /// Requires that the two iterators produce sorted ranges.
    pub fn new(left: L, right: R) -> Self {
        Self {
            left: left.peekable(),
            right: right.peekable(),
        }
    }
}

impl<'a, R, I> Iterator for Union<'a, R, I>
where
    R: RangeOrder + RangeMerge + Clone,
    I: Iterator<Item = &'a R>,
{
    type Item = R;

    fn next(&mut self) -> Option<Self::Item> {
        // get start range
        let mut range = match (self.left.peek(), self.right.peek()) {
            // if there is only one possible range, pick that
            (Some(_), None) => self.left.next().unwrap(),
            (None, Some(_)) => self.right.next().unwrap(),
            // when there are two ranges, pick the one with the earlier start
            (Some(left), Some(right)) => {
                if left.order_start(right).is_lt() {
                    self.left.next().unwrap()
                } else {
                    self.right.next().unwrap()
                }
            }
            // otherwise we are done
            (None, None) => return None,
        }
        .clone();

        // peek into next value of iterator and merge if it is contiguous
        let mut join = |iter: &mut Peekable<I>| {
            if let Some(next) = iter.peek() {
                if range.merge(next) {
                    iter.next().unwrap();
                    return true;
                }
            }
            false
        };

        // keep merging ranges as long as we can
        loop {
            if !(join(&mut self.left) || join(&mut self.right)) {
                break;
            }
        }

        Some(range)
    }
}

impl<'a, R, I> FusedIterator for Union<'a, R, I>
where
    R: RangeOrder + RangeMerge + Clone,
    I: Iterator<Item = &'a R>,
{
}

/// Iterator that produces the union of two iterators of sorted ranges.
pub struct Intersection<'a, T, L, R = L>
where
    T: 'a,
    L: Iterator<Item = &'a T>,
    R: Iterator<Item = &'a T>,
{
    left: Peekable<L>,
    right: Peekable<R>,
}

impl<'a, T, L, R> Intersection<'a, T, L, R>
where
    T: 'a,
    L: Iterator<Item = &'a T>,
    R: Iterator<Item = &'a T>,
{
    /// Create new Intersection iterator.
    ///
    /// Requires that the two iterators produce sorted ranges.
    pub fn new(left: L, right: R) -> Self {
        Self {
            left: left.peekable(),
            right: right.peekable(),
        }
    }
}

impl<'a, R, I> Iterator for Intersection<'a, R, I>
where
    R: RangeOrder + RangeIntersect + Clone,
    I: Iterator<Item = &'a R>,
{
    type Item = R;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            // if we don't have at least two ranges, there cannot be an intersection
            let (Some(left), Some(right)) = (self.left.peek(), self.right.peek()) else {
                return None;
            };

            let intersection = left.intersect(right);

            // pop the range that ends earlier
            if left.order_end(right).is_lt() {
                self.left.next();
            } else {
                self.right.next();
            }

            if let Some(intersection) = intersection {
                return Some(intersection);
            }
        }
    }
}