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