1 #![allow(dead_code)]
2 
3 use std::{
4     cmp,
5     cmp::Ordering,
6     collections::{btree_map, BTreeMap},
7     fmt::{Debug, Error as FmtError, Formatter},
8     iter::{FromIterator, FusedIterator, Peekable},
9     ops::{Add, Bound, Range, Sub},
10 };
11 
12 /// A map whose keys are stored as (half-open) ranges bounded
13 /// inclusively below and exclusively above `(start..end)`.
14 ///
15 /// Contiguous and overlapping ranges that map to the same value
16 /// are coalesced into a single range.
17 #[derive(Clone)]
18 pub struct RangeMap<K, V> {
19     // Wrap ranges so that they are `Ord`.
20     // See `range_wrapper.rs` for explanation.
21     btm: BTreeMap<RangeStartWrapper<K>, V>,
22 }
23 
24 impl<K, V> Default for RangeMap<K, V>
25 where
26     K: Ord + Clone,
27     V: Eq + Clone,
28 {
default() -> Self29     fn default() -> Self {
30         Self::new()
31     }
32 }
33 
34 impl<K, V> RangeMap<K, V>
35 where
36     K: Ord + Clone,
37     V: Eq + Clone,
38 {
39     /// Makes a new empty `RangeMap`.
40     #[inline]
new() -> Self41     pub fn new() -> Self {
42         RangeMap {
43             btm: BTreeMap::new(),
44         }
45     }
46 
47     /// Returns a reference to the value corresponding to the given key,
48     /// if the key is covered by any range in the map.
49     #[inline]
get(&self, key: &K) -> Option<&V>50     pub fn get(&self, key: &K) -> Option<&V> {
51         self.get_key_value(key).map(|(_range, value)| value)
52     }
53 
54     /// Returns the range-value pair (as a pair of references) corresponding
55     /// to the given key, if the key is covered by any range in the map.
56     #[inline]
get_key_value(&self, key: &K) -> Option<(&Range<K>, &V)>57     pub fn get_key_value(&self, key: &K) -> Option<(&Range<K>, &V)> {
58         // The only stored range that could contain the given key is the
59         // last stored range whose start is less than or equal to this key.
60         let key_as_start = RangeStartWrapper::new(key.clone()..key.clone());
61 
62         self.btm
63             .range((Bound::Unbounded, Bound::Included(key_as_start)))
64             .next_back()
65             .filter(|(range_start_wrapper, _value)| {
66                 // Does the only candidate range contain
67                 // the requested key?
68                 range_start_wrapper.range.contains(key)
69             })
70             .map(|(range_start_wrapper, value)| (&range_start_wrapper.range, value))
71     }
72 
73     /// Returns `true` if any range in the map covers the specified key.
74     #[inline]
contains_key(&self, key: &K) -> bool75     pub fn contains_key(&self, key: &K) -> bool {
76         self.get(key).is_some()
77     }
78 
79     /// Returns `true` if any part of the provided range overlaps with a range in the map.
80     #[inline]
contains_any(&self, range: &Range<K>) -> bool81     pub fn contains_any(&self, range: &Range<K>) -> bool {
82         self.range(range).next().is_some()
83     }
84 
85     /// Returns `true` if all of the provided range is covered by ranges in the map.
86     #[inline]
contains_all(&self, range: &Range<K>) -> bool87     pub fn contains_all(&self, range: &Range<K>) -> bool {
88         self.gaps(range).next().is_none()
89     }
90 
91     /// Gets an iterator over all pairs of key range and value,
92     /// ordered by key range.
93     ///
94     /// The iterator element type is `(&'a Range<K>, &'a V)`.
95     #[inline]
iter(&self) -> Iter<'_, K, V>96     pub fn iter(&self) -> Iter<'_, K, V> {
97         Iter {
98             inner: self.btm.iter(),
99         }
100     }
101 
102     /// Gets a mutable iterator over all pairs of key range and value,
103     /// ordered by key range.
104     ///
105     /// The iterator element type is `(&'a Range<K>, &'a mut V)`.
106     #[inline]
iter_mut(&mut self) -> IterMut<'_, K, V>107     pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
108         IterMut {
109             inner: self.btm.iter_mut(),
110         }
111     }
112 
113     /// Insert a pair of key range and value into the map.
114     ///
115     /// If the inserted range partially or completely overlaps any
116     /// existing range in the map, then the existing range (or ranges) will be
117     /// partially or completely replaced by the inserted range.
118     ///
119     /// If the inserted range either overlaps or is immediately adjacent
120     /// any existing range _mapping to the same value_, then the ranges
121     /// will be coalesced into a single contiguous range.
122     ///
123     /// # Panics
124     ///
125     /// Panics if range `start >= end`.
insert(&mut self, range: Range<K>, value: V)126     pub fn insert(&mut self, range: Range<K>, value: V) {
127         // We don't want to have to make empty ranges make sense;
128         // they don't represent anything meaningful in this structure.
129         assert!(range.start < range.end);
130 
131         // Wrap up the given range so that we can "borrow"
132         // it as a wrapper reference to either its start or end.
133         // See `range_wrapper.rs` for explanation of these hacks.
134         let mut new_range_start_wrapper: RangeStartWrapper<K> = RangeStartWrapper::new(range);
135         let new_value = value;
136 
137         // Is there a stored range either overlapping the start of
138         // the range to insert or immediately preceding it?
139         //
140         // If there is any such stored range, it will be the last
141         // whose start is less than or equal to the start of the range to insert,
142         // or the one before that if both of the above cases exist.
143         let mut candidates = self
144             .btm
145             .range((Bound::Unbounded, Bound::Included(&new_range_start_wrapper)))
146             .rev()
147             .take(2)
148             .filter(|(stored_range_start_wrapper, _stored_value)| {
149                 // Does the candidate range either overlap
150                 // or immediately precede the range to insert?
151                 // (Remember that it might actually cover the _whole_
152                 // range to insert and then some.)
153                 stored_range_start_wrapper
154                     .range
155                     .touches(&new_range_start_wrapper.range)
156             });
157 
158         if let Some(mut candidate) = candidates.next() {
159             // Or the one before it if both cases described above exist.
160             if let Some(another_candidate) = candidates.next() {
161                 candidate = another_candidate;
162             }
163 
164             let (stored_range_start_wrapper, stored_value) =
165                 (candidate.0.clone(), candidate.1.clone());
166 
167             self.adjust_touching_ranges_for_insert(
168                 stored_range_start_wrapper,
169                 stored_value,
170                 &mut new_range_start_wrapper.range,
171                 &new_value,
172             );
173         }
174 
175         // Are there any stored ranges whose heads overlap or immediately
176         // follow the range to insert?
177         //
178         // If there are any such stored ranges (that weren't already caught above),
179         // their starts will fall somewhere after the start of the range to insert,
180         // and on or before its end.
181         //
182         // This time around, if the latter holds, it also implies
183         // the former so we don't need to check here if they touch.
184         //
185         // REVISIT: Possible micro-optimisation: `impl Borrow<T> for RangeStartWrapper<T>`
186         // and use that to search here, to avoid constructing another `RangeStartWrapper`.
187         let new_range_end_as_start = RangeStartWrapper::new(
188             new_range_start_wrapper.range.end.clone()..new_range_start_wrapper.range.end.clone(),
189         );
190 
191         while let Some((stored_range_start_wrapper, stored_value)) = self
192             .btm
193             .range((
194                 Bound::Included(&new_range_start_wrapper),
195                 Bound::Included(&new_range_end_as_start),
196             ))
197             .next()
198         {
199             // One extra exception: if we have different values,
200             // and the stored range starts at the end of the range to insert,
201             // then we don't want to keep looping forever trying to find more!
202             #[allow(clippy::suspicious_operation_groupings)]
203             if stored_range_start_wrapper.range.start == new_range_start_wrapper.range.end
204                 && *stored_value != new_value
205             {
206                 // We're beyond the last stored range that could be relevant.
207                 // Avoid wasting time on irrelevant ranges, or even worse, looping forever.
208                 // (`adjust_touching_ranges_for_insert` below assumes that the given range
209                 // is relevant, and behaves very poorly if it is handed a range that it
210                 // shouldn't be touching.)
211                 break;
212             }
213 
214             let stored_range_start_wrapper = stored_range_start_wrapper.clone();
215             let stored_value = stored_value.clone();
216 
217             self.adjust_touching_ranges_for_insert(
218                 stored_range_start_wrapper,
219                 stored_value,
220                 &mut new_range_start_wrapper.range,
221                 &new_value,
222             );
223         }
224 
225         // Insert the (possibly expanded) new range, and we're done!
226         self.btm.insert(new_range_start_wrapper, new_value);
227     }
228 
229     /// Removes a range from the map, if all or any of it was present.
230     ///
231     /// If the range to be removed _partially_ overlaps any ranges
232     /// in the map, then those ranges will be contracted to no
233     /// longer cover the removed range.
234     ///
235     ///
236     /// # Panics
237     ///
238     /// Panics if range `start >= end`.
remove(&mut self, range: Range<K>)239     pub fn remove(&mut self, range: Range<K>) {
240         // We don't want to have to make empty ranges make sense;
241         // they don't represent anything meaningful in this structure.
242         assert!(range.start < range.end);
243 
244         let range_start_wrapper: RangeStartWrapper<K> = RangeStartWrapper::new(range);
245         let range = &range_start_wrapper.range;
246 
247         // Is there a stored range overlapping the start of
248         // the range to insert?
249         //
250         // If there is any such stored range, it will be the last
251         // whose start is less than or equal to the start of the range to insert.
252         if let Some((stored_range_start_wrapper, stored_value)) = self
253             .btm
254             .range((Bound::Unbounded, Bound::Included(&range_start_wrapper)))
255             .next_back()
256             .filter(|(stored_range_start_wrapper, _stored_value)| {
257                 // Does the only candidate range overlap
258                 // the range to insert?
259                 stored_range_start_wrapper.range.overlaps(range)
260             })
261             .map(|(stored_range_start_wrapper, stored_value)| {
262                 (stored_range_start_wrapper.clone(), stored_value.clone())
263             })
264         {
265             self.adjust_overlapping_ranges_for_remove(
266                 stored_range_start_wrapper,
267                 stored_value,
268                 range,
269             );
270         }
271 
272         // Are there any stored ranges whose heads overlap the range to insert?
273         //
274         // If there are any such stored ranges (that weren't already caught above),
275         // their starts will fall somewhere after the start of the range to insert,
276         // and before its end.
277         //
278         // REVISIT: Possible micro-optimisation: `impl Borrow<T> for RangeStartWrapper<T>`
279         // and use that to search here, to avoid constructing another `RangeStartWrapper`.
280         let new_range_end_as_start = RangeStartWrapper::new(range.end.clone()..range.end.clone());
281 
282         while let Some((stored_range_start_wrapper, stored_value)) = self
283             .btm
284             .range((
285                 Bound::Excluded(&range_start_wrapper),
286                 Bound::Excluded(&new_range_end_as_start),
287             ))
288             .next()
289             .map(|(stored_range_start_wrapper, stored_value)| {
290                 (stored_range_start_wrapper.clone(), stored_value.clone())
291             })
292         {
293             self.adjust_overlapping_ranges_for_remove(
294                 stored_range_start_wrapper,
295                 stored_value,
296                 range,
297             );
298         }
299     }
300 
adjust_touching_ranges_for_insert( &mut self, stored_range_start_wrapper: RangeStartWrapper<K>, stored_value: V, new_range: &mut Range<K>, new_value: &V, )301     fn adjust_touching_ranges_for_insert(
302         &mut self,
303         stored_range_start_wrapper: RangeStartWrapper<K>,
304         stored_value: V,
305         new_range: &mut Range<K>,
306         new_value: &V,
307     ) {
308         if stored_value == *new_value {
309             // The ranges have the same value, so we can "adopt"
310             // the stored range.
311             //
312             // This means that no matter how big or where the stored range is,
313             // we will expand the new range's bounds to subsume it,
314             // and then delete the stored range.
315             new_range.start =
316                 cmp::min(&new_range.start, &stored_range_start_wrapper.range.start).clone();
317             new_range.end = cmp::max(&new_range.end, &stored_range_start_wrapper.range.end).clone();
318             self.btm.remove(&stored_range_start_wrapper);
319         } else {
320             // The ranges have different values.
321             if new_range.overlaps(&stored_range_start_wrapper.range) {
322                 // The ranges overlap. This is a little bit more complicated.
323                 // Delete the stored range, and then add back between
324                 // 0 and 2 subranges at the ends of the range to insert.
325                 self.btm.remove(&stored_range_start_wrapper);
326                 if stored_range_start_wrapper.range.start < new_range.start {
327                     // Insert the piece left of the range to insert.
328                     self.btm.insert(
329                         RangeStartWrapper::new(
330                             stored_range_start_wrapper.range.start..new_range.start.clone(),
331                         ),
332                         stored_value.clone(),
333                     );
334                 }
335                 if stored_range_start_wrapper.range.end > new_range.end {
336                     // Insert the piece right of the range to insert.
337                     self.btm.insert(
338                         RangeStartWrapper::new(
339                             new_range.end.clone()..stored_range_start_wrapper.range.end,
340                         ),
341                         stored_value,
342                     );
343                 }
344             } else {
345                 // No-op; they're not overlapping,
346                 // so we can just keep both ranges as they are.
347             }
348         }
349     }
350 
adjust_overlapping_ranges_for_remove( &mut self, stored_range_start_wrapper: RangeStartWrapper<K>, stored_value: V, range_to_remove: &Range<K>, )351     fn adjust_overlapping_ranges_for_remove(
352         &mut self,
353         stored_range_start_wrapper: RangeStartWrapper<K>,
354         stored_value: V,
355         range_to_remove: &Range<K>,
356     ) {
357         // Delete the stored range, and then add back between
358         // 0 and 2 subranges at the ends of the range to insert.
359         self.btm.remove(&stored_range_start_wrapper);
360         let stored_range = stored_range_start_wrapper.range;
361 
362         if stored_range.start < range_to_remove.start {
363             // Insert the piece left of the range to insert.
364             self.btm.insert(
365                 RangeStartWrapper::new(stored_range.start..range_to_remove.start.clone()),
366                 stored_value.clone(),
367             );
368         }
369 
370         if stored_range.end > range_to_remove.end {
371             // Insert the piece right of the range to insert.
372             self.btm.insert(
373                 RangeStartWrapper::new(range_to_remove.end.clone()..stored_range.end),
374                 stored_value,
375             );
376         }
377     }
378 
379     /// Splits a range in two at the provided key.
380     ///
381     /// Does nothing if no range exists at the key, or if the key is at a range boundary.
split_at(&mut self, key: &K)382     pub fn split_at(&mut self, key: &K) {
383         // Find a range that contains the key, but doesn't start or end with the key.
384         let bounds = (
385             Bound::Unbounded,
386             Bound::Excluded(RangeStartWrapper::new(key.clone()..key.clone())),
387         );
388 
389         let range_to_remove = match self
390             .btm
391             .range(bounds)
392             .next_back()
393             .filter(|(range_start_wrapper, _value)| range_start_wrapper.range.contains(key))
394         {
395             Some((k, _v)) => k.clone(),
396             None => return,
397         };
398 
399         // Remove the range, and re-insert two new ranges with the same value, separated by the key.
400         let value = self.btm.remove(&range_to_remove).unwrap();
401         self.btm.insert(
402             RangeStartWrapper::new(range_to_remove.range.start..key.clone()),
403             value.clone(),
404         );
405         self.btm.insert(
406             RangeStartWrapper::new(key.clone()..range_to_remove.range.end),
407             value,
408         );
409     }
410 
411     /// Gets an iterator over all pairs of key range and value, where the key range overlaps with
412     /// the provided range.
413     ///
414     /// The iterator element type is `(&Range<K>, &V)`.
range(&self, range: &Range<K>) -> RangeIter<'_, K, V>415     pub fn range(&self, range: &Range<K>) -> RangeIter<'_, K, V> {
416         let start = self
417             .get_key_value(&range.start)
418             .map_or(&range.start, |(k, _v)| &k.start);
419         let end = &range.end;
420 
421         RangeIter {
422             inner: self.btm.range((
423                 Bound::Included(RangeStartWrapper::new(start.clone()..start.clone())),
424                 Bound::Excluded(RangeStartWrapper::new(end.clone()..end.clone())),
425             )),
426         }
427     }
428 
429     /// Gets a mutable iterator over all pairs of key range and value, where the key range overlaps
430     /// with the provided range.
431     ///
432     /// The iterator element type is `(&Range<K>, &mut V)`.
range_mut(&mut self, range: &Range<K>) -> RangeMutIter<'_, K, V>433     pub fn range_mut(&mut self, range: &Range<K>) -> RangeMutIter<'_, K, V> {
434         let start = self
435             .get_key_value(&range.start)
436             .map_or(&range.start, |(k, _v)| &k.start);
437         let end = &range.end;
438         let bounds = (
439             Bound::Included(RangeStartWrapper::new(start.clone()..start.clone())),
440             Bound::Excluded(RangeStartWrapper::new(end.clone()..end.clone())),
441         );
442 
443         RangeMutIter {
444             inner: self.btm.range_mut(bounds),
445         }
446     }
447 
448     /// Gets an iterator over all the maximally-sized ranges
449     /// contained in `outer_range` that are not covered by
450     /// any range stored in the map.
451     ///
452     /// The iterator element type is `Range<K>`.
453     ///
454     /// NOTE: Calling `gaps` eagerly finds the first gap,
455     /// even if the iterator is never consumed.
gaps<'a>(&'a self, outer_range: &'a Range<K>) -> Gaps<'a, K, V>456     pub fn gaps<'a>(&'a self, outer_range: &'a Range<K>) -> Gaps<'a, K, V> {
457         let mut keys = self.btm.keys().peekable();
458         // Find the first potential gap.
459         let mut candidate_start = &outer_range.start;
460 
461         while let Some(item) = keys.peek() {
462             if item.range.end <= outer_range.start {
463                 // This range sits entirely before the start of
464                 // the outer range; just skip it.
465                 let _ = keys.next();
466             } else if item.range.start <= outer_range.start {
467                 // This range overlaps the start of the
468                 // outer range, so the first possible candidate
469                 // range begins at its end.
470                 candidate_start = &item.range.end;
471                 let _ = keys.next();
472             } else {
473                 // The rest of the items might contribute to gaps.
474                 break;
475             }
476         }
477 
478         Gaps {
479             outer_range,
480             keys,
481             candidate_start,
482         }
483     }
484 }
485 
486 /// An iterator over the entries of a `RangeMap`, ordered by key range.
487 ///
488 /// The iterator element type is `(&'a Range<K>, &'a V)`.
489 ///
490 /// This `struct` is created by the [`iter`] method on [`RangeMap`]. See its
491 /// documentation for more.
492 ///
493 /// [`iter`]: RangeMap::iter
494 pub struct Iter<'a, K, V> {
495     inner: btree_map::Iter<'a, RangeStartWrapper<K>, V>,
496 }
497 
498 impl<'a, K, V> Iterator for Iter<'a, K, V>
499 where
500     K: 'a,
501     V: 'a,
502 {
503     type Item = (&'a Range<K>, &'a V);
504 
next(&mut self) -> Option<(&'a Range<K>, &'a V)>505     fn next(&mut self) -> Option<(&'a Range<K>, &'a V)> {
506         self.inner.next().map(|(by_start, v)| (&by_start.range, v))
507     }
508 
size_hint(&self) -> (usize, Option<usize>)509     fn size_hint(&self) -> (usize, Option<usize>) {
510         self.inner.size_hint()
511     }
512 }
513 
514 impl<'a, K, V> FusedIterator for Iter<'a, K, V> where K: Ord + Clone {}
515 impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> where K: Ord + Clone {}
516 
517 /// An iterator over the entries of a `RangeMap`, ordered by key range.
518 ///
519 /// The iterator element type is `(&'a Range<K>, &'a V)`.
520 ///
521 /// This `struct` is created by the [`iter`] method on [`RangeMap`]. See its
522 /// documentation for more.
523 ///
524 /// [`iter`]: RangeMap::iter
525 pub struct IterMut<'a, K, V> {
526     inner: btree_map::IterMut<'a, RangeStartWrapper<K>, V>,
527 }
528 
529 impl<'a, K, V> Iterator for IterMut<'a, K, V>
530 where
531     K: 'a,
532     V: 'a,
533 {
534     type Item = (&'a Range<K>, &'a mut V);
535 
next(&mut self) -> Option<(&'a Range<K>, &'a mut V)>536     fn next(&mut self) -> Option<(&'a Range<K>, &'a mut V)> {
537         self.inner.next().map(|(by_start, v)| (&by_start.range, v))
538     }
539 
size_hint(&self) -> (usize, Option<usize>)540     fn size_hint(&self) -> (usize, Option<usize>) {
541         self.inner.size_hint()
542     }
543 }
544 
545 impl<'a, K, V> FusedIterator for IterMut<'a, K, V> where K: Ord + Clone {}
546 impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> where K: Ord + Clone {}
547 
548 /// An owning iterator over the entries of a `RangeMap`, ordered by key range.
549 ///
550 /// The iterator element type is `(Range<K>, V)`.
551 ///
552 /// This `struct` is created by the [`into_iter`] method on [`RangeMap`]
553 /// (provided by the `IntoIterator` trait). See its documentation for more.
554 ///
555 /// [`into_iter`]: IntoIterator::into_iter
556 pub struct IntoIter<K, V> {
557     inner: btree_map::IntoIter<RangeStartWrapper<K>, V>,
558 }
559 
560 impl<K, V> IntoIterator for RangeMap<K, V> {
561     type Item = (Range<K>, V);
562     type IntoIter = IntoIter<K, V>;
563 
into_iter(self) -> Self::IntoIter564     fn into_iter(self) -> Self::IntoIter {
565         IntoIter {
566             inner: self.btm.into_iter(),
567         }
568     }
569 }
570 
571 impl<K, V> Iterator for IntoIter<K, V> {
572     type Item = (Range<K>, V);
573 
next(&mut self) -> Option<(Range<K>, V)>574     fn next(&mut self) -> Option<(Range<K>, V)> {
575         self.inner.next().map(|(by_start, v)| (by_start.range, v))
576     }
577 
size_hint(&self) -> (usize, Option<usize>)578     fn size_hint(&self) -> (usize, Option<usize>) {
579         self.inner.size_hint()
580     }
581 }
582 
583 impl<K, V> FusedIterator for IntoIter<K, V> where K: Ord + Clone {}
584 impl<K, V> ExactSizeIterator for IntoIter<K, V> where K: Ord + Clone {}
585 
586 // We can't just derive this automatically, because that would
587 // expose irrelevant (and private) implementation details.
588 // Instead implement it in the same way that the underlying BTreeMap does.
589 impl<K: Debug, V: Debug> Debug for RangeMap<K, V>
590 where
591     K: Ord + Clone,
592     V: Eq + Clone,
593 {
fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError>594     fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
595         f.debug_map().entries(self.iter()).finish()
596     }
597 }
598 
599 impl<K, V> FromIterator<(Range<K>, V)> for RangeMap<K, V>
600 where
601     K: Ord + Clone,
602     V: Eq + Clone,
603 {
from_iter<T: IntoIterator<Item = (Range<K>, V)>>(iter: T) -> Self604     fn from_iter<T: IntoIterator<Item = (Range<K>, V)>>(iter: T) -> Self {
605         let mut range_map = RangeMap::new();
606         range_map.extend(iter);
607         range_map
608     }
609 }
610 
611 impl<K, V> Extend<(Range<K>, V)> for RangeMap<K, V>
612 where
613     K: Ord + Clone,
614     V: Eq + Clone,
615 {
extend<T: IntoIterator<Item = (Range<K>, V)>>(&mut self, iter: T)616     fn extend<T: IntoIterator<Item = (Range<K>, V)>>(&mut self, iter: T) {
617         iter.into_iter().for_each(move |(k, v)| {
618             self.insert(k, v);
619         })
620     }
621 }
622 
623 /// An iterator over entries of a `RangeMap` whose range overlaps with a specified range.
624 ///
625 /// The iterator element type is `(&'a Range<K>, &'a V)`.
626 ///
627 /// This `struct` is created by the [`range`] method on [`RangeMap`]. See its
628 /// documentation for more.
629 ///
630 /// [`range`]: RangeMap::range
631 pub struct RangeIter<'a, K, V> {
632     inner: btree_map::Range<'a, RangeStartWrapper<K>, V>,
633 }
634 
635 impl<'a, K, V> FusedIterator for RangeIter<'a, K, V> where K: Ord + Clone {}
636 
637 impl<'a, K, V> Iterator for RangeIter<'a, K, V>
638 where
639     K: 'a,
640     V: 'a,
641 {
642     type Item = (&'a Range<K>, &'a V);
643 
next(&mut self) -> Option<Self::Item>644     fn next(&mut self) -> Option<Self::Item> {
645         self.inner.next().map(|(by_start, v)| (&by_start.range, v))
646     }
647 
size_hint(&self) -> (usize, Option<usize>)648     fn size_hint(&self) -> (usize, Option<usize>) {
649         self.inner.size_hint()
650     }
651 }
652 
653 /// A mutable iterator over entries of a `RangeMap` whose range overlaps with a specified range.
654 ///
655 /// The iterator element type is `(&'a Range<K>, &'a mut V)`.
656 ///
657 /// This `struct` is created by the [`range_mut`] method on [`RangeMap`]. See its
658 /// documentation for more.
659 ///
660 /// [`range_mut`]: RangeMap::range_mut
661 pub struct RangeMutIter<'a, K, V> {
662     inner: btree_map::RangeMut<'a, RangeStartWrapper<K>, V>,
663 }
664 
665 impl<'a, K, V> FusedIterator for RangeMutIter<'a, K, V> where K: Ord + Clone {}
666 
667 impl<'a, K, V> Iterator for RangeMutIter<'a, K, V>
668 where
669     K: 'a,
670     V: 'a,
671 {
672     type Item = (&'a Range<K>, &'a mut V);
673 
next(&mut self) -> Option<Self::Item>674     fn next(&mut self) -> Option<Self::Item> {
675         self.inner.next().map(|(by_start, v)| (&by_start.range, v))
676     }
677 
size_hint(&self) -> (usize, Option<usize>)678     fn size_hint(&self) -> (usize, Option<usize>) {
679         self.inner.size_hint()
680     }
681 }
682 
683 /// An iterator over all ranges not covered by a `RangeMap`.
684 ///
685 /// The iterator element type is `Range<K>`.
686 ///
687 /// This `struct` is created by the [`gaps`] method on [`RangeMap`]. See its
688 /// documentation for more.
689 ///
690 /// [`gaps`]: RangeMap::gaps
691 pub struct Gaps<'a, K, V> {
692     outer_range: &'a Range<K>,
693     keys: Peekable<btree_map::Keys<'a, RangeStartWrapper<K>, V>>,
694     candidate_start: &'a K,
695 }
696 
697 // `Gaps` is always fused. (See definition of `next` below.)
698 impl<'a, K, V> FusedIterator for Gaps<'a, K, V> where K: Ord + Clone {}
699 
700 impl<'a, K, V> Iterator for Gaps<'a, K, V>
701 where
702     K: Ord + Clone,
703 {
704     type Item = Range<K>;
705 
next(&mut self) -> Option<Self::Item>706     fn next(&mut self) -> Option<Self::Item> {
707         if *self.candidate_start >= self.outer_range.end {
708             // We've already passed the end of the outer range;
709             // there are no more gaps to find.
710             return None;
711         }
712 
713         // Figure out where this gap ends.
714         let (gap_end, mut next_candidate_start) = if let Some(next_item) = self.keys.next() {
715             if next_item.range.start < self.outer_range.end {
716                 // The gap goes up until the start of the next item,
717                 // and the next candidate starts after it.
718                 (&next_item.range.start, &next_item.range.end)
719             } else {
720                 // The item sits after the end of the outer range,
721                 // so this gap ends at the end of the outer range.
722                 // This also means there will be no more gaps.
723                 (&self.outer_range.end, &self.outer_range.end)
724             }
725         } else {
726             // There's no next item; the end is at the
727             // end of the outer range.
728             // This also means there will be no more gaps.
729             (&self.outer_range.end, &self.outer_range.end)
730         };
731 
732         // Find the start of the next gap.
733         while let Some(next_item) = self.keys.peek() {
734             if next_item.range.start == *next_candidate_start {
735                 // There's another item at the start of our candidate range.
736                 // Gaps can't have zero width, so skip to the end of this
737                 // item and try again.
738                 next_candidate_start = &next_item.range.end;
739                 self.keys.next().expect("We just checked that this exists");
740             } else {
741                 // We found an item that actually has a gap before it.
742                 break;
743             }
744         }
745 
746         // Move the next candidate gap start past the end
747         // of this gap, and yield the gap we found.
748         let gap = self.candidate_start.clone()..gap_end.clone();
749         self.candidate_start = next_candidate_start;
750         Some(gap)
751     }
752 }
753 
754 // Wrappers to allow storing (and sorting/searching)
755 // ranges as the keys of a `BTreeMap`.
756 //
757 // We can do this because we maintain the invariants
758 // that the order of range starts is the same as the order
759 // of range ends, and that no two stored ranges have the
760 // same start or end as each other.
761 //
762 // NOTE: Be very careful not to accidentally use these
763 // if you really do want to compare equality of the
764 // inner range!
765 
766 //
767 // Range start wrapper
768 //
769 
770 #[derive(Eq, Debug, Clone)]
771 pub struct RangeStartWrapper<T> {
772     pub range: Range<T>,
773 }
774 
775 impl<T> RangeStartWrapper<T> {
776     #[inline]
new(range: Range<T>) -> RangeStartWrapper<T>777     pub fn new(range: Range<T>) -> RangeStartWrapper<T> {
778         RangeStartWrapper { range }
779     }
780 }
781 
782 impl<T> PartialEq for RangeStartWrapper<T>
783 where
784     T: Eq,
785 {
eq(&self, other: &RangeStartWrapper<T>) -> bool786     fn eq(&self, other: &RangeStartWrapper<T>) -> bool {
787         self.range.start == other.range.start
788     }
789 }
790 
791 impl<T> Ord for RangeStartWrapper<T>
792 where
793     T: Ord,
794 {
cmp(&self, other: &RangeStartWrapper<T>) -> Ordering795     fn cmp(&self, other: &RangeStartWrapper<T>) -> Ordering {
796         self.range.start.cmp(&other.range.start)
797     }
798 }
799 
800 impl<T> PartialOrd for RangeStartWrapper<T>
801 where
802     T: Ord,
803 {
partial_cmp(&self, other: &RangeStartWrapper<T>) -> Option<Ordering>804     fn partial_cmp(&self, other: &RangeStartWrapper<T>) -> Option<Ordering> {
805         Some(self.cmp(other))
806     }
807 }
808 
809 pub trait RangeExt<T> {
overlaps(&self, other: &Self) -> bool810     fn overlaps(&self, other: &Self) -> bool;
touches(&self, other: &Self) -> bool811     fn touches(&self, other: &Self) -> bool;
812 }
813 
814 impl<T> RangeExt<T> for Range<T>
815 where
816     T: Ord,
817 {
overlaps(&self, other: &Self) -> bool818     fn overlaps(&self, other: &Self) -> bool {
819         // Strictly less than, because ends are excluded.
820         cmp::max(&self.start, &other.start) < cmp::min(&self.end, &other.end)
821     }
822 
touches(&self, other: &Self) -> bool823     fn touches(&self, other: &Self) -> bool {
824         // Less-than-or-equal-to because if one end is excluded, the other is included.
825         // I.e. the two could be joined into a single range, because they're overlapping
826         // or immediately adjacent.
827         cmp::max(&self.start, &other.start) <= cmp::min(&self.end, &other.end)
828     }
829 }
830 
831 /// Minimal version of unstable [`Step`](std::iter::Step) trait
832 /// from the Rust standard library.
833 ///
834 /// This is needed for [`RangeInclusiveMap`](crate::RangeInclusiveMap)
835 /// because ranges stored as its keys interact with each other
836 /// when the start of one is _adjacent_ the end of another.
837 /// I.e. we need a concept of successor values rather than just
838 /// equality, and that is what `Step` will
839 /// eventually provide once it is stabilized.
840 ///
841 /// **NOTE:** This will likely be deprecated and then eventually
842 /// removed once the standard library's `Step`
843 /// trait is stabilised, as most crates will then likely implement `Step`
844 /// for their types where appropriate.
845 ///
846 /// See [this issue](https://github.com/rust-lang/rust/issues/42168)
847 /// for details about that stabilization process.
848 pub trait StepLite {
849     /// Returns the _successor_ of `self`.
850     ///
851     /// If this would overflow the range of values supported by `Self`,
852     /// this function is allowed to panic, wrap, or saturate.
853     /// The suggested behavior is to panic when debug assertions are enabled,
854     /// and to wrap or saturate otherwise.
add_one(&self) -> Self855     fn add_one(&self) -> Self;
856 
857     /// Returns the _predecessor_ of `self`.
858     ///
859     /// If this would overflow the range of values supported by `Self`,
860     /// this function is allowed to panic, wrap, or saturate.
861     /// The suggested behavior is to panic when debug assertions are enabled,
862     /// and to wrap or saturate otherwise.
sub_one(&self) -> Self863     fn sub_one(&self) -> Self;
864 }
865 
866 // Implement for all common integer types.
867 macro_rules! impl_step_lite {
868     ($($t:ty)*) => ($(
869         impl StepLite for $t {
870             #[inline]
871             fn add_one(&self) -> Self {
872                 Add::add(*self, 1)
873             }
874 
875             #[inline]
876             fn sub_one(&self) -> Self {
877                 Sub::sub(*self, 1)
878             }
879         }
880     )*)
881 }
882 
883 impl_step_lite!(usize u8 u16 u32 u64 u128 i8 i16 i32 i64 i128);
884 
885 // TODO: When on nightly, a blanket implementation for
886 // all types that implement `std::iter::Step` instead
887 // of the auto-impl above.
888 
889 /// Successor and predecessor functions defined for `T`,
890 /// but as free functions rather than methods on `T` itself.
891 ///
892 /// This is useful as a workaround for Rust's "orphan rules",
893 /// which prevent you from implementing [`StepLite`](crate::StepLite) for `T` if `T`
894 /// is a foreign type.
895 ///
896 /// **NOTE:** This will likely be deprecated and then eventually
897 /// removed once the standard library's [`Step`](std::iter::Step)
898 /// trait is stabilised, as most crates will then likely implement `Step`
899 /// for their types where appropriate.
900 ///
901 /// See [this issue](https://github.com/rust-lang/rust/issues/42168)
902 /// for details about that stabilization process.
903 ///
904 /// There is also a blanket implementation of `StepFns` for all
905 /// types implementing `StepLite`. Consumers of this crate should
906 /// prefer to implement `StepLite` for their own types, and only
907 /// fall back to `StepFns` when dealing with foreign types.
908 pub trait StepFns<T> {
909     /// Returns the _successor_ of value `start`.
910     ///
911     /// If this would overflow the range of values supported by `Self`,
912     /// this function is allowed to panic, wrap, or saturate.
913     /// The suggested behavior is to panic when debug assertions are enabled,
914     /// and to wrap or saturate otherwise.
add_one(start: &T) -> T915     fn add_one(start: &T) -> T;
916 
917     /// Returns the _predecessor_ of value `start`.
918     ///
919     /// If this would overflow the range of values supported by `Self`,
920     /// this function is allowed to panic, wrap, or saturate.
921     /// The suggested behavior is to panic when debug assertions are enabled,
922     /// and to wrap or saturate otherwise.
sub_one(start: &T) -> T923     fn sub_one(start: &T) -> T;
924 }
925 
926 impl<T> StepFns<T> for T
927 where
928     T: StepLite,
929 {
add_one(start: &T) -> T930     fn add_one(start: &T) -> T {
931         start.add_one()
932     }
933 
sub_one(start: &T) -> T934     fn sub_one(start: &T) -> T {
935         start.sub_one()
936     }
937 }
938 
939 #[cfg(test)]
940 mod tests {
941     use super::*;
942     use std::{format, vec, vec::Vec};
943 
944     trait RangeMapExt<K, V> {
to_vec(&self) -> Vec<(Range<K>, V)>945         fn to_vec(&self) -> Vec<(Range<K>, V)>;
946     }
947 
948     impl<K, V> RangeMapExt<K, V> for RangeMap<K, V>
949     where
950         K: Ord + Clone,
951         V: Eq + Clone,
952     {
to_vec(&self) -> Vec<(Range<K>, V)>953         fn to_vec(&self) -> Vec<(Range<K>, V)> {
954             self.iter().map(|(kr, v)| (kr.clone(), v.clone())).collect()
955         }
956     }
957 
958     //
959     // Insertion tests
960     //
961 
962     #[test]
empty_map_is_empty()963     fn empty_map_is_empty() {
964         let range_map: RangeMap<u32, bool> = RangeMap::new();
965         assert_eq!(range_map.to_vec(), vec![]);
966     }
967 
968     #[test]
insert_into_empty_map()969     fn insert_into_empty_map() {
970         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
971         range_map.insert(0..50, false);
972         assert_eq!(range_map.to_vec(), vec![(0..50, false)]);
973     }
974 
975     #[test]
new_same_value_immediately_following_stored()976     fn new_same_value_immediately_following_stored() {
977         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
978         // 0 1 2 3 4 5 6 7 8 9
979         // ◌ ●---◌ ◌ ◌ ◌ ◌ ◌ ◌
980         range_map.insert(1..3, false);
981         // 0 1 2 3 4 5 6 7 8 9
982         // ◌ ◌ ◌ ●---◌ ◌ ◌ ◌ ◌
983         range_map.insert(3..5, false);
984         // 0 1 2 3 4 5 6 7 8 9
985         // ◌ ●-------◌ ◌ ◌ ◌ ◌
986         assert_eq!(range_map.to_vec(), vec![(1..5, false)]);
987     }
988 
989     #[test]
new_different_value_immediately_following_stored()990     fn new_different_value_immediately_following_stored() {
991         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
992         // 0 1 2 3 4 5 6 7 8 9
993         // ◌ ●---◌ ◌ ◌ ◌ ◌ ◌ ◌
994         range_map.insert(1..3, false);
995         // 0 1 2 3 4 5 6 7 8 9
996         // ◌ ◌ ◌ ◆---◇ ◌ ◌ ◌ ◌
997         range_map.insert(3..5, true);
998         // 0 1 2 3 4 5 6 7 8 9
999         // ◌ ●---◌ ◌ ◌ ◌ ◌ ◌ ◌
1000         // ◌ ◌ ◌ ◆---◇ ◌ ◌ ◌ ◌
1001         assert_eq!(range_map.to_vec(), vec![(1..3, false), (3..5, true)]);
1002     }
1003 
1004     #[test]
new_same_value_overlapping_end_of_stored()1005     fn new_same_value_overlapping_end_of_stored() {
1006         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
1007         // 0 1 2 3 4 5 6 7 8 9
1008         // ◌ ●-----◌ ◌ ◌ ◌ ◌ ◌
1009         range_map.insert(1..4, false);
1010         // 0 1 2 3 4 5 6 7 8 9
1011         // ◌ ◌ ◌ ●---◌ ◌ ◌ ◌ ◌
1012         range_map.insert(3..5, false);
1013         // 0 1 2 3 4 5 6 7 8 9
1014         // ◌ ●-------◌ ◌ ◌ ◌ ◌
1015         assert_eq!(range_map.to_vec(), vec![(1..5, false)]);
1016     }
1017 
1018     #[test]
new_different_value_overlapping_end_of_stored()1019     fn new_different_value_overlapping_end_of_stored() {
1020         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
1021         // 0 1 2 3 4 5 6 7 8 9
1022         // ◌ ●-----◌ ◌ ◌ ◌ ◌ ◌
1023         range_map.insert(1..4, false);
1024         // 0 1 2 3 4 5 6 7 8 9
1025         // ◌ ◌ ◌ ◆---◇ ◌ ◌ ◌ ◌
1026         range_map.insert(3..5, true);
1027         // 0 1 2 3 4 5 6 7 8 9
1028         // ◌ ●---◌ ◌ ◌ ◌ ◌ ◌ ◌
1029         // ◌ ◌ ◌ ◆---◇ ◌ ◌ ◌ ◌
1030         assert_eq!(range_map.to_vec(), vec![(1..3, false), (3..5, true)]);
1031     }
1032 
1033     #[test]
new_same_value_immediately_preceding_stored()1034     fn new_same_value_immediately_preceding_stored() {
1035         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
1036         // 0 1 2 3 4 5 6 7 8 9
1037         // ◌ ◌ ◌ ●---◌ ◌ ◌ ◌ ◌
1038         range_map.insert(3..5, false);
1039         // 0 1 2 3 4 5 6 7 8 9
1040         // ◌ ●---◌ ◌ ◌ ◌ ◌ ◌ ◌
1041         range_map.insert(1..3, false);
1042         // 0 1 2 3 4 5 6 7 8 9
1043         // ◌ ●-------◌ ◌ ◌ ◌ ◌
1044         assert_eq!(range_map.to_vec(), vec![(1..5, false)]);
1045     }
1046 
1047     #[test]
new_different_value_immediately_preceding_stored()1048     fn new_different_value_immediately_preceding_stored() {
1049         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
1050         // 0 1 2 3 4 5 6 7 8 9
1051         // ◌ ◌ ◌ ◆---◇ ◌ ◌ ◌ ◌
1052         range_map.insert(3..5, true);
1053         // 0 1 2 3 4 5 6 7 8 9
1054         // ◌ ●---◌ ◌ ◌ ◌ ◌ ◌ ◌
1055         range_map.insert(1..3, false);
1056         // 0 1 2 3 4 5 6 7 8 9
1057         // ◌ ●---◌ ◌ ◌ ◌ ◌ ◌ ◌
1058         // ◌ ◌ ◌ ◆---◇ ◌ ◌ ◌ ◌
1059         assert_eq!(range_map.to_vec(), vec![(1..3, false), (3..5, true)]);
1060     }
1061 
1062     #[test]
new_same_value_wholly_inside_stored()1063     fn new_same_value_wholly_inside_stored() {
1064         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
1065         // 0 1 2 3 4 5 6 7 8 9
1066         // ◌ ●-------◌ ◌ ◌ ◌ ◌
1067         range_map.insert(1..5, false);
1068         // 0 1 2 3 4 5 6 7 8 9
1069         // ◌ ◌ ●---◌ ◌ ◌ ◌ ◌ ◌ ◌
1070         range_map.insert(2..4, false);
1071         // 0 1 2 3 4 5 6 7 8 9
1072         // ◌ ●-------◌ ◌ ◌ ◌ ◌
1073         assert_eq!(range_map.to_vec(), vec![(1..5, false)]);
1074     }
1075 
1076     #[test]
new_different_value_wholly_inside_stored()1077     fn new_different_value_wholly_inside_stored() {
1078         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
1079         // 0 1 2 3 4 5 6 7 8 9
1080         // ◌ ◆-------◇ ◌ ◌ ◌ ◌
1081         range_map.insert(1..5, true);
1082         // 0 1 2 3 4 5 6 7 8 9
1083         // ◌ ◌ ●---◌ ◌ ◌ ◌ ◌ ◌ ◌
1084         range_map.insert(2..4, false);
1085         // 0 1 2 3 4 5 6 7 8 9
1086         // ◌ ●-◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌
1087         // ◌ ◌ ◆---◇ ◌ ◌ ◌ ◌ ◌
1088         // ◌ ◌ ◌ ◌ ●-◌ ◌ ◌ ◌ ◌
1089         assert_eq!(
1090             range_map.to_vec(),
1091             vec![(1..2, true), (2..4, false), (4..5, true)]
1092         );
1093     }
1094 
1095     #[test]
replace_at_end_of_existing_range_should_coalesce()1096     fn replace_at_end_of_existing_range_should_coalesce() {
1097         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
1098         // 0 1 2 3 4 5 6 7 8 9
1099         // ◌ ●---◌ ◌ ◌ ◌ ◌ ◌ ◌
1100         range_map.insert(1..3, false);
1101         // 0 1 2 3 4 5 6 7 8 9
1102         // ◌ ◌ ◌ ●---◌ ◌ ◌ ◌ ◌
1103         range_map.insert(3..5, true);
1104         // 0 1 2 3 4 5 6 7 8 9
1105         // ◌ ◌ ◌ ●---◌ ◌ ◌ ◌ ◌
1106         range_map.insert(3..5, false);
1107         // 0 1 2 3 4 5 6 7 8 9
1108         // ◌ ●-------◌ ◌ ◌ ◌ ◌
1109         assert_eq!(range_map.to_vec(), vec![(1..5, false)]);
1110     }
1111 
1112     //
1113     // Get* tests
1114     //
1115 
1116     #[test]
get()1117     fn get() {
1118         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
1119         range_map.insert(0..50, false);
1120         assert_eq!(range_map.get(&49), Some(&false));
1121         assert_eq!(range_map.get(&50), None);
1122     }
1123 
1124     #[test]
get_key_value()1125     fn get_key_value() {
1126         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
1127         range_map.insert(0..50, false);
1128         assert_eq!(range_map.get_key_value(&49), Some((&(0..50), &false)));
1129         assert_eq!(range_map.get_key_value(&50), None);
1130     }
1131 
1132     //
1133     // Removal tests
1134     //
1135 
1136     #[test]
remove_from_empty_map()1137     fn remove_from_empty_map() {
1138         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
1139         range_map.remove(0..50);
1140         assert_eq!(range_map.to_vec(), vec![]);
1141     }
1142 
1143     #[test]
remove_non_covered_range_before_stored()1144     fn remove_non_covered_range_before_stored() {
1145         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
1146         range_map.insert(25..75, false);
1147         range_map.remove(0..25);
1148         assert_eq!(range_map.to_vec(), vec![(25..75, false)]);
1149     }
1150 
1151     #[test]
remove_non_covered_range_after_stored()1152     fn remove_non_covered_range_after_stored() {
1153         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
1154         range_map.insert(25..75, false);
1155         range_map.remove(75..100);
1156         assert_eq!(range_map.to_vec(), vec![(25..75, false)]);
1157     }
1158 
1159     #[test]
remove_overlapping_start_of_stored()1160     fn remove_overlapping_start_of_stored() {
1161         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
1162         range_map.insert(25..75, false);
1163         range_map.remove(0..30);
1164         assert_eq!(range_map.to_vec(), vec![(30..75, false)]);
1165     }
1166 
1167     #[test]
remove_middle_of_stored()1168     fn remove_middle_of_stored() {
1169         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
1170         range_map.insert(25..75, false);
1171         range_map.remove(30..70);
1172         assert_eq!(range_map.to_vec(), vec![(25..30, false), (70..75, false)]);
1173     }
1174 
1175     #[test]
remove_overlapping_end_of_stored()1176     fn remove_overlapping_end_of_stored() {
1177         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
1178         range_map.insert(25..75, false);
1179         range_map.remove(70..100);
1180         assert_eq!(range_map.to_vec(), vec![(25..70, false)]);
1181     }
1182 
1183     #[test]
remove_exactly_stored()1184     fn remove_exactly_stored() {
1185         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
1186         range_map.insert(25..75, false);
1187         range_map.remove(25..75);
1188         assert_eq!(range_map.to_vec(), vec![]);
1189     }
1190 
1191     #[test]
remove_superset_of_stored()1192     fn remove_superset_of_stored() {
1193         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
1194         range_map.insert(25..75, false);
1195         range_map.remove(0..100);
1196         assert_eq!(range_map.to_vec(), vec![]);
1197     }
1198 
1199     // Gaps tests
1200 
1201     #[test]
whole_range_is_a_gap()1202     fn whole_range_is_a_gap() {
1203         // 0 1 2 3 4 5 6 7 8 9
1204         // ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌
1205         let range_map: RangeMap<u32, ()> = RangeMap::new();
1206         // 0 1 2 3 4 5 6 7 8 9
1207         // ◌ ◆-------------◇ ◌
1208         let outer_range = 1..8;
1209         let mut gaps = range_map.gaps(&outer_range);
1210         // Should yield the entire outer range.
1211         assert_eq!(gaps.next(), Some(1..8));
1212         assert_eq!(gaps.next(), None);
1213         // Gaps iterator should be fused.
1214         assert_eq!(gaps.next(), None);
1215         assert_eq!(gaps.next(), None);
1216     }
1217 
1218     #[test]
whole_range_is_covered_exactly()1219     fn whole_range_is_covered_exactly() {
1220         let mut range_map: RangeMap<u32, ()> = RangeMap::new();
1221         // 0 1 2 3 4 5 6 7 8 9
1222         // ◌ ●---------◌ ◌ ◌ ◌
1223         range_map.insert(1..6, ());
1224         // 0 1 2 3 4 5 6 7 8 9
1225         // ◌ ◆---------◇ ◌ ◌ ◌
1226         let outer_range = 1..6;
1227         let mut gaps = range_map.gaps(&outer_range);
1228         // Should yield no gaps.
1229         assert_eq!(gaps.next(), None);
1230         // Gaps iterator should be fused.
1231         assert_eq!(gaps.next(), None);
1232         assert_eq!(gaps.next(), None);
1233     }
1234 
1235     #[test]
item_before_outer_range()1236     fn item_before_outer_range() {
1237         let mut range_map: RangeMap<u32, ()> = RangeMap::new();
1238         // 0 1 2 3 4 5 6 7 8 9
1239         // ◌ ●---◌ ◌ ◌ ◌ ◌ ◌ ◌
1240         range_map.insert(1..3, ());
1241         // 0 1 2 3 4 5 6 7 8 9
1242         // ◌ ◌ ◌ ◌ ◌ ◆-----◇ ◌
1243         let outer_range = 5..8;
1244         let mut gaps = range_map.gaps(&outer_range);
1245         // Should yield the entire outer range.
1246         assert_eq!(gaps.next(), Some(5..8));
1247         assert_eq!(gaps.next(), None);
1248         // Gaps iterator should be fused.
1249         assert_eq!(gaps.next(), None);
1250         assert_eq!(gaps.next(), None);
1251     }
1252 
1253     #[test]
item_touching_start_of_outer_range()1254     fn item_touching_start_of_outer_range() {
1255         let mut range_map: RangeMap<u32, ()> = RangeMap::new();
1256         // 0 1 2 3 4 5 6 7 8 9
1257         // ◌ ●-------◌ ◌ ◌ ◌ ◌
1258         range_map.insert(1..5, ());
1259         // 0 1 2 3 4 5 6 7 8 9
1260         // ◌ ◌ ◌ ◌ ◌ ◆-----◇ ◌
1261         let outer_range = 5..8;
1262         let mut gaps = range_map.gaps(&outer_range);
1263         // Should yield the entire outer range.
1264         assert_eq!(gaps.next(), Some(5..8));
1265         assert_eq!(gaps.next(), None);
1266         // Gaps iterator should be fused.
1267         assert_eq!(gaps.next(), None);
1268         assert_eq!(gaps.next(), None);
1269     }
1270 
1271     #[test]
item_overlapping_start_of_outer_range()1272     fn item_overlapping_start_of_outer_range() {
1273         let mut range_map: RangeMap<u32, ()> = RangeMap::new();
1274         // 0 1 2 3 4 5 6 7 8 9
1275         // ◌ ●---------◌ ◌ ◌ ◌
1276         range_map.insert(1..6, ());
1277         // 0 1 2 3 4 5 6 7 8 9
1278         // ◌ ◌ ◌ ◌ ◌ ◆-----◇ ◌
1279         let outer_range = 5..8;
1280         let mut gaps = range_map.gaps(&outer_range);
1281         // Should yield from the end of the stored item
1282         // to the end of the outer range.
1283         assert_eq!(gaps.next(), Some(6..8));
1284         assert_eq!(gaps.next(), None);
1285         // Gaps iterator should be fused.
1286         assert_eq!(gaps.next(), None);
1287         assert_eq!(gaps.next(), None);
1288     }
1289 
1290     #[test]
item_starting_at_start_of_outer_range()1291     fn item_starting_at_start_of_outer_range() {
1292         let mut range_map: RangeMap<u32, ()> = RangeMap::new();
1293         // 0 1 2 3 4 5 6 7 8 9
1294         // ◌ ◌ ◌ ◌ ◌ ●-◌ ◌ ◌ ◌
1295         range_map.insert(5..6, ());
1296         // 0 1 2 3 4 5 6 7 8 9
1297         // ◌ ◌ ◌ ◌ ◌ ◆-----◇ ◌
1298         let outer_range = 5..8;
1299         let mut gaps = range_map.gaps(&outer_range);
1300         // Should yield from the item onwards.
1301         assert_eq!(gaps.next(), Some(6..8));
1302         assert_eq!(gaps.next(), None);
1303         // Gaps iterator should be fused.
1304         assert_eq!(gaps.next(), None);
1305         assert_eq!(gaps.next(), None);
1306     }
1307 
1308     #[test]
items_floating_inside_outer_range()1309     fn items_floating_inside_outer_range() {
1310         let mut range_map: RangeMap<u32, ()> = RangeMap::new();
1311         // 0 1 2 3 4 5 6 7 8 9
1312         // ◌ ◌ ◌ ◌ ◌ ●-◌ ◌ ◌ ◌
1313         range_map.insert(5..6, ());
1314         // 0 1 2 3 4 5 6 7 8 9
1315         // ◌ ◌ ◌ ●-◌ ◌ ◌ ◌ ◌ ◌
1316         range_map.insert(3..4, ());
1317         // 0 1 2 3 4 5 6 7 8 9
1318         // ◌ ◆-------------◇ ◌
1319         let outer_range = 1..8;
1320         let mut gaps = range_map.gaps(&outer_range);
1321         // Should yield gaps at start, between items,
1322         // and at end.
1323         assert_eq!(gaps.next(), Some(1..3));
1324         assert_eq!(gaps.next(), Some(4..5));
1325         assert_eq!(gaps.next(), Some(6..8));
1326         assert_eq!(gaps.next(), None);
1327         // Gaps iterator should be fused.
1328         assert_eq!(gaps.next(), None);
1329         assert_eq!(gaps.next(), None);
1330     }
1331 
1332     #[test]
item_ending_at_end_of_outer_range()1333     fn item_ending_at_end_of_outer_range() {
1334         let mut range_map: RangeMap<u32, ()> = RangeMap::new();
1335         // 0 1 2 3 4 5 6 7 8 9
1336         // ◌ ◌ ◌ ◌ ◌ ◌ ◌ ●-◌ ◌
1337         range_map.insert(7..8, ());
1338         // 0 1 2 3 4 5 6 7 8 9
1339         // ◌ ◌ ◌ ◌ ◌ ◆-----◇ ◌
1340         let outer_range = 5..8;
1341         let mut gaps = range_map.gaps(&outer_range);
1342         // Should yield from the start of the outer range
1343         // up to the start of the stored item.
1344         assert_eq!(gaps.next(), Some(5..7));
1345         assert_eq!(gaps.next(), None);
1346         // Gaps iterator should be fused.
1347         assert_eq!(gaps.next(), None);
1348         assert_eq!(gaps.next(), None);
1349     }
1350 
1351     #[test]
item_overlapping_end_of_outer_range()1352     fn item_overlapping_end_of_outer_range() {
1353         let mut range_map: RangeMap<u32, ()> = RangeMap::new();
1354         // 0 1 2 3 4 5 6 7 8 9
1355         // ◌ ◌ ◌ ◌ ●---◌ ◌ ◌ ◌
1356         range_map.insert(4..6, ());
1357         // 0 1 2 3 4 5 6 7 8 9
1358         // ◌ ◌ ◆-----◇ ◌ ◌ ◌ ◌
1359         let outer_range = 2..5;
1360         let mut gaps = range_map.gaps(&outer_range);
1361         // Should yield from the start of the outer range
1362         // up to the start of the stored item.
1363         assert_eq!(gaps.next(), Some(2..4));
1364         assert_eq!(gaps.next(), None);
1365         // Gaps iterator should be fused.
1366         assert_eq!(gaps.next(), None);
1367         assert_eq!(gaps.next(), None);
1368     }
1369 
1370     #[test]
item_touching_end_of_outer_range()1371     fn item_touching_end_of_outer_range() {
1372         let mut range_map: RangeMap<u32, ()> = RangeMap::new();
1373         // 0 1 2 3 4 5 6 7 8 9
1374         // ◌ ◌ ◌ ◌ ●-------◌ ◌
1375         range_map.insert(4..8, ());
1376         // 0 1 2 3 4 5 6 7 8 9
1377         // ◌ ◆-----◇ ◌ ◌ ◌ ◌ ◌
1378         let outer_range = 1..4;
1379         let mut gaps = range_map.gaps(&outer_range);
1380         // Should yield the entire outer range.
1381         assert_eq!(gaps.next(), Some(1..4));
1382         assert_eq!(gaps.next(), None);
1383         // Gaps iterator should be fused.
1384         assert_eq!(gaps.next(), None);
1385         assert_eq!(gaps.next(), None);
1386     }
1387 
1388     #[test]
item_after_outer_range()1389     fn item_after_outer_range() {
1390         let mut range_map: RangeMap<u32, ()> = RangeMap::new();
1391         // 0 1 2 3 4 5 6 7 8 9
1392         // ◌ ◌ ◌ ◌ ◌ ◌ ●---◌ ◌
1393         range_map.insert(6..7, ());
1394         // 0 1 2 3 4 5 6 7 8 9
1395         // ◌ ◆-----◇ ◌ ◌ ◌ ◌ ◌
1396         let outer_range = 1..4;
1397         let mut gaps = range_map.gaps(&outer_range);
1398         // Should yield the entire outer range.
1399         assert_eq!(gaps.next(), Some(1..4));
1400         assert_eq!(gaps.next(), None);
1401         // Gaps iterator should be fused.
1402         assert_eq!(gaps.next(), None);
1403         assert_eq!(gaps.next(), None);
1404     }
1405 
1406     #[test]
empty_outer_range_with_items_away_from_both_sides()1407     fn empty_outer_range_with_items_away_from_both_sides() {
1408         let mut range_map: RangeMap<u32, ()> = RangeMap::new();
1409         // 0 1 2 3 4 5 6 7 8 9
1410         // ◌ ◆---◇ ◌ ◌ ◌ ◌ ◌ ◌
1411         range_map.insert(1..3, ());
1412         // 0 1 2 3 4 5 6 7 8 9
1413         // ◌ ◌ ◌ ◌ ◌ ◆---◇ ◌ ◌
1414         range_map.insert(5..7, ());
1415         // 0 1 2 3 4 5 6 7 8 9
1416         // ◌ ◌ ◌ ◌ ◆ ◌ ◌ ◌ ◌ ◌
1417         let outer_range = 4..4;
1418         let mut gaps = range_map.gaps(&outer_range);
1419         // Should yield no gaps.
1420         assert_eq!(gaps.next(), None);
1421         // Gaps iterator should be fused.
1422         assert_eq!(gaps.next(), None);
1423         assert_eq!(gaps.next(), None);
1424     }
1425 
1426     #[test]
empty_outer_range_with_items_touching_both_sides()1427     fn empty_outer_range_with_items_touching_both_sides() {
1428         let mut range_map: RangeMap<u32, ()> = RangeMap::new();
1429         // 0 1 2 3 4 5 6 7 8 9
1430         // ◌ ◌ ◆---◇ ◌ ◌ ◌ ◌ ◌ ◌
1431         range_map.insert(2..4, ());
1432         // 0 1 2 3 4 5 6 7 8 9
1433         // ◌ ◌ ◌ ◌ ◆---◇ ◌ ◌ ◌
1434         range_map.insert(4..6, ());
1435         // 0 1 2 3 4 5 6 7 8 9
1436         // ◌ ◌ ◌ ◌ ◆ ◌ ◌ ◌ ◌ ◌
1437         let outer_range = 4..4;
1438         let mut gaps = range_map.gaps(&outer_range);
1439         // Should yield no gaps.
1440         assert_eq!(gaps.next(), None);
1441         // Gaps iterator should be fused.
1442         assert_eq!(gaps.next(), None);
1443         assert_eq!(gaps.next(), None);
1444     }
1445 
1446     #[test]
empty_outer_range_with_item_straddling()1447     fn empty_outer_range_with_item_straddling() {
1448         let mut range_map: RangeMap<u32, ()> = RangeMap::new();
1449         // 0 1 2 3 4 5 6 7 8 9
1450         // ◌ ◌ ◆-----◇ ◌ ◌ ◌ ◌ ◌
1451         range_map.insert(2..5, ());
1452         // 0 1 2 3 4 5 6 7 8 9
1453         // ◌ ◌ ◌ ◌ ◆ ◌ ◌ ◌ ◌ ◌
1454         let outer_range = 4..4;
1455         let mut gaps = range_map.gaps(&outer_range);
1456         // Should yield no gaps.
1457         assert_eq!(gaps.next(), None);
1458         // Gaps iterator should be fused.
1459         assert_eq!(gaps.next(), None);
1460         assert_eq!(gaps.next(), None);
1461     }
1462 
1463     #[test]
no_empty_gaps()1464     fn no_empty_gaps() {
1465         // Make two ranges different values so they don't
1466         // get coalesced.
1467         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
1468         // 0 1 2 3 4 5 6 7 8 9
1469         // ◌ ◌ ◌ ◌ ●-◌ ◌ ◌ ◌ ◌
1470         range_map.insert(4..5, true);
1471         // 0 1 2 3 4 5 6 7 8 9
1472         // ◌ ◌ ◌ ●-◌ ◌ ◌ ◌ ◌ ◌
1473         range_map.insert(3..4, false);
1474         // 0 1 2 3 4 5 6 7 8 9
1475         // ◌ ◆-------------◇ ◌
1476         let outer_range = 1..8;
1477         let mut gaps = range_map.gaps(&outer_range);
1478         // Should yield gaps at start and end, but not between the
1479         // two touching items. (4 is covered, so there should be no gap.)
1480         assert_eq!(gaps.next(), Some(1..3));
1481         assert_eq!(gaps.next(), Some(5..8));
1482         assert_eq!(gaps.next(), None);
1483         // Gaps iterator should be fused.
1484         assert_eq!(gaps.next(), None);
1485         assert_eq!(gaps.next(), None);
1486     }
1487 
1488     ///
1489     /// impl Debug
1490     ///
1491 
1492     #[test]
map_debug_repr_looks_right()1493     fn map_debug_repr_looks_right() {
1494         let mut map: RangeMap<u32, ()> = RangeMap::new();
1495 
1496         // Empty
1497         assert_eq!(format!("{:?}", map), "{}");
1498 
1499         // One entry
1500         map.insert(2..5, ());
1501         assert_eq!(format!("{:?}", map), "{2..5: ()}");
1502 
1503         // Many entries
1504         map.insert(6..7, ());
1505         map.insert(8..9, ());
1506         assert_eq!(format!("{:?}", map), "{2..5: (), 6..7: (), 8..9: ()}");
1507     }
1508 
1509     // Iterator Tests
1510 
1511     #[test]
into_iter_matches_iter()1512     fn into_iter_matches_iter() {
1513         // Just use vec since that's the same implementation we'd expect
1514         let mut range_map: RangeMap<u32, bool> = RangeMap::new();
1515         range_map.insert(1..3, false);
1516         range_map.insert(3..5, true);
1517 
1518         let cloned = range_map.to_vec();
1519         let consumed = range_map.into_iter().collect::<Vec<_>>();
1520 
1521         // Correct value
1522         assert_eq!(cloned, vec![(1..3, false), (3..5, true)]);
1523 
1524         // Equality
1525         assert_eq!(cloned, consumed);
1526     }
1527 }
1528