read_fonts/collections/
range_set.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
//! Stores a disjoint collection of ranges over numeric types.
//!
//! Overlapping and adjacent ranges are automatically merged together.

use core::{
    cmp::{max, min},
    fmt::{Debug, Formatter},
    iter::Peekable,
    ops::RangeInclusive,
};
use std::collections::BTreeMap;

use types::Fixed;

#[derive(Default, Clone, PartialEq, Eq)]
/// A set of disjoint ranges over numeric types.
///
/// Overlapping and adjacent ranges are automatically merged together.
pub struct RangeSet<T> {
    // an entry in the map ranges[a] = b implies there is an range [a, b] (inclusive) in this set.
    ranges: BTreeMap<T, T>,
}

/// Allows a two values to be tested for adjacency.
pub trait OrdAdjacency {
    /// Returns true if self is adjacent on either side of rhs.
    fn are_adjacent(self, rhs: Self) -> bool;
}

impl<T> RangeSet<T>
where
    T: Ord + Copy + OrdAdjacency,
{
    // Returns true if there are no members in this set currently.
    pub fn is_empty(&self) -> bool {
        self.ranges.is_empty()
    }

    /// Insert a range into this set, automatically merging with existing ranges as needed.
    pub fn insert(&mut self, range: RangeInclusive<T>) {
        if range.end() < range.start() {
            // ignore or malformed ranges.
            return;
        }

        let mut start = *range.start();
        let mut end = *range.end();

        // There may be up to one intersecting range prior to this new range, check for it and merge if needed.
        if let Some((prev_start, prev_end)) = self.prev_range(start) {
            if range_is_subset(start, end, prev_start, prev_end) {
                return;
            }
            if ranges_overlap_or_adjacent(start, end, prev_start, prev_end) {
                start = min(start, prev_start);
                end = max(end, prev_end);
                self.ranges.remove(&prev_start);
            }
        };

        // There may be one or more ranges proceeding this new range that intersect, find and merge them as needed.
        loop {
            let Some((next_start, next_end)) = self.next_range(start) else {
                // No existing ranges which might overlap, can now insert the current range
                self.ranges.insert(start, end);
                return;
            };

            if range_is_subset(start, end, next_start, next_end) {
                return;
            }
            if ranges_overlap_or_adjacent(start, end, next_start, next_end) {
                start = min(start, next_start);
                end = max(end, next_end);
                self.ranges.remove(&next_start);
            } else {
                self.ranges.insert(start, end);
                return;
            }
        }
    }

    /// Returns an iterator over the contained ranges.
    pub fn iter(&'_ self) -> impl Iterator<Item = RangeInclusive<T>> + '_ {
        self.ranges.iter().map(|(a, b)| *a..=*b)
    }

    /// Returns an iterator over the intersection of this and other.
    pub fn intersection<'a>(
        &'a self,
        other: &'a Self,
    ) -> impl Iterator<Item = RangeInclusive<T>> + 'a {
        IntersectionIter {
            it_a: self.iter().peekable(),
            it_b: other.iter().peekable(),
        }
    }

    /// Finds a range in this set with a start greater than or equal to the provided start value.
    fn next_range(&self, start: T) -> Option<(T, T)> {
        let (next_start, next_end) = self.ranges.range(start..).next()?;
        Some((*next_start, *next_end))
    }

    /// Finds a range in this set with a start less than the provided start value.
    fn prev_range(&self, start: T) -> Option<(T, T)> {
        let (next_start, next_end) = self.ranges.range(..start).next_back()?;
        Some((*next_start, *next_end))
    }
}

impl<T> Extend<RangeInclusive<T>> for RangeSet<T>
where
    T: Copy + Ord + OrdAdjacency,
{
    fn extend<I: IntoIterator<Item = RangeInclusive<T>>>(&mut self, iter: I) {
        iter.into_iter().for_each(|r| self.insert(r));
    }
}

impl<T> FromIterator<RangeInclusive<T>> for RangeSet<T>
where
    T: Default + Copy + Ord + OrdAdjacency,
{
    fn from_iter<I: IntoIterator<Item = RangeInclusive<T>>>(iter: I) -> Self {
        let mut result: Self = Default::default();
        result.extend(iter);
        result
    }
}

impl<T> Debug for RangeSet<T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
        write!(f, "RangeSet {{")?;
        for (start, end) in self.ranges.iter() {
            write!(f, "[{:?}, {:?}], ", start, end)?;
        }
        write!(f, "}}")
    }
}

struct IntersectionIter<A, B, T>
where
    A: Iterator<Item = RangeInclusive<T>>,
    B: Iterator<Item = RangeInclusive<T>>,
{
    it_a: Peekable<A>,
    it_b: Peekable<B>,
}

impl<A, B, T> Iterator for IntersectionIter<A, B, T>
where
    A: Iterator<Item = RangeInclusive<T>>,
    B: Iterator<Item = RangeInclusive<T>>,
    T: Ord + Copy,
{
    type Item = RangeInclusive<T>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let (Some(a), Some(b)) = (self.it_a.peek(), self.it_b.peek()) else {
                return None;
            };

            let a = a.clone();
            let b = b.clone();

            match range_intersection(&a, &b) {
                Some(intersection) => {
                    self.step_iterators(&a, &b);
                    return Some(intersection);
                }
                None => self.step_iterators(&a, &b),
            }
        }
    }
}

impl<A, B, T> IntersectionIter<A, B, T>
where
    A: Iterator<Item = RangeInclusive<T>>,
    B: Iterator<Item = RangeInclusive<T>>,
    T: Ord,
{
    fn step_iterators(&mut self, a: &RangeInclusive<T>, b: &RangeInclusive<T>) {
        if a.end() <= b.end() {
            self.it_a.next();
        }

        if a.end() >= b.end() {
            self.it_b.next();
        }
    }
}

impl OrdAdjacency for u32 {
    fn are_adjacent(self, rhs: u32) -> bool {
        matches!(self.checked_add(1).map(|r| r == rhs), Some(true))
            || matches!(rhs.checked_add(1).map(|r| r == self), Some(true))
    }
}

impl OrdAdjacency for u16 {
    fn are_adjacent(self, rhs: u16) -> bool {
        matches!(self.checked_add(1).map(|r| r == rhs), Some(true))
            || matches!(rhs.checked_add(1).map(|r| r == self), Some(true))
    }
}

impl OrdAdjacency for Fixed {
    fn are_adjacent(self, rhs: Fixed) -> bool {
        matches!(
            self.checked_add(Fixed::EPSILON).map(|r| r == rhs),
            Some(true)
        ) || matches!(
            rhs.checked_add(Fixed::EPSILON).map(|r| r == self),
            Some(true)
        )
    }
}

/// If a and b intersect return a range representing the intersection.
fn range_intersection<T: Ord + Copy>(
    a: &RangeInclusive<T>,
    b: &RangeInclusive<T>,
) -> Option<RangeInclusive<T>> {
    if a.start() <= b.end() && b.start() <= a.end() {
        Some(*max(a.start(), b.start())..=*min(a.end(), b.end()))
    } else {
        None
    }
}

/// Returns true if the ranges [a_start, a_end] and [b_start, b_end] overlap or are adjacent to each other.
///
/// All bounds are inclusive.
fn ranges_overlap_or_adjacent<T>(a_start: T, a_end: T, b_start: T, b_end: T) -> bool
where
    T: Ord + OrdAdjacency,
{
    (a_start <= b_end && b_start <= a_end)
        || (a_end.are_adjacent(b_start))
        || (b_end.are_adjacent(a_start))
}

/// Returns true if the range [a_start, a_end] is a subset of [b_start, b_end].
///
/// All bounds are inclusive.
fn range_is_subset<T>(a_start: T, a_end: T, b_start: T, b_end: T) -> bool
where
    T: Ord,
{
    a_start >= b_start && a_end <= b_end
}

#[cfg(test)]
mod test {

    use super::*;

    #[test]
    #[allow(clippy::reversed_empty_ranges)]
    fn insert_invalid() {
        let mut map: RangeSet<u32> = Default::default();
        map.insert(12..=11);
        assert_eq!(map.iter().collect::<Vec<_>>(), vec![],);
    }

    #[test]
    fn insert_non_overlapping() {
        let mut map: RangeSet<u32> = Default::default();

        map.insert(11..=11);
        map.insert(2..=3);
        map.insert(6..=9);

        assert_eq!(map.iter().collect::<Vec<_>>(), vec![2..=3, 6..=9, 11..=11],);
    }

    #[test]
    fn insert_subset_before() {
        let mut map: RangeSet<u32> = Default::default();

        map.insert(2..=8);
        map.insert(3..=7);

        assert_eq!(map.iter().collect::<Vec<_>>(), vec![2..=8],);
    }

    #[test]
    fn insert_subset_after() {
        let mut map: RangeSet<u32> = Default::default();

        map.insert(2..=8);
        map.insert(2..=7);
        map.insert(2..=8);

        assert_eq!(map.iter().collect::<Vec<_>>(), vec![2..=8],);
    }

    #[test]
    fn insert_overlapping_before() {
        let mut map: RangeSet<u32> = Default::default();

        map.insert(2..=8);
        map.insert(7..=11);

        assert_eq!(map.iter().collect::<Vec<_>>(), vec![2..=11],);
    }

    #[test]
    fn insert_overlapping_after() {
        let mut map: RangeSet<u32> = Default::default();
        map.insert(10..=14);
        map.insert(7..=11);
        assert_eq!(map.iter().collect::<Vec<_>>(), vec![7..=14],);

        let mut map: RangeSet<u32> = Default::default();
        map.insert(10..=14);
        map.insert(10..=17);
        assert_eq!(map.iter().collect::<Vec<_>>(), vec![10..=17],);
    }

    #[test]
    fn insert_overlapping_multiple_after() {
        let mut map: RangeSet<u32> = Default::default();
        map.insert(10..=14);
        map.insert(16..=17);
        map.insert(7..=16);
        assert_eq!(map.iter().collect::<Vec<_>>(), vec![7..=17],);

        let mut map: RangeSet<u32> = Default::default();
        map.insert(10..=14);
        map.insert(16..=17);
        map.insert(10..=16);
        assert_eq!(map.iter().collect::<Vec<_>>(), vec![10..=17],);

        let mut map: RangeSet<u32> = Default::default();
        map.insert(10..=14);
        map.insert(16..=17);
        map.insert(10..=17);
        assert_eq!(map.iter().collect::<Vec<_>>(), vec![10..=17],);
    }

    #[test]
    fn insert_overlapping_before_and_after() {
        let mut map: RangeSet<u32> = Default::default();

        map.insert(6..=8);
        map.insert(10..=14);
        map.insert(16..=20);

        map.insert(7..=19);

        assert_eq!(map.iter().collect::<Vec<_>>(), vec![6..=20],);
    }

    #[test]
    fn insert_joins_adjacent() {
        let mut map: RangeSet<u32> = Default::default();
        map.insert(6..=8);
        map.insert(9..=10);
        assert_eq!(map.iter().collect::<Vec<_>>(), vec![6..=10],);

        let mut map: RangeSet<u32> = Default::default();
        map.insert(9..=10);
        map.insert(6..=8);
        assert_eq!(map.iter().collect::<Vec<_>>(), vec![6..=10],);

        let mut map: RangeSet<u32> = Default::default();
        map.insert(6..=8);
        map.insert(10..=10);
        map.insert(9..=9);
        assert_eq!(map.iter().collect::<Vec<_>>(), vec![6..=10],);
    }

    #[test]
    fn from_iter_and_extend() {
        let mut map: RangeSet<u32> = [2..=5, 13..=64, 7..=9].into_iter().collect();
        assert_eq!(map.iter().collect::<Vec<_>>(), vec![2..=5, 7..=9, 13..=64],);

        map.extend([6..=17, 100..=101]);

        assert_eq!(map.iter().collect::<Vec<_>>(), vec![2..=64, 100..=101],);
    }

    #[test]
    fn intersection() {
        let a: RangeSet<u32> = [2..=5, 7..=9, 13..=64].into_iter().collect();
        let b: RangeSet<u32> = [1..=3, 5..=8, 13..=64, 67..=69].into_iter().collect();

        let expected = vec![2..=3, 5..=5, 7..=8, 13..=64];

        assert_eq!(a.intersection(&b).collect::<Vec<_>>(), expected);
        assert_eq!(b.intersection(&a).collect::<Vec<_>>(), expected);
    }
}