rangemap/
inclusive_map.rs

1use super::range_wrapper::RangeInclusiveStartWrapper;
2use crate::range_wrapper::RangeInclusiveEndWrapper;
3use crate::std_ext::*;
4use alloc::collections::BTreeMap;
5use core::borrow::Borrow;
6use core::cmp::Ordering;
7use core::fmt::{self, Debug};
8use core::hash::Hash;
9use core::iter::{DoubleEndedIterator, FromIterator};
10use core::marker::PhantomData;
11use core::ops::{RangeFrom, RangeInclusive};
12use core::prelude::v1::*;
13
14#[cfg(feature = "serde1")]
15use serde::{
16    de::{Deserialize, Deserializer, SeqAccess, Visitor},
17    ser::{Serialize, Serializer},
18};
19
20/// A map whose keys are stored as ranges bounded
21/// inclusively below and above `(start..=end)`.
22///
23/// Contiguous and overlapping ranges that map to the same value
24/// are coalesced into a single range.
25///
26/// Successor and predecessor functions must be provided for
27/// the key type `K`, so that we can detect adjacent but non-overlapping
28/// (closed) ranges. (This is not a problem for half-open ranges,
29/// because adjacent ranges can be detected using equality of range ends alone.)
30///
31/// You can provide these functions either by implementing the
32/// [`StepLite`] trait for your key type `K`, or,
33/// if this is impossible because of Rust's "orphan rules",
34/// you can provide equivalent free functions using the `StepFnsT` type parameter.
35/// [`StepLite`] is implemented for all standard integer types,
36/// but not for any third party crate types.
37#[derive(Clone)]
38pub struct RangeInclusiveMap<K, V, StepFnsT = K> {
39    // Wrap ranges so that they are `Ord`.
40    // See `range_wrapper.rs` for explanation.
41    pub(crate) btm: BTreeMap<RangeInclusiveStartWrapper<K>, V>,
42    _phantom: PhantomData<StepFnsT>,
43}
44
45impl<K, V, StepFnsT> Default for RangeInclusiveMap<K, V, StepFnsT> {
46    fn default() -> Self {
47        Self {
48            btm: BTreeMap::default(),
49            _phantom: PhantomData,
50        }
51    }
52}
53
54impl<K, V, StepFnsT> Hash for RangeInclusiveMap<K, V, StepFnsT>
55where
56    K: Hash,
57    V: Hash,
58{
59    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
60        state.write_usize(self.btm.len());
61        for elt in self.iter() {
62            elt.hash(state);
63        }
64    }
65}
66
67impl<K, V, StepFnsT> PartialEq for RangeInclusiveMap<K, V, StepFnsT>
68where
69    K: PartialEq,
70    V: PartialEq,
71{
72    fn eq(&self, other: &RangeInclusiveMap<K, V, StepFnsT>) -> bool {
73        self.btm == other.btm
74    }
75}
76
77impl<K, V, StepFnsT> Eq for RangeInclusiveMap<K, V, StepFnsT>
78where
79    K: Eq,
80    V: Eq,
81{
82}
83
84impl<K, V, StepFnsT> PartialOrd for RangeInclusiveMap<K, V, StepFnsT>
85where
86    K: PartialOrd,
87    V: PartialOrd,
88{
89    #[inline]
90    fn partial_cmp(&self, other: &RangeInclusiveMap<K, V, StepFnsT>) -> Option<Ordering> {
91        self.btm.partial_cmp(&other.btm)
92    }
93}
94
95impl<K, V, StepFnsT> Ord for RangeInclusiveMap<K, V, StepFnsT>
96where
97    K: Ord,
98    V: Ord,
99{
100    #[inline]
101    fn cmp(&self, other: &RangeInclusiveMap<K, V, StepFnsT>) -> Ordering {
102        self.btm.cmp(&other.btm)
103    }
104}
105
106#[cfg(feature = "quickcheck")]
107impl<K, V> quickcheck::Arbitrary for RangeInclusiveMap<K, V>
108where
109    K: quickcheck::Arbitrary + Ord + StepLite,
110    V: quickcheck::Arbitrary + PartialEq,
111{
112    fn arbitrary(g: &mut quickcheck::Gen) -> Self {
113        // REVISIT: allocation could be avoided if Gen::gen_size were public (https://github.com/BurntSushi/quickcheck/issues/326#issue-2653601170)
114        <alloc::vec::Vec<(RangeInclusive<_>, _)>>::arbitrary(g)
115            .into_iter()
116            .filter(|(range, _)| !range.is_empty())
117            .collect()
118    }
119}
120
121impl<K, V, StepFnsT> RangeInclusiveMap<K, V, StepFnsT> {
122    /// Gets an iterator over all pairs of key range and value,
123    /// ordered by key range.
124    ///
125    /// The iterator element type is `(&'a RangeInclusive<K>, &'a V)`.
126    pub fn iter(&self) -> Iter<'_, K, V> {
127        Iter {
128            inner: self.btm.iter(),
129        }
130    }
131}
132
133impl<K, V> RangeInclusiveMap<K, V, K>
134where
135    K: Ord + Clone + StepLite,
136    V: PartialEq + Clone,
137{
138    /// Makes a new empty `RangeInclusiveMap`.
139    #[cfg(feature = "const_fn")]
140    pub const fn new() -> Self {
141        Self::new_with_step_fns()
142    }
143
144    /// Makes a new empty `RangeInclusiveMap`.
145    #[cfg(not(feature = "const_fn"))]
146    pub fn new() -> Self {
147        Self::new_with_step_fns()
148    }
149}
150
151impl<K, V, StepFnsT> RangeInclusiveMap<K, V, StepFnsT>
152where
153    K: Ord + Clone,
154    V: PartialEq + Clone,
155    StepFnsT: StepFns<K>,
156{
157    /// Makes a new empty `RangeInclusiveMap`, specifying successor and
158    /// predecessor functions defined separately from `K` itself.
159    ///
160    /// This is useful as a workaround for Rust's "orphan rules",
161    /// which prevent you from implementing `StepLite` for `K` if `K`
162    /// is a foreign type.
163    ///
164    /// **NOTE:** This will likely be deprecated and then eventually
165    /// removed once the standard library's [Step](core::iter::Step)
166    /// trait is stabilised, as most crates will then likely implement [Step](core::iter::Step)
167    /// for their types where appropriate.
168    ///
169    /// See [this issue](https://github.com/rust-lang/rust/issues/42168)
170    /// for details about that stabilization process.
171    #[cfg(not(feature = "const_fn"))]
172    pub fn new_with_step_fns() -> Self {
173        Self {
174            btm: BTreeMap::new(),
175            _phantom: PhantomData,
176        }
177    }
178
179    #[cfg(feature = "const_fn")]
180    pub const fn new_with_step_fns() -> Self {
181        Self {
182            btm: BTreeMap::new(),
183            _phantom: PhantomData,
184        }
185    }
186    /// Returns a reference to the value corresponding to the given key,
187    /// if the key is covered by any range in the map.
188    pub fn get(&self, key: &K) -> Option<&V> {
189        self.get_key_value(key).map(|(_range, value)| value)
190    }
191
192    /// Returns the range-value pair (as a pair of references) corresponding
193    /// to the given key, if the key is covered by any range in the map.
194    pub fn get_key_value(&self, key: &K) -> Option<(&RangeInclusive<K>, &V)> {
195        use core::ops::Bound;
196
197        // The only stored range that could contain the given key is the
198        // last stored range whose start is less than or equal to this key.
199        let key_as_start = RangeInclusiveStartWrapper::new(key.clone()..=key.clone());
200        self.btm
201            .range((Bound::Unbounded, Bound::Included(key_as_start)))
202            .next_back()
203            .filter(|(range_start_wrapper, _value)| {
204                // Does the only candidate range contain
205                // the requested key?
206                range_start_wrapper.contains(key)
207            })
208            .map(|(range_start_wrapper, value)| (&range_start_wrapper.range, value))
209    }
210
211    /// Returns `true` if any range in the map covers the specified key.
212    pub fn contains_key(&self, key: &K) -> bool {
213        self.get(key).is_some()
214    }
215
216    /// Clears the map, removing all elements.
217    pub fn clear(&mut self) {
218        self.btm.clear();
219    }
220
221    /// Returns the number of elements in the map.
222    pub fn len(&self) -> usize {
223        self.btm.len()
224    }
225
226    /// Returns true if the map contains no elements.
227    pub fn is_empty(&self) -> bool {
228        self.btm.is_empty()
229    }
230
231    /// Insert a pair of key range and value into the map.
232    ///
233    /// If the inserted range partially or completely overlaps any
234    /// existing range in the map, then the existing range (or ranges) will be
235    /// partially or completely replaced by the inserted range.
236    ///
237    /// If the inserted range either overlaps or is immediately adjacent
238    /// any existing range _mapping to the same value_, then the ranges
239    /// will be coalesced into a single contiguous range.
240    ///
241    /// # Panics
242    ///
243    /// Panics if range `start > end`.
244    pub fn insert(&mut self, range: RangeInclusive<K>, value: V) {
245        use core::ops::Bound;
246
247        // Backwards ranges don't make sense.
248        // `RangeInclusive` doesn't enforce this,
249        // and we don't want weird explosions further down
250        // if someone gives us such a range.
251        assert!(
252            range.start() <= range.end(),
253            "Range start can not be after range end"
254        );
255
256        // Wrap up the given range so that we can "borrow"
257        // it as a wrapper reference to either its start or end.
258        // See `range_wrapper.rs` for explanation of these hacks.
259        let mut new_range_start_wrapper: RangeInclusiveStartWrapper<K> =
260            RangeInclusiveStartWrapper::new(range);
261        let new_value = value;
262
263        // Is there a stored range either overlapping the start of
264        // the range to insert or immediately preceding it?
265        //
266        // If there is any such stored range, it will be the last
267        // whose start is less than or equal to _one less than_
268        // the start of the range to insert, or the one before that
269        // if both of the above cases exist.
270        let mut candidates = self
271            .btm
272            .range::<RangeInclusiveStartWrapper<K>, (
273                Bound<&RangeInclusiveStartWrapper<K>>,
274                Bound<&RangeInclusiveStartWrapper<K>>,
275            )>((Bound::Unbounded, Bound::Included(&new_range_start_wrapper)))
276            .rev()
277            .take(2)
278            .filter(|(stored_range_start_wrapper, _stored_value)| {
279                // Does the candidate range either overlap
280                // or immediately precede the range to insert?
281                // (Remember that it might actually cover the _whole_
282                // range to insert and then some.)
283                stored_range_start_wrapper
284                    .touches::<StepFnsT>(&new_range_start_wrapper.end_wrapper.range)
285            });
286        if let Some(mut candidate) = candidates.next() {
287            // Or the one before it if both cases described above exist.
288            if let Some(another_candidate) = candidates.next() {
289                candidate = another_candidate;
290            }
291            let (stored_range_start_wrapper, stored_value) =
292                (candidate.0.clone(), candidate.1.clone());
293            self.adjust_touching_ranges_for_insert(
294                stored_range_start_wrapper,
295                stored_value,
296                &mut new_range_start_wrapper.end_wrapper.range,
297                &new_value,
298            );
299        }
300
301        // Are there any stored ranges whose heads overlap or immediately
302        // follow the range to insert?
303        //
304        // If there are any such stored ranges (that weren't already caught above),
305        // their starts will fall somewhere after the start of the range to insert,
306        // and on, before, or _immediately after_ its end. To handle that last case
307        // without risking arithmetic overflow, we'll consider _one more_ stored item past
308        // the end of the end of the range to insert.
309        //
310        // REVISIT: Possible micro-optimisation: `impl Borrow<T> for RangeInclusiveStartWrapper<T>`
311        // and use that to search here, to avoid constructing another `RangeInclusiveStartWrapper`.
312        let second_last_possible_start = new_range_start_wrapper.end().clone();
313        let second_last_possible_start = RangeInclusiveStartWrapper::new(
314            second_last_possible_start.clone()..=second_last_possible_start,
315        );
316        while let Some((stored_range_start_wrapper, stored_value)) = self
317            .btm
318            .range::<RangeInclusiveStartWrapper<K>, (
319                Bound<&RangeInclusiveStartWrapper<K>>,
320                Bound<&RangeInclusiveStartWrapper<K>>,
321            )>((
322                Bound::Included(&new_range_start_wrapper),
323                // We would use something like `Bound::Included(&last_possible_start)`,
324                // but making `last_possible_start` might cause arithmetic overflow;
325                // instead decide inside the loop whether we've gone too far and break.
326                Bound::Unbounded,
327            ))
328            .next()
329        {
330            // A couple of extra exceptions are needed at the
331            // end of the subset of stored ranges we want to consider,
332            // in part because we use `Bound::Unbounded` above.
333            // (See comments up there, and in the individual cases below.)
334            let stored_start = stored_range_start_wrapper.start();
335            if *stored_start > *second_last_possible_start.start() {
336                let latest_possible_start = StepFnsT::add_one(second_last_possible_start.start());
337                if *stored_start > latest_possible_start {
338                    // We're beyond the last stored range that could be relevant.
339                    // Avoid wasting time on irrelevant ranges, or even worse, looping forever.
340                    // (`adjust_touching_ranges_for_insert` below assumes that the given range
341                    // is relevant, and behaves very poorly if it is handed a range that it
342                    // shouldn't be touching.)
343                    break;
344                }
345
346                if *stored_start == latest_possible_start && *stored_value != new_value {
347                    // We are looking at the last stored range that could be relevant,
348                    // but it has a different value, so we don't want to merge with it.
349                    // We must explicitly break here as well, because `adjust_touching_ranges_for_insert`
350                    // below assumes that the given range is relevant, and behaves very poorly if it
351                    // is handed a range that it shouldn't be touching.
352                    break;
353                }
354            }
355
356            let stored_range_start_wrapper = stored_range_start_wrapper.clone();
357            let stored_value = stored_value.clone();
358
359            self.adjust_touching_ranges_for_insert(
360                stored_range_start_wrapper,
361                stored_value,
362                &mut new_range_start_wrapper.end_wrapper.range,
363                &new_value,
364            );
365        }
366
367        // Insert the (possibly expanded) new range, and we're done!
368        self.btm.insert(new_range_start_wrapper, new_value);
369    }
370
371    /// Removes a range from the map, if all or any of it was present.
372    ///
373    /// If the range to be removed _partially_ overlaps any ranges
374    /// in the map, then those ranges will be contracted to no
375    /// longer cover the removed range.
376    ///
377    ///
378    /// # Panics
379    ///
380    /// Panics if range `start > end`.
381    pub fn remove(&mut self, range: RangeInclusive<K>) {
382        use core::ops::Bound;
383
384        // Backwards ranges don't make sense.
385        // `RangeInclusive` doesn't enforce this,
386        // and we don't want weird explosions further down
387        // if someone gives us such a range.
388        assert!(
389            range.start() <= range.end(),
390            "Range start can not be after range end"
391        );
392
393        let range_start_wrapper: RangeInclusiveStartWrapper<K> =
394            RangeInclusiveStartWrapper::new(range);
395        let range = &range_start_wrapper.range;
396
397        // Is there a stored range overlapping the start of
398        // the range to insert?
399        //
400        // If there is any such stored range, it will be the last
401        // whose start is less than or equal to the start of the range to insert.
402        if let Some((stored_range_start_wrapper, stored_value)) = self
403            .btm
404            .range::<RangeInclusiveStartWrapper<K>, (
405                Bound<&RangeInclusiveStartWrapper<K>>,
406                Bound<&RangeInclusiveStartWrapper<K>>,
407            )>((Bound::Unbounded, Bound::Included(&range_start_wrapper)))
408            .next_back()
409            .filter(|(stored_range_start_wrapper, _stored_value)| {
410                // Does the only candidate range overlap
411                // the range to insert?
412                stored_range_start_wrapper.overlaps(range)
413            })
414            .map(|(stored_range_start_wrapper, stored_value)| {
415                (stored_range_start_wrapper.clone(), stored_value.clone())
416            })
417        {
418            self.adjust_overlapping_ranges_for_remove(
419                stored_range_start_wrapper,
420                stored_value,
421                range,
422            );
423        }
424
425        // Are there any stored ranges whose heads overlap the range to insert?
426        //
427        // If there are any such stored ranges (that weren't already caught above),
428        // their starts will fall somewhere after the start of the range to insert,
429        // and on or before its end.
430        //
431        // REVISIT: Possible micro-optimisation: `impl Borrow<T> for RangeInclusiveStartWrapper<T>`
432        // and use that to search here, to avoid constructing another `RangeInclusiveStartWrapper`.
433        let new_range_end_as_start =
434            RangeInclusiveStartWrapper::new(range.end().clone()..=range.end().clone());
435        while let Some((stored_range_start_wrapper, stored_value)) = self
436            .btm
437            .range::<RangeInclusiveStartWrapper<K>, (
438                Bound<&RangeInclusiveStartWrapper<K>>,
439                Bound<&RangeInclusiveStartWrapper<K>>,
440            )>((
441                Bound::Excluded(&range_start_wrapper),
442                Bound::Included(&new_range_end_as_start),
443            ))
444            .next()
445            .map(|(stored_range_start_wrapper, stored_value)| {
446                (stored_range_start_wrapper.clone(), stored_value.clone())
447            })
448        {
449            self.adjust_overlapping_ranges_for_remove(
450                stored_range_start_wrapper,
451                stored_value,
452                range,
453            );
454        }
455    }
456
457    fn adjust_touching_ranges_for_insert(
458        &mut self,
459        stored_range_start_wrapper: RangeInclusiveStartWrapper<K>,
460        stored_value: V,
461        new_range: &mut RangeInclusive<K>,
462        new_value: &V,
463    ) {
464        use core::cmp::{max, min};
465
466        if stored_value == *new_value {
467            // The ranges have the same value, so we can "adopt"
468            // the stored range.
469            //
470            // This means that no matter how big or where the stored range is,
471            // we will expand the new range's bounds to subsume it,
472            // and then delete the stored range.
473            let new_start = min(new_range.start(), stored_range_start_wrapper.start()).clone();
474            let new_end = max(new_range.end(), stored_range_start_wrapper.end()).clone();
475            *new_range = new_start..=new_end;
476            self.btm.remove(&stored_range_start_wrapper);
477        } else {
478            // The ranges have different values.
479            if new_range.overlaps(&stored_range_start_wrapper.range) {
480                // The ranges overlap. This is a little bit more complicated.
481                // Delete the stored range, and then add back between
482                // 0 and 2 subranges at the ends of the range to insert.
483                self.btm.remove(&stored_range_start_wrapper);
484                if stored_range_start_wrapper.start() < new_range.start() {
485                    // Insert the piece left of the range to insert.
486                    self.btm.insert(
487                        RangeInclusiveStartWrapper::new(
488                            stored_range_start_wrapper.start().clone()
489                                ..=StepFnsT::sub_one(new_range.start()),
490                        ),
491                        stored_value.clone(),
492                    );
493                }
494                if stored_range_start_wrapper.end() > new_range.end() {
495                    // Insert the piece right of the range to insert.
496                    self.btm.insert(
497                        RangeInclusiveStartWrapper::new(
498                            StepFnsT::add_one(new_range.end())
499                                ..=stored_range_start_wrapper.end().clone(),
500                        ),
501                        stored_value,
502                    );
503                }
504            } else {
505                // No-op; they're not overlapping,
506                // so we can just keep both ranges as they are.
507            }
508        }
509    }
510
511    fn adjust_overlapping_ranges_for_remove(
512        &mut self,
513        stored_range_start_wrapper: RangeInclusiveStartWrapper<K>,
514        stored_value: V,
515        range_to_remove: &RangeInclusive<K>,
516    ) {
517        // Delete the stored range, and then add back between
518        // 0 and 2 subranges at the ends of the range to insert.
519        self.btm.remove(&stored_range_start_wrapper);
520        let stored_range = stored_range_start_wrapper.end_wrapper.range;
521        if stored_range.start() < range_to_remove.start() {
522            // Insert the piece left of the range to insert.
523            self.btm.insert(
524                RangeInclusiveStartWrapper::new(
525                    stored_range.start().clone()..=StepFnsT::sub_one(range_to_remove.start()),
526                ),
527                stored_value.clone(),
528            );
529        }
530        if stored_range.end() > range_to_remove.end() {
531            // Insert the piece right of the range to insert.
532            self.btm.insert(
533                RangeInclusiveStartWrapper::new(
534                    StepFnsT::add_one(range_to_remove.end())..=stored_range.end().clone(),
535                ),
536                stored_value,
537            );
538        }
539    }
540
541    /// Gets an iterator over all the maximally-sized ranges
542    /// contained in `outer_range` that are not covered by
543    /// any range stored in the map.
544    ///
545    /// The iterator element type is `RangeInclusive<K>`.
546    pub fn gaps<'a>(&'a self, outer_range: &'a RangeInclusive<K>) -> Gaps<'a, K, V, StepFnsT> {
547        let overlap_iter = self.overlapping(outer_range);
548        Gaps {
549            candidate_needs_plus_one: false,
550            candidate_start: outer_range.start(),
551            query_end: outer_range.end(),
552            btm_range_iter: overlap_iter.btm_range_iter,
553            // We'll start the candidate range at the start of the outer range
554            // without checking what's there. Each time we yield an item,
555            // we'll skip any ranges we find before the next gap.
556            _phantom: PhantomData,
557        }
558    }
559
560    /// Gets an iterator over all the stored ranges that are
561    /// either partially or completely overlapped by the given range.
562    pub fn overlapping<R: Borrow<RangeInclusive<K>>>(
563        &'_ self,
564        range: R,
565    ) -> Overlapping<'_, K, V, R> {
566        // Find the first matching stored range by its _end_,
567        // using sneaky layering and `Borrow` implementation. (See `range_wrappers` module.)
568        let start_sliver = RangeInclusiveEndWrapper::new(
569            range.borrow().start().clone()..=range.borrow().start().clone(),
570        );
571        let btm_range_iter = self
572            .btm
573            .range::<RangeInclusiveEndWrapper<K>, RangeFrom<&RangeInclusiveEndWrapper<K>>>(
574                &start_sliver..,
575            );
576        Overlapping {
577            query_range: range,
578            btm_range_iter,
579        }
580    }
581
582    /// Returns `true` if any range in the map completely or partially
583    /// overlaps the given range.
584    pub fn overlaps(&self, range: &RangeInclusive<K>) -> bool {
585        self.overlapping(range).next().is_some()
586    }
587
588    /// Returns the first range-value pair in this map, if one exists. The range in this pair is the
589    /// minimum range in the map.
590    pub fn first_range_value(&self) -> Option<(&RangeInclusive<K>, &V)> {
591        self.btm
592            .first_key_value()
593            .map(|(range, value)| (&range.end_wrapper.range, value))
594    }
595
596    /// Returns the last range-value pair in this map, if one exists. The range in this pair is the
597    /// maximum range in the map.
598    pub fn last_range_value(&self) -> Option<(&RangeInclusive<K>, &V)> {
599        self.btm
600            .last_key_value()
601            .map(|(range, value)| (&range.end_wrapper.range, value))
602    }
603}
604
605/// An iterator over the entries of a `RangeInclusiveMap`, ordered by key range.
606///
607/// The iterator element type is `(&'a RangeInclusive<K>, &'a V)`.
608///
609/// This `struct` is created by the [`iter`] method on [`RangeInclusiveMap`]. See its
610/// documentation for more.
611///
612/// [`iter`]: RangeInclusiveMap::iter
613pub struct Iter<'a, K, V> {
614    inner: alloc::collections::btree_map::Iter<'a, RangeInclusiveStartWrapper<K>, V>,
615}
616
617impl<'a, K, V> Iterator for Iter<'a, K, V>
618where
619    K: 'a,
620    V: 'a,
621{
622    type Item = (&'a RangeInclusive<K>, &'a V);
623
624    fn next(&mut self) -> Option<Self::Item> {
625        self.inner.next().map(|(by_start, v)| (&by_start.range, v))
626    }
627
628    fn size_hint(&self) -> (usize, Option<usize>) {
629        self.inner.size_hint()
630    }
631}
632
633impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V>
634where
635    K: 'a,
636    V: 'a,
637{
638    fn next_back(&mut self) -> Option<Self::Item> {
639        self.inner
640            .next_back()
641            .map(|(range, value)| (&range.end_wrapper.range, value))
642    }
643}
644
645/// An owning iterator over the entries of a `RangeInclusiveMap`, ordered by key range.
646///
647/// The iterator element type is `(RangeInclusive<K>, V)`.
648///
649/// This `struct` is created by the [`into_iter`] method on [`RangeInclusiveMap`]
650/// (provided by the `IntoIterator` trait). See its documentation for more.
651///
652/// [`into_iter`]: IntoIterator::into_iter
653pub struct IntoIter<K, V> {
654    inner: alloc::collections::btree_map::IntoIter<RangeInclusiveStartWrapper<K>, V>,
655}
656
657impl<K, V> IntoIterator for RangeInclusiveMap<K, V> {
658    type Item = (RangeInclusive<K>, V);
659    type IntoIter = IntoIter<K, V>;
660    fn into_iter(self) -> Self::IntoIter {
661        IntoIter {
662            inner: self.btm.into_iter(),
663        }
664    }
665}
666
667impl<K, V> Iterator for IntoIter<K, V> {
668    type Item = (RangeInclusive<K>, V);
669    fn next(&mut self) -> Option<(RangeInclusive<K>, V)> {
670        self.inner
671            .next()
672            .map(|(by_start, v)| (by_start.end_wrapper.range, v))
673    }
674    fn size_hint(&self) -> (usize, Option<usize>) {
675        self.inner.size_hint()
676    }
677}
678
679impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
680    fn next_back(&mut self) -> Option<Self::Item> {
681        self.inner
682            .next_back()
683            .map(|(range, value)| (range.end_wrapper.range, value))
684    }
685}
686
687// We can't just derive this automatically, because that would
688// expose irrelevant (and private) implementation details.
689// Instead implement it in the same way that the underlying BTreeMap does.
690impl<K: Debug, V: Debug> Debug for RangeInclusiveMap<K, V>
691where
692    K: Ord + Clone + StepLite,
693    V: PartialEq + Clone,
694{
695    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
696        f.debug_map().entries(self.iter()).finish()
697    }
698}
699
700impl<K, V> FromIterator<(RangeInclusive<K>, V)> for RangeInclusiveMap<K, V>
701where
702    K: Ord + Clone + StepLite,
703    V: PartialEq + Clone,
704{
705    fn from_iter<T: IntoIterator<Item = (RangeInclusive<K>, V)>>(iter: T) -> Self {
706        let mut range_map = RangeInclusiveMap::new();
707        range_map.extend(iter);
708        range_map
709    }
710}
711
712impl<K, V> Extend<(RangeInclusive<K>, V)> for RangeInclusiveMap<K, V>
713where
714    K: Ord + Clone + StepLite,
715    V: PartialEq + Clone,
716{
717    fn extend<T: IntoIterator<Item = (RangeInclusive<K>, V)>>(&mut self, iter: T) {
718        iter.into_iter().for_each(move |(k, v)| {
719            self.insert(k, v);
720        })
721    }
722}
723
724#[cfg(feature = "serde1")]
725impl<K, V> Serialize for RangeInclusiveMap<K, V>
726where
727    K: Ord + Clone + StepLite + Serialize,
728    V: PartialEq + Clone + Serialize,
729{
730    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
731    where
732        S: Serializer,
733    {
734        use serde::ser::SerializeSeq;
735        let mut seq = serializer.serialize_seq(Some(self.btm.len()))?;
736        for (k, v) in self.iter() {
737            seq.serialize_element(&((k.start(), k.end()), &v))?;
738        }
739        seq.end()
740    }
741}
742
743#[cfg(feature = "serde1")]
744impl<'de, K, V> Deserialize<'de> for RangeInclusiveMap<K, V>
745where
746    K: Ord + Clone + StepLite + Deserialize<'de>,
747    V: PartialEq + Clone + Deserialize<'de>,
748{
749    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
750    where
751        D: Deserializer<'de>,
752    {
753        deserializer.deserialize_seq(RangeInclusiveMapVisitor::new())
754    }
755}
756
757#[cfg(feature = "serde1")]
758struct RangeInclusiveMapVisitor<K, V> {
759    marker: PhantomData<fn() -> RangeInclusiveMap<K, V>>,
760}
761
762#[cfg(feature = "serde1")]
763impl<K, V> RangeInclusiveMapVisitor<K, V> {
764    fn new() -> Self {
765        RangeInclusiveMapVisitor {
766            marker: PhantomData,
767        }
768    }
769}
770
771#[cfg(feature = "serde1")]
772impl<'de, K, V> Visitor<'de> for RangeInclusiveMapVisitor<K, V>
773where
774    K: Ord + Clone + StepLite + Deserialize<'de>,
775    V: PartialEq + Clone + Deserialize<'de>,
776{
777    type Value = RangeInclusiveMap<K, V>;
778
779    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
780        formatter.write_str("RangeInclusiveMap")
781    }
782
783    fn visit_seq<A>(self, mut access: A) -> Result<Self::Value, A::Error>
784    where
785        A: SeqAccess<'de>,
786    {
787        let mut range_inclusive_map = RangeInclusiveMap::new();
788        while let Some(((start, end), value)) = access.next_element()? {
789            range_inclusive_map.insert(start..=end, value);
790        }
791        Ok(range_inclusive_map)
792    }
793}
794
795/// An iterator over all ranges not covered by a `RangeInclusiveMap`.
796///
797/// The iterator element type is `RangeInclusive<K>`.
798///
799/// This `struct` is created by the [`gaps`] method on [`RangeInclusiveMap`]. See its
800/// documentation for more.
801///
802/// [`gaps`]: RangeInclusiveMap::gaps
803pub struct Gaps<'a, K, V, StepFnsT> {
804    /// Would be redundant, but we need an extra flag to
805    /// avoid overflowing when dealing with inclusive ranges.
806    ///
807    /// All other things here are ignored if `done` is `true`.
808    candidate_needs_plus_one: bool,
809    candidate_start: &'a K,
810    query_end: &'a K,
811    btm_range_iter: alloc::collections::btree_map::Range<'a, RangeInclusiveStartWrapper<K>, V>,
812    _phantom: PhantomData<StepFnsT>,
813}
814
815// `Gaps` is always fused. (See definition of `next` below.)
816impl<'a, K, V, StepFnsT> core::iter::FusedIterator for Gaps<'a, K, V, StepFnsT>
817where
818    K: Ord + Clone,
819    StepFnsT: StepFns<K>,
820{
821}
822
823impl<'a, K, V, StepFnsT> Iterator for Gaps<'a, K, V, StepFnsT>
824where
825    K: Ord + Clone,
826    StepFnsT: StepFns<K>,
827{
828    type Item = RangeInclusive<K>;
829
830    fn next(&mut self) -> Option<Self::Item> {
831        for overlap in self.btm_range_iter.by_ref() {
832            let overlap = overlap.0;
833
834            // If the range in the map has advanced beyond the query range, return
835            // any tail gap.
836            if *self.query_end < *overlap.start() {
837                break;
838            }
839
840            let candidate_needs_plus_one =
841                core::mem::replace(&mut self.candidate_needs_plus_one, true);
842
843            let cur_candidate_start = core::mem::replace(&mut self.candidate_start, overlap.end());
844
845            let cur_candidate_start = if candidate_needs_plus_one {
846                StepFnsT::add_one(cur_candidate_start)
847            } else {
848                cur_candidate_start.clone()
849            };
850
851            if cur_candidate_start < *overlap.start() {
852                let gap = cur_candidate_start..=StepFnsT::sub_one(overlap.start());
853                return Some(gap);
854            }
855        }
856
857        // Now that we've run out of items, the only other possible
858        // gap is one at the end of the outer range.
859        let candidate_needs_plus_one = core::mem::replace(&mut self.candidate_needs_plus_one, true);
860
861        let cur_candidate_start = core::mem::replace(&mut self.candidate_start, self.query_end);
862        if candidate_needs_plus_one {
863            if *cur_candidate_start < *self.query_end {
864                return Some(StepFnsT::add_one(cur_candidate_start)..=self.query_end.clone());
865            }
866        } else if *cur_candidate_start <= *self.query_end {
867            // There's a gap at the end!
868            return Some(cur_candidate_start.clone()..=self.query_end.clone());
869        }
870
871        None
872    }
873}
874
875/// An iterator over all stored ranges partially or completely
876/// overlapped by a given range.
877///
878/// The iterator element type is `(&'a RangeInclusive<K>, &'a V)`.
879///
880/// This `struct` is created by the [`overlapping`] method on [`RangeInclusiveMap`]. See its
881/// documentation for more.
882///
883/// [`overlapping`]: RangeInclusiveMap::overlapping
884pub struct Overlapping<'a, K, V, R: Borrow<RangeInclusive<K>> = &'a RangeInclusive<K>> {
885    query_range: R,
886    btm_range_iter: alloc::collections::btree_map::Range<'a, RangeInclusiveStartWrapper<K>, V>,
887}
888
889// `Overlapping` is always fused. (See definition of `next` below.)
890impl<'a, K, V, R: Borrow<RangeInclusive<K>>> core::iter::FusedIterator for Overlapping<'a, K, V, R> where
891    K: Ord + Clone
892{
893}
894
895impl<'a, K, V, R: Borrow<RangeInclusive<K>>> Iterator for Overlapping<'a, K, V, R>
896where
897    K: Ord + Clone,
898{
899    type Item = (&'a RangeInclusive<K>, &'a V);
900
901    fn next(&mut self) -> Option<Self::Item> {
902        if let Some((k, v)) = self.btm_range_iter.next() {
903            if k.start() <= self.query_range.borrow().end() {
904                Some((&k.range, v))
905            } else {
906                // The rest of the items in the underlying iterator
907                // are past the query range. We can keep taking items
908                // from that iterator and this will remain true,
909                // so this is enough to make the iterator fused.
910                None
911            }
912        } else {
913            None
914        }
915    }
916}
917
918impl<'a, K, V, R: Borrow<RangeInclusive<K>>> DoubleEndedIterator for Overlapping<'a, K, V, R>
919where
920    K: Ord + Clone,
921{
922    fn next_back(&mut self) -> Option<Self::Item> {
923        while let Some((k, v)) = self.btm_range_iter.next_back() {
924            if k.start() <= self.query_range.borrow().end() {
925                return Some((&k.range, v));
926            }
927        }
928
929        None
930    }
931}
932
933impl<K: Ord + Clone + StepLite, V: Eq + Clone, const N: usize> From<[(RangeInclusive<K>, V); N]>
934    for RangeInclusiveMap<K, V>
935{
936    fn from(value: [(RangeInclusive<K>, V); N]) -> Self {
937        let mut map = Self::new();
938        for (range, value) in IntoIterator::into_iter(value) {
939            map.insert(range, value);
940        }
941        map
942    }
943}
944
945/// Create a [`RangeInclusiveMap`] from key-value pairs.
946///
947/// # Example
948///
949/// ```rust
950/// # use rangemap::range_inclusive_map;
951/// let map = range_inclusive_map!{
952///     0..=100 => "abc",
953///     100..=200 => "def",
954///     200..=300 => "ghi"
955/// };
956/// ```
957#[macro_export]
958macro_rules! range_inclusive_map {
959    ($($k:expr => $v:expr),* $(,)?) => {{
960        $crate::RangeInclusiveMap::from([$(($k, $v)),*])
961    }};
962}
963
964#[cfg(test)]
965mod tests {
966    use super::*;
967    use alloc as std;
968    use alloc::{format, string::String, vec, vec::Vec};
969    use proptest::prelude::*;
970    use test_strategy::proptest;
971
972    impl<K, V> Arbitrary for RangeInclusiveMap<K, V>
973    where
974        K: Ord + Clone + Debug + StepLite + Arbitrary + 'static,
975        V: Clone + PartialEq + Arbitrary + 'static,
976    {
977        type Parameters = ();
978        type Strategy = BoxedStrategy<Self>;
979
980        fn arbitrary_with(_parameters: Self::Parameters) -> Self::Strategy {
981            any::<Vec<(RangeInclusive<K>, V)>>()
982                .prop_map(|ranges| ranges.into_iter().collect::<RangeInclusiveMap<K, V>>())
983                .boxed()
984        }
985    }
986
987    #[proptest]
988    #[allow(clippy::len_zero)]
989    fn test_len(mut map: RangeInclusiveMap<u64, String>) {
990        assert_eq!(map.len(), map.iter().count());
991        assert_eq!(map.is_empty(), map.len() == 0);
992        map.clear();
993        assert_eq!(map.len(), 0);
994        assert!(map.is_empty());
995        assert_eq!(map.iter().count(), 0);
996    }
997
998    #[proptest]
999    fn test_first(set: RangeInclusiveMap<u64, String>) {
1000        assert_eq!(
1001            set.first_range_value(),
1002            set.iter().min_by_key(|(range, _)| range.start())
1003        );
1004    }
1005
1006    #[proptest]
1007    fn test_last(set: RangeInclusiveMap<u64, String>) {
1008        assert_eq!(
1009            set.last_range_value(),
1010            set.iter().max_by_key(|(range, _)| range.end())
1011        );
1012    }
1013
1014    #[proptest]
1015    fn test_iter_reversible(set: RangeInclusiveMap<u64, String>) {
1016        let forward: Vec<_> = set.iter().collect();
1017        let mut backward: Vec<_> = set.iter().rev().collect();
1018        backward.reverse();
1019        assert_eq!(forward, backward);
1020    }
1021
1022    #[proptest]
1023    fn test_into_iter_reversible(set: RangeInclusiveMap<u64, String>) {
1024        let forward: Vec<_> = set.clone().into_iter().collect();
1025        let mut backward: Vec<_> = set.into_iter().rev().collect();
1026        backward.reverse();
1027        assert_eq!(forward, backward);
1028    }
1029
1030    #[proptest]
1031    fn test_overlapping_reversible(
1032        set: RangeInclusiveMap<u64, String>,
1033        range: RangeInclusive<u64>,
1034    ) {
1035        let forward: Vec<_> = set.overlapping(&range).collect();
1036        let mut backward: Vec<_> = set.overlapping(&range).rev().collect();
1037        backward.reverse();
1038        assert_eq!(forward, backward);
1039    }
1040
1041    #[proptest]
1042    fn test_arbitrary_map_u8(ranges: Vec<(RangeInclusive<u8>, String)>) {
1043        let ranges: Vec<_> = ranges
1044            .into_iter()
1045            .filter(|(range, _value)| range.start() != range.end())
1046            .collect();
1047        let set = ranges
1048            .iter()
1049            .fold(RangeInclusiveMap::new(), |mut set, (range, value)| {
1050                set.insert(range.clone(), value.clone());
1051                set
1052            });
1053
1054        for value in 0..u8::MAX {
1055            assert_eq!(
1056                set.get(&value),
1057                ranges
1058                    .iter()
1059                    .rev()
1060                    .find(|(range, _value)| range.contains(&value))
1061                    .map(|(_range, value)| value)
1062            );
1063        }
1064    }
1065
1066    #[proptest]
1067    #[allow(deprecated)]
1068    fn test_hash(left: RangeInclusiveMap<u64, u64>, right: RangeInclusiveMap<u64, u64>) {
1069        use core::hash::{Hash, Hasher, SipHasher};
1070
1071        let hash = |set: &RangeInclusiveMap<_, _>| {
1072            let mut hasher = SipHasher::new();
1073            set.hash(&mut hasher);
1074            hasher.finish()
1075        };
1076
1077        if left == right {
1078            assert!(
1079                hash(&left) == hash(&right),
1080                "if two values are equal, their hash must be equal"
1081            );
1082        }
1083
1084        // if the hashes are equal the values might not be the same (collision)
1085        if hash(&left) != hash(&right) {
1086            assert!(
1087                left != right,
1088                "if two value's hashes are not equal, they must not be equal"
1089            );
1090        }
1091    }
1092
1093    #[proptest]
1094    fn test_ord(left: RangeInclusiveMap<u64, u64>, right: RangeInclusiveMap<u64, u64>) {
1095        assert_eq!(
1096            left == right,
1097            left.cmp(&right).is_eq(),
1098            "ordering and equality must match"
1099        );
1100        assert_eq!(
1101            left.cmp(&right),
1102            left.partial_cmp(&right).unwrap(),
1103            "ordering is total for ordered parameters"
1104        );
1105    }
1106
1107    #[test]
1108    fn test_from_array() {
1109        let mut map = RangeInclusiveMap::new();
1110        map.insert(0..=100, "hello");
1111        map.insert(200..=300, "world");
1112        assert_eq!(
1113            map,
1114            RangeInclusiveMap::from([(0..=100, "hello"), (200..=300, "world")])
1115        );
1116    }
1117
1118    #[test]
1119    fn test_macro() {
1120        assert_eq!(
1121            range_inclusive_map![],
1122            RangeInclusiveMap::<i64, i64>::default()
1123        );
1124        assert_eq!(
1125            range_inclusive_map!(0..=100 => "abc", 100..=200 => "def", 200..=300 => "ghi"),
1126            [(0..=100, "abc"), (100..=200, "def"), (200..=300, "ghi")]
1127                .iter()
1128                .cloned()
1129                .collect(),
1130        );
1131    }
1132
1133    trait RangeInclusiveMapExt<K, V> {
1134        fn to_vec(&self) -> Vec<(RangeInclusive<K>, V)>;
1135    }
1136
1137    impl<K, V> RangeInclusiveMapExt<K, V> for RangeInclusiveMap<K, V, K>
1138    where
1139        K: Ord + Clone + StepLite,
1140        V: PartialEq + Clone,
1141    {
1142        fn to_vec(&self) -> Vec<(RangeInclusive<K>, V)> {
1143            self.iter().map(|(kr, v)| (kr.clone(), v.clone())).collect()
1144        }
1145    }
1146
1147    //
1148    // Insertion tests
1149    //
1150
1151    #[test]
1152    fn empty_map_is_empty() {
1153        let range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1154        assert_eq!(range_map.to_vec(), vec![]);
1155    }
1156
1157    #[test]
1158    fn insert_into_empty_map() {
1159        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1160        range_map.insert(0..=50, false);
1161        assert_eq!(range_map.to_vec(), vec![(0..=50, false)]);
1162    }
1163
1164    #[test]
1165    fn new_same_value_immediately_following_stored() {
1166        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1167        // 0 1 2 3 4 5 6 7 8 9
1168        // ◌ ●---● ◌ ◌ ◌ ◌ ◌ ◌
1169        range_map.insert(1..=3, false);
1170        // 0 1 2 3 4 5 6 7 8 9
1171        // ◌ ◌ ◌ ◌ ●---◌ ◌ ◌ ◌
1172        range_map.insert(4..=6, false);
1173        // 0 1 2 3 4 5 6 7 8 9
1174        // ◌ ●---------◌ ◌ ◌ ◌
1175        assert_eq!(range_map.to_vec(), vec![(1..=6, false)]);
1176    }
1177
1178    #[test]
1179    fn new_different_value_immediately_following_stored() {
1180        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1181        // 0 1 2 3 4 5 6 7 8 9
1182        // ◌ ●---● ◌ ◌ ◌ ◌ ◌ ◌
1183        range_map.insert(1..=3, false);
1184        // 0 1 2 3 4 5 6 7 8 9
1185        // ◌ ◌ ◌ ◌ ◆---◇ ◌ ◌ ◌
1186        range_map.insert(4..=6, true);
1187        // 0 1 2 3 4 5 6 7 8 9
1188        // ◌ ●---● ◌ ◌ ◌ ◌ ◌ ◌
1189        // ◌ ◌ ◌ ◌ ◆---◇ ◌ ◌ ◌
1190        assert_eq!(range_map.to_vec(), vec![(1..=3, false), (4..=6, true)]);
1191    }
1192
1193    #[test]
1194    fn new_same_value_overlapping_end_of_stored() {
1195        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1196        // 0 1 2 3 4 5 6 7 8 9
1197        // ◌ ●-----● ◌ ◌ ◌ ◌ ◌
1198        range_map.insert(1..=4, false);
1199        // 0 1 2 3 4 5 6 7 8 9
1200        // ◌ ◌ ◌ ◌ ●---● ◌ ◌ ◌
1201        range_map.insert(4..=6, false);
1202        // 0 1 2 3 4 5 6 7 8 9
1203        // ◌ ●---------● ◌ ◌ ◌
1204        assert_eq!(range_map.to_vec(), vec![(1..=6, false)]);
1205    }
1206
1207    #[test]
1208    fn new_different_value_overlapping_end_of_stored() {
1209        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1210        // 0 1 2 3 4 5 6 7 8 9
1211        // ◌ ●---● ◌ ◌ ◌ ◌ ◌ ◌
1212        range_map.insert(1..=3, false);
1213        // 0 1 2 3 4 5 6 7 8 9
1214        // ◌ ◌ ◌ ◆---◆ ◌ ◌ ◌ ◌
1215        range_map.insert(3..=5, true);
1216        // 0 1 2 3 4 5 6 7 8 9
1217        // ◌ ●-● ◌ ◌ ◌ ◌ ◌ ◌ ◌
1218        // ◌ ◌ ◌ ◆---◇ ◌ ◌ ◌ ◌
1219        assert_eq!(range_map.to_vec(), vec![(1..=2, false), (3..=5, true)]);
1220    }
1221
1222    #[test]
1223    fn new_same_value_immediately_preceding_stored() {
1224        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1225        // 0 1 2 3 4 5 6 7 8 9
1226        // ◌ ◌ ◌ ●---● ◌ ◌ ◌ ◌
1227        range_map.insert(3..=5, false);
1228        // 0 1 2 3 4 5 6 7 8 9
1229        // ◌ ●-● ◌ ◌ ◌ ◌ ◌ ◌ ◌
1230        range_map.insert(1..=2, false);
1231        // 0 1 2 3 4 5 6 7 8 9
1232        // ◌ ●-------● ◌ ◌ ◌ ◌
1233        assert_eq!(range_map.to_vec(), vec![(1..=5, false)]);
1234    }
1235
1236    #[test]
1237    fn new_different_value_immediately_preceding_stored() {
1238        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1239        // 0 1 2 3 4 5 6 7 8 9
1240        // ◌ ◌ ◌ ◆---◆ ◌ ◌ ◌ ◌
1241        range_map.insert(3..=5, true);
1242        // 0 1 2 3 4 5 6 7 8 9
1243        // ◌ ●-● ◌ ◌ ◌ ◌ ◌ ◌ ◌
1244        range_map.insert(1..=2, false);
1245        // 0 1 2 3 4 5 6 7 8 9
1246        // ◌ ●-● ◌ ◌ ◌ ◌ ◌ ◌ ◌
1247        // ◌ ◌ ◌ ◆---◇ ◌ ◌ ◌ ◌
1248        assert_eq!(range_map.to_vec(), vec![(1..=2, false), (3..=5, true)]);
1249    }
1250
1251    #[test]
1252    fn new_same_value_wholly_inside_stored() {
1253        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1254        // 0 1 2 3 4 5 6 7 8 9
1255        // ◌ ●-------● ◌ ◌ ◌ ◌
1256        range_map.insert(1..=5, false);
1257        // 0 1 2 3 4 5 6 7 8 9
1258        // ◌ ◌ ●---● ◌ ◌ ◌ ◌ ◌ ◌
1259        range_map.insert(2..=4, false);
1260        // 0 1 2 3 4 5 6 7 8 9
1261        // ◌ ●-------● ◌ ◌ ◌ ◌
1262        assert_eq!(range_map.to_vec(), vec![(1..=5, false)]);
1263    }
1264
1265    #[test]
1266    fn new_different_value_wholly_inside_stored() {
1267        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1268        // 0 1 2 3 4 5 6 7 8 9
1269        // ◌ ◆-------◆ ◌ ◌ ◌ ◌
1270        range_map.insert(1..=5, true);
1271        // 0 1 2 3 4 5 6 7 8 9
1272        // ◌ ◌ ●---● ◌ ◌ ◌ ◌ ◌ ◌
1273        range_map.insert(2..=4, false);
1274        // 0 1 2 3 4 5 6 7 8 9
1275        // ◌ ◆ ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌
1276        // ◌ ◌ ●---● ◌ ◌ ◌ ◌ ◌
1277        // ◌ ◌ ◌ ◌ ◌ ◆ ◌ ◌ ◌ ◌
1278        assert_eq!(
1279            range_map.to_vec(),
1280            vec![(1..=1, true), (2..=4, false), (5..=5, true)]
1281        );
1282    }
1283
1284    #[test]
1285    fn replace_at_end_of_existing_range_should_coalesce() {
1286        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1287        // 0 1 2 3 4 5 6 7 8 9
1288        // ◌ ●---● ◌ ◌ ◌ ◌ ◌ ◌
1289        range_map.insert(1..=3, false);
1290        // 0 1 2 3 4 5 6 7 8 9
1291        // ◌ ◌ ◌ ◌ ●---● ◌ ◌ ◌
1292        range_map.insert(4..=6, true);
1293        // 0 1 2 3 4 5 6 7 8 9
1294        // ◌ ◌ ◌ ◌ ●---● ◌ ◌ ◌
1295        range_map.insert(4..=6, false);
1296        // 0 1 2 3 4 5 6 7 8 9
1297        // ◌ ●---------● ◌ ◌ ◌
1298        assert_eq!(range_map.to_vec(), vec![(1..=6, false)]);
1299    }
1300
1301    #[test]
1302    // Test every permutation of a bunch of touching and overlapping ranges.
1303    fn lots_of_interesting_ranges() {
1304        use crate::dense::DenseU32RangeMap;
1305        use permutator::Permutation;
1306
1307        let mut ranges_with_values = [
1308            (2..=3, false),
1309            // A duplicate range
1310            (2..=3, false),
1311            // Almost a duplicate, but with a different value
1312            (2..=3, true),
1313            // A few small ranges, some of them overlapping others,
1314            // some of them touching others
1315            (3..=5, true),
1316            (4..=6, true),
1317            (6..=7, true),
1318            // A really big range
1319            (2..=6, true),
1320        ];
1321
1322        ranges_with_values.permutation().for_each(|permutation| {
1323            let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1324            let mut dense: DenseU32RangeMap<bool> = DenseU32RangeMap::new();
1325
1326            for (k, v) in permutation {
1327                // Insert it into both maps.
1328                range_map.insert(k.clone(), v);
1329                dense.insert(k, v);
1330
1331                // At every step, both maps should contain the same stuff.
1332                let sparse = range_map.to_vec();
1333                let dense = dense.to_vec();
1334                assert_eq!(sparse, dense);
1335            }
1336        });
1337    }
1338
1339    //
1340    // Get* tests
1341    //
1342
1343    #[test]
1344    fn get() {
1345        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1346        range_map.insert(0..=50, false);
1347        assert_eq!(range_map.get(&50), Some(&false));
1348        assert_eq!(range_map.get(&51), None);
1349    }
1350
1351    #[test]
1352    fn get_key_value() {
1353        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1354        range_map.insert(0..=50, false);
1355        assert_eq!(range_map.get_key_value(&50), Some((&(0..=50), &false)));
1356        assert_eq!(range_map.get_key_value(&51), None);
1357    }
1358
1359    //
1360    // Removal tests
1361    //
1362
1363    #[test]
1364    fn remove_from_empty_map() {
1365        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1366        range_map.remove(0..=50);
1367        assert_eq!(range_map.to_vec(), vec![]);
1368    }
1369
1370    #[test]
1371    fn remove_non_covered_range_before_stored() {
1372        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1373        range_map.insert(25..=75, false);
1374        range_map.remove(0..=24);
1375        assert_eq!(range_map.to_vec(), vec![(25..=75, false)]);
1376    }
1377
1378    #[test]
1379    fn remove_non_covered_range_after_stored() {
1380        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1381        range_map.insert(25..=75, false);
1382        range_map.remove(76..=100);
1383        assert_eq!(range_map.to_vec(), vec![(25..=75, false)]);
1384    }
1385
1386    #[test]
1387    fn remove_overlapping_start_of_stored() {
1388        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1389        range_map.insert(25..=75, false);
1390        range_map.remove(0..=25);
1391        assert_eq!(range_map.to_vec(), vec![(26..=75, false)]);
1392    }
1393
1394    #[test]
1395    fn remove_middle_of_stored() {
1396        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1397        range_map.insert(25..=75, false);
1398        range_map.remove(30..=70);
1399        assert_eq!(range_map.to_vec(), vec![(25..=29, false), (71..=75, false)]);
1400    }
1401
1402    #[test]
1403    fn remove_overlapping_end_of_stored() {
1404        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1405        range_map.insert(25..=75, false);
1406        range_map.remove(75..=100);
1407        assert_eq!(range_map.to_vec(), vec![(25..=74, false)]);
1408    }
1409
1410    #[test]
1411    fn remove_exactly_stored() {
1412        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1413        range_map.insert(25..=75, false);
1414        range_map.remove(25..=75);
1415        assert_eq!(range_map.to_vec(), vec![]);
1416    }
1417
1418    #[test]
1419    fn remove_superset_of_stored() {
1420        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1421        range_map.insert(25..=75, false);
1422        range_map.remove(0..=100);
1423        assert_eq!(range_map.to_vec(), vec![]);
1424    }
1425
1426    //
1427    // Test extremes of key ranges; we do addition/subtraction in
1428    // the range domain so I want to make sure I haven't accidentally
1429    // introduced some arithmetic overflow there.
1430    //
1431
1432    #[test]
1433    fn no_overflow_at_key_domain_extremes() {
1434        let mut range_map: RangeInclusiveMap<u8, bool> = RangeInclusiveMap::new();
1435        range_map.insert(0..=255, false);
1436        range_map.insert(0..=10, true);
1437        range_map.insert(245..=255, true);
1438        range_map.remove(0..=5);
1439        range_map.remove(0..=5);
1440        range_map.remove(250..=255);
1441        range_map.remove(250..=255);
1442        range_map.insert(0..=255, true);
1443        range_map.remove(1..=254);
1444        range_map.insert(254..=254, true);
1445        range_map.insert(255..=255, true);
1446        range_map.insert(255..=255, false);
1447        range_map.insert(0..=0, false);
1448        range_map.insert(1..=1, true);
1449        range_map.insert(0..=0, true);
1450    }
1451
1452    // Gaps tests
1453
1454    #[test]
1455    fn whole_range_is_a_gap() {
1456        // 0 1 2 3 4 5 6 7 8 9
1457        // ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌
1458        let range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1459        // 0 1 2 3 4 5 6 7 8 9
1460        // ◌ ◆-------------◆ ◌
1461        let outer_range = 1..=8;
1462        let mut gaps = range_map.gaps(&outer_range);
1463        // Should yield the entire outer range.
1464        assert_eq!(gaps.next(), Some(1..=8));
1465        assert_eq!(gaps.next(), None);
1466        // Gaps iterator should be fused.
1467        assert_eq!(gaps.next(), None);
1468        assert_eq!(gaps.next(), None);
1469    }
1470
1471    #[test]
1472    fn whole_range_is_covered_exactly() {
1473        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1474        // 0 1 2 3 4 5 6 7 8 9
1475        // ◌ ●---------● ◌ ◌ ◌
1476        range_map.insert(1..=6, ());
1477        // 0 1 2 3 4 5 6 7 8 9
1478        // ◌ ◆---------◆ ◌ ◌ ◌
1479        let outer_range = 1..=6;
1480        let mut gaps = range_map.gaps(&outer_range);
1481        // Should yield no gaps.
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    #[test]
1489    fn item_before_outer_range() {
1490        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1491        // 0 1 2 3 4 5 6 7 8 9
1492        // ◌ ●---● ◌ ◌ ◌ ◌ ◌ ◌
1493        range_map.insert(1..=3, ());
1494        // 0 1 2 3 4 5 6 7 8 9
1495        // ◌ ◌ ◌ ◌ ◌ ◆-----◆ ◌
1496        let outer_range = 5..=8;
1497        let mut gaps = range_map.gaps(&outer_range);
1498        // Should yield the entire outer range.
1499        assert_eq!(gaps.next(), Some(5..=8));
1500        assert_eq!(gaps.next(), None);
1501        // Gaps iterator should be fused.
1502        assert_eq!(gaps.next(), None);
1503        assert_eq!(gaps.next(), None);
1504    }
1505
1506    #[test]
1507    fn item_touching_start_of_outer_range() {
1508        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1509        // 0 1 2 3 4 5 6 7 8 9
1510        // ◌ ●-----● ◌ ◌ ◌ ◌ ◌
1511        range_map.insert(1..=4, ());
1512        // 0 1 2 3 4 5 6 7 8 9
1513        // ◌ ◌ ◌ ◌ ◌ ◆-----◆ ◌
1514        let outer_range = 5..=8;
1515        let mut gaps = range_map.gaps(&outer_range);
1516        // Should yield the entire outer range.
1517        assert_eq!(gaps.next(), Some(5..=8));
1518        assert_eq!(gaps.next(), None);
1519        // Gaps iterator should be fused.
1520        assert_eq!(gaps.next(), None);
1521        assert_eq!(gaps.next(), None);
1522    }
1523
1524    #[test]
1525    fn item_overlapping_start_of_outer_range() {
1526        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1527        // 0 1 2 3 4 5 6 7 8 9
1528        // ◌ ●-------● ◌ ◌ ◌ ◌
1529        range_map.insert(1..=5, ());
1530        // 0 1 2 3 4 5 6 7 8 9
1531        // ◌ ◌ ◌ ◌ ◌ ◆-----◆ ◌
1532        let outer_range = 5..=8;
1533        let mut gaps = range_map.gaps(&outer_range);
1534        // Should yield from just past the end of the stored item
1535        // to the end of the outer range.
1536        assert_eq!(gaps.next(), Some(6..=8));
1537        assert_eq!(gaps.next(), None);
1538        // Gaps iterator should be fused.
1539        assert_eq!(gaps.next(), None);
1540        assert_eq!(gaps.next(), None);
1541    }
1542
1543    #[test]
1544    fn item_starting_at_start_of_outer_range() {
1545        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1546        // 0 1 2 3 4 5 6 7 8 9
1547        // ◌ ◌ ◌ ◌ ◌ ●-● ◌ ◌ ◌
1548        range_map.insert(5..=6, ());
1549        // 0 1 2 3 4 5 6 7 8 9
1550        // ◌ ◌ ◌ ◌ ◌ ◆-----◆ ◌
1551        let outer_range = 5..=8;
1552        let mut gaps = range_map.gaps(&outer_range);
1553        // Should yield from just past the item onwards.
1554        assert_eq!(gaps.next(), Some(7..=8));
1555        assert_eq!(gaps.next(), None);
1556        // Gaps iterator should be fused.
1557        assert_eq!(gaps.next(), None);
1558        assert_eq!(gaps.next(), None);
1559    }
1560
1561    #[test]
1562    fn items_floating_inside_outer_range() {
1563        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1564        // 0 1 2 3 4 5 6 7 8 9
1565        // ◌ ◌ ◌ ◌ ◌ ◌ ●-● ◌ ◌
1566        range_map.insert(6..=7, ());
1567        // 0 1 2 3 4 5 6 7 8 9
1568        // ◌ ◌ ◌ ●-● ◌ ◌ ◌ ◌ ◌
1569        range_map.insert(3..=4, ());
1570        // 0 1 2 3 4 5 6 7 8 9
1571        // ◌ ◆-------------◆ ◌
1572        let outer_range = 1..=8;
1573        let mut gaps = range_map.gaps(&outer_range);
1574        // Should yield gaps at start, between items,
1575        // and at end.
1576        assert_eq!(gaps.next(), Some(1..=2));
1577        assert_eq!(gaps.next(), Some(5..=5));
1578        assert_eq!(gaps.next(), Some(8..=8));
1579        assert_eq!(gaps.next(), None);
1580        // Gaps iterator should be fused.
1581        assert_eq!(gaps.next(), None);
1582        assert_eq!(gaps.next(), None);
1583    }
1584
1585    #[test]
1586    fn item_ending_at_end_of_outer_range() {
1587        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1588        // 0 1 2 3 4 5 6 7 8 9
1589        // ◌ ◌ ◌ ◌ ◌ ◌ ◌ ●-● ◌
1590        range_map.insert(7..=8, ());
1591        // 0 1 2 3 4 5 6 7 8 9
1592        // ◌ ◌ ◌ ◌ ◌ ◆-----◆ ◌
1593        let outer_range = 5..=8;
1594        let mut gaps = range_map.gaps(&outer_range);
1595        // Should yield from the start of the outer range
1596        // up to just before the start of the stored item.
1597        assert_eq!(gaps.next(), Some(5..=6));
1598        assert_eq!(gaps.next(), None);
1599        // Gaps iterator should be fused.
1600        assert_eq!(gaps.next(), None);
1601        assert_eq!(gaps.next(), None);
1602    }
1603
1604    #[test]
1605    fn item_overlapping_end_of_outer_range() {
1606        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1607        // 0 1 2 3 4 5 6 7 8 9
1608        // ◌ ◌ ◌ ◌ ◌ ●---● ◌ ◌
1609        range_map.insert(5..=6, ());
1610        // 0 1 2 3 4 5 6 7 8 9
1611        // ◌ ◌ ◆-----◆ ◌ ◌ ◌ ◌
1612        let outer_range = 2..=5;
1613        let mut gaps = range_map.gaps(&outer_range);
1614        // Should yield from the start of the outer range
1615        // up to the start of the stored item.
1616        assert_eq!(gaps.next(), Some(2..=4));
1617        assert_eq!(gaps.next(), None);
1618        // Gaps iterator should be fused.
1619        assert_eq!(gaps.next(), None);
1620        assert_eq!(gaps.next(), None);
1621    }
1622
1623    #[test]
1624    fn item_touching_end_of_outer_range() {
1625        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1626        // 0 1 2 3 4 5 6 7 8 9
1627        // ◌ ◌ ◌ ◌ ◌ ●-----● ◌
1628        range_map.insert(5..=9, ());
1629        // 0 1 2 3 4 5 6 7 8 9
1630        // ◌ ◆-----◆ ◌ ◌ ◌ ◌ ◌
1631        let outer_range = 1..=4;
1632        let mut gaps = range_map.gaps(&outer_range);
1633        // Should yield the entire outer range.
1634        assert_eq!(gaps.next(), Some(1..=4));
1635        assert_eq!(gaps.next(), None);
1636        // Gaps iterator should be fused.
1637        assert_eq!(gaps.next(), None);
1638        assert_eq!(gaps.next(), None);
1639    }
1640
1641    #[test]
1642    fn item_after_outer_range() {
1643        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1644        // 0 1 2 3 4 5 6 7 8 9
1645        // ◌ ◌ ◌ ◌ ◌ ◌ ●---● ◌
1646        range_map.insert(6..=7, ());
1647        // 0 1 2 3 4 5 6 7 8 9
1648        // ◌ ◆-----◆ ◌ ◌ ◌ ◌ ◌
1649        let outer_range = 1..=4;
1650        let mut gaps = range_map.gaps(&outer_range);
1651        // Should yield the entire outer range.
1652        assert_eq!(gaps.next(), Some(1..=4));
1653        assert_eq!(gaps.next(), None);
1654        // Gaps iterator should be fused.
1655        assert_eq!(gaps.next(), None);
1656        assert_eq!(gaps.next(), None);
1657    }
1658
1659    #[test]
1660    fn zero_width_outer_range_with_items_away_from_both_sides() {
1661        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1662        // 0 1 2 3 4 5 6 7 8 9
1663        // ◌ ◆---◆ ◌ ◌ ◌ ◌ ◌ ◌
1664        range_map.insert(1..=3, ());
1665        // 0 1 2 3 4 5 6 7 8 9
1666        // ◌ ◌ ◌ ◌ ◌ ◆---◆ ◌ ◌
1667        range_map.insert(5..=7, ());
1668        // 0 1 2 3 4 5 6 7 8 9
1669        // ◌ ◌ ◌ ◌ ◆ ◌ ◌ ◌ ◌ ◌
1670        let outer_range = 4..=4;
1671        let mut gaps = range_map.gaps(&outer_range);
1672        // Should yield a zero-width gap.
1673        assert_eq!(gaps.next(), Some(4..=4));
1674        // Gaps iterator should be fused.
1675        assert_eq!(gaps.next(), None);
1676        assert_eq!(gaps.next(), None);
1677    }
1678
1679    #[test]
1680    fn zero_width_outer_range_with_items_touching_both_sides() {
1681        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1682        // 0 1 2 3 4 5 6 7 8 9
1683        // ◌ ◌ ◆-◆ ◌ ◌ ◌ ◌ ◌ ◌ ◌
1684        range_map.insert(2..=3, ());
1685        // 0 1 2 3 4 5 6 7 8 9
1686        // ◌ ◌ ◌ ◌ ◌ ◆---◆ ◌ ◌ ◌
1687        range_map.insert(5..=6, ());
1688        // 0 1 2 3 4 5 6 7 8 9
1689        // ◌ ◌ ◌ ◌ ◆ ◌ ◌ ◌ ◌ ◌
1690        let outer_range = 4..=4;
1691        let mut gaps = range_map.gaps(&outer_range);
1692        // Should yield no gaps.
1693        assert_eq!(gaps.next(), Some(4..=4));
1694        // Gaps iterator should be fused.
1695        assert_eq!(gaps.next(), None);
1696        assert_eq!(gaps.next(), None);
1697    }
1698
1699    #[test]
1700    fn empty_outer_range_with_item_straddling() {
1701        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1702        // 0 1 2 3 4 5 6 7 8 9
1703        // ◌ ◌ ◆-----◆ ◌ ◌ ◌ ◌ ◌
1704        range_map.insert(2..=5, ());
1705        // 0 1 2 3 4 5 6 7 8 9
1706        // ◌ ◌ ◌ ◌ ◆ ◌ ◌ ◌ ◌ ◌
1707        let outer_range = 4..=4;
1708        let mut gaps = range_map.gaps(&outer_range);
1709        // Should yield no gaps.
1710        assert_eq!(gaps.next(), None);
1711        // Gaps iterator should be fused.
1712        assert_eq!(gaps.next(), None);
1713        assert_eq!(gaps.next(), None);
1714    }
1715
1716    #[test]
1717    fn no_empty_gaps() {
1718        // Make two ranges different values so they don't
1719        // get coalesced.
1720        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1721        // 0 1 2 3 4 5 6 7 8 9
1722        // ◌ ◌ ◌ ◌ ◆-◆ ◌ ◌ ◌ ◌
1723        range_map.insert(4..=5, true);
1724        // 0 1 2 3 4 5 6 7 8 9
1725        // ◌ ◌ ◆-◆ ◌ ◌ ◌ ◌ ◌ ◌
1726        range_map.insert(2..=3, false);
1727        // 0 1 2 3 4 5 6 7 8 9
1728        // ◌ ●-------------● ◌
1729        let outer_range = 1..=8;
1730        let mut gaps = range_map.gaps(&outer_range);
1731        // Should yield gaps at start and end, but not between the
1732        // two touching items.
1733        assert_eq!(gaps.next(), Some(1..=1));
1734        assert_eq!(gaps.next(), Some(6..=8));
1735        assert_eq!(gaps.next(), None);
1736        // Gaps iterator should be fused.
1737        assert_eq!(gaps.next(), None);
1738        assert_eq!(gaps.next(), None);
1739    }
1740
1741    #[test]
1742    fn no_overflow_finding_gaps_at_key_domain_extremes() {
1743        // Items and outer range both at extremes.
1744        let mut range_map: RangeInclusiveMap<u8, bool> = RangeInclusiveMap::new();
1745        range_map.insert(0..=255, false);
1746        range_map.gaps(&(0..=255));
1747
1748        // Items at extremes with gaps in middle.
1749        let mut range_map: RangeInclusiveMap<u8, bool> = RangeInclusiveMap::new();
1750        range_map.insert(0..=255, false);
1751        range_map.gaps(&(0..=5));
1752        range_map.gaps(&(250..=255));
1753
1754        // Items just in from extremes.
1755        let mut range_map: RangeInclusiveMap<u8, bool> = RangeInclusiveMap::new();
1756        range_map.insert(0..=255, false);
1757        range_map.gaps(&(1..=5));
1758        range_map.gaps(&(250..=254));
1759
1760        // Outer range just in from extremes,
1761        // items at extremes.
1762        let mut range_map: RangeInclusiveMap<u8, bool> = RangeInclusiveMap::new();
1763        range_map.insert(1..=254, false);
1764        range_map.gaps(&(0..=5));
1765        range_map.gaps(&(250..=255));
1766    }
1767
1768    #[test]
1769    fn adjacent_unit_width_items() {
1770        // Items two items next to each other at the start, and at the end.
1771        let mut range_map: RangeInclusiveMap<u8, bool> = RangeInclusiveMap::new();
1772        range_map.insert(0..=0, false);
1773        range_map.insert(1..=1, true);
1774        range_map.insert(254..=254, false);
1775        range_map.insert(255..=255, true);
1776
1777        let outer_range = 0..=255;
1778        let mut gaps = range_map.gaps(&outer_range);
1779        // Should yield one big gap in the middle.
1780        assert_eq!(gaps.next(), Some(2..=253));
1781        // Gaps iterator should be fused.
1782        assert_eq!(gaps.next(), None);
1783        assert_eq!(gaps.next(), None);
1784    }
1785
1786    // Overlapping tests
1787
1788    #[test]
1789    fn overlapping_ref_with_empty_map() {
1790        // 0 1 2 3 4 5 6 7 8 9
1791        // ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌
1792        let range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1793        // 0 1 2 3 4 5 6 7 8 9
1794        // ◌ ◆-------------◆ ◌
1795        let query_range = 1..=8;
1796        let mut overlapping = range_map.overlapping(&query_range);
1797        // Should not yield any items.
1798        assert_eq!(overlapping.next(), None);
1799        // Gaps iterator should be fused.
1800        assert_eq!(overlapping.next(), None);
1801    }
1802
1803    #[test]
1804    fn overlapping_owned_with_empty_map() {
1805        // 0 1 2 3 4 5 6 7 8 9
1806        // ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌
1807        let range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1808        // 0 1 2 3 4 5 6 7 8 9
1809        // ◌ ◆-------------◆ ◌
1810        let query_range = 1..=8;
1811        let mut overlapping = range_map.overlapping(query_range);
1812        // Should not yield any items.
1813        assert_eq!(overlapping.next(), None);
1814        // Gaps iterator should be fused.
1815        assert_eq!(overlapping.next(), None);
1816    }
1817
1818    #[test]
1819    fn overlapping_partial_edges_complete_middle() {
1820        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1821
1822        // 0 1 2 3 4 5 6 7 8 9
1823        // ●-● ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌
1824        range_map.insert(0..=1, ());
1825        // 0 1 2 3 4 5 6 7 8 9
1826        // ◌ ◌ ◌ ●-● ◌ ◌ ◌ ◌ ◌
1827        range_map.insert(3..=4, ());
1828        // 0 1 2 3 4 5 6 7 8 9
1829        // ◌ ◌ ◌ ◌ ◌ ◌ ●-● ◌ ◌
1830        range_map.insert(6..=7, ());
1831
1832        // 0 1 2 3 4 5 6 7 8 9
1833        // ◌ ◆---------◆ ◌ ◌ ◌
1834        let query_range = 1..=6;
1835
1836        let mut overlapping = range_map.overlapping(&query_range);
1837
1838        // Should yield partially overlapped range at start.
1839        assert_eq!(overlapping.next(), Some((&(0..=1), &())));
1840        // Should yield completely overlapped range in middle.
1841        assert_eq!(overlapping.next(), Some((&(3..=4), &())));
1842        // Should yield partially overlapped range at end.
1843        assert_eq!(overlapping.next(), Some((&(6..=7), &())));
1844        // Gaps iterator should be fused.
1845        assert_eq!(overlapping.next(), None);
1846        assert_eq!(overlapping.next(), None);
1847    }
1848
1849    #[test]
1850    fn overlapping_non_overlapping_edges_complete_middle() {
1851        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1852
1853        // 0 1 2 3 4 5 6 7 8 9
1854        // ●-● ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌
1855        range_map.insert(0..=1, ());
1856        // 0 1 2 3 4 5 6 7 8 9
1857        // ◌ ◌ ◌ ●-● ◌ ◌ ◌ ◌ ◌
1858        range_map.insert(3..=4, ());
1859        // 0 1 2 3 4 5 6 7 8 9
1860        // ◌ ◌ ◌ ◌ ◌ ◌ ●-● ◌ ◌
1861        range_map.insert(6..=7, ());
1862
1863        // 0 1 2 3 4 5 6 7 8 9
1864        // ◌ ◌ ◆-----◆ ◌ ◌ ◌ ◌
1865        let query_range = 2..=5;
1866
1867        let mut overlapping = range_map.overlapping(&query_range);
1868
1869        // Should only yield the completely overlapped range in middle.
1870        // (Not the ranges that are touched by not covered to either side.)
1871        assert_eq!(overlapping.next(), Some((&(3..=4), &())));
1872        // Gaps iterator should be fused.
1873        assert_eq!(overlapping.next(), None);
1874        assert_eq!(overlapping.next(), None);
1875    }
1876
1877    ///
1878    /// impl Debug
1879    ///
1880
1881    #[test]
1882    fn map_debug_repr_looks_right() {
1883        let mut map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1884
1885        // Empty
1886        assert_eq!(format!("{:?}", map), "{}");
1887
1888        // One entry
1889        map.insert(2..=5, ());
1890        assert_eq!(format!("{:?}", map), "{2..=5: ()}");
1891
1892        // Many entries
1893        map.insert(7..=8, ());
1894        map.insert(10..=11, ());
1895        assert_eq!(format!("{:?}", map), "{2..=5: (), 7..=8: (), 10..=11: ()}");
1896    }
1897
1898    // impl Default where T: ?Default
1899
1900    #[test]
1901    fn always_default() {
1902        struct NoDefault;
1903        RangeInclusiveMap::<NoDefault, NoDefault>::default();
1904    }
1905
1906    // impl Serialize
1907
1908    #[cfg(feature = "serde1")]
1909    #[test]
1910    fn serialization() {
1911        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1912        // 0 1 2 3 4 5 6 7 8 9
1913        // ◌ ◆---◆ ◌ ◌ ◌ ◌ ◌ ◌
1914        range_map.insert(1..=3, false);
1915        // 0 1 2 3 4 5 6 7 8 9
1916        // ◌ ◌ ◌ ◌ ◌ ◆---◆ ◌ ◌
1917        range_map.insert(5..=7, true);
1918        let output = serde_json::to_string(&range_map).expect("Failed to serialize");
1919        assert_eq!(output, "[[[1,3],false],[[5,7],true]]");
1920    }
1921
1922    // impl Deserialize
1923
1924    #[cfg(feature = "serde1")]
1925    #[test]
1926    fn deserialization() {
1927        let input = "[[[1,3],false],[[5,7],true]]";
1928        let range_map: RangeInclusiveMap<u32, bool> =
1929            serde_json::from_str(input).expect("Failed to deserialize");
1930        let reserialized = serde_json::to_string(&range_map).expect("Failed to re-serialize");
1931        assert_eq!(reserialized, input);
1932    }
1933
1934    // const fn
1935
1936    #[cfg(feature = "const_fn")]
1937    const _MAP: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1938    #[cfg(feature = "const_fn")]
1939    const _MAP2: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new_with_step_fns();
1940
1941    #[cfg(feature = "quickcheck")]
1942    quickcheck::quickcheck! {
1943        fn prop(xs: RangeInclusiveMap<usize, usize>) -> bool {
1944            xs == xs
1945        }
1946    }
1947}