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 + Eq,
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: Eq + 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: Eq + 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>>>(&self, range: R) -> Overlapping<K, V, R> {
563        // Find the first matching stored range by its _end_,
564        // using sneaky layering and `Borrow` implementation. (See `range_wrappers` module.)
565        let start_sliver = RangeInclusiveEndWrapper::new(
566            range.borrow().start().clone()..=range.borrow().start().clone(),
567        );
568        let btm_range_iter = self
569            .btm
570            .range::<RangeInclusiveEndWrapper<K>, RangeFrom<&RangeInclusiveEndWrapper<K>>>(
571                &start_sliver..,
572            );
573        Overlapping {
574            query_range: range,
575            btm_range_iter,
576        }
577    }
578
579    /// Returns `true` if any range in the map completely or partially
580    /// overlaps the given range.
581    pub fn overlaps(&self, range: &RangeInclusive<K>) -> bool {
582        self.overlapping(range).next().is_some()
583    }
584
585    /// Returns the first range-value pair in this map, if one exists. The range in this pair is the
586    /// minimum range in the map.
587    pub fn first_range_value(&self) -> Option<(&RangeInclusive<K>, &V)> {
588        self.btm
589            .first_key_value()
590            .map(|(range, value)| (&range.end_wrapper.range, value))
591    }
592
593    /// Returns the last range-value pair in this map, if one exists. The range in this pair is the
594    /// maximum range in the map.
595    pub fn last_range_value(&self) -> Option<(&RangeInclusive<K>, &V)> {
596        self.btm
597            .last_key_value()
598            .map(|(range, value)| (&range.end_wrapper.range, value))
599    }
600}
601
602/// An iterator over the entries of a `RangeInclusiveMap`, ordered by key range.
603///
604/// The iterator element type is `(&'a RangeInclusive<K>, &'a V)`.
605///
606/// This `struct` is created by the [`iter`] method on [`RangeInclusiveMap`]. See its
607/// documentation for more.
608///
609/// [`iter`]: RangeInclusiveMap::iter
610pub struct Iter<'a, K, V> {
611    inner: alloc::collections::btree_map::Iter<'a, RangeInclusiveStartWrapper<K>, V>,
612}
613
614impl<'a, K, V> Iterator for Iter<'a, K, V>
615where
616    K: 'a,
617    V: 'a,
618{
619    type Item = (&'a RangeInclusive<K>, &'a V);
620
621    fn next(&mut self) -> Option<Self::Item> {
622        self.inner.next().map(|(by_start, v)| (&by_start.range, v))
623    }
624
625    fn size_hint(&self) -> (usize, Option<usize>) {
626        self.inner.size_hint()
627    }
628}
629
630impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V>
631where
632    K: 'a,
633    V: 'a,
634{
635    fn next_back(&mut self) -> Option<Self::Item> {
636        self.inner
637            .next_back()
638            .map(|(range, value)| (&range.end_wrapper.range, value))
639    }
640}
641
642/// An owning iterator over the entries of a `RangeInclusiveMap`, ordered by key range.
643///
644/// The iterator element type is `(RangeInclusive<K>, V)`.
645///
646/// This `struct` is created by the [`into_iter`] method on [`RangeInclusiveMap`]
647/// (provided by the `IntoIterator` trait). See its documentation for more.
648///
649/// [`into_iter`]: IntoIterator::into_iter
650pub struct IntoIter<K, V> {
651    inner: alloc::collections::btree_map::IntoIter<RangeInclusiveStartWrapper<K>, V>,
652}
653
654impl<K, V> IntoIterator for RangeInclusiveMap<K, V> {
655    type Item = (RangeInclusive<K>, V);
656    type IntoIter = IntoIter<K, V>;
657    fn into_iter(self) -> Self::IntoIter {
658        IntoIter {
659            inner: self.btm.into_iter(),
660        }
661    }
662}
663
664impl<K, V> Iterator for IntoIter<K, V> {
665    type Item = (RangeInclusive<K>, V);
666    fn next(&mut self) -> Option<(RangeInclusive<K>, V)> {
667        self.inner
668            .next()
669            .map(|(by_start, v)| (by_start.end_wrapper.range, v))
670    }
671    fn size_hint(&self) -> (usize, Option<usize>) {
672        self.inner.size_hint()
673    }
674}
675
676impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
677    fn next_back(&mut self) -> Option<Self::Item> {
678        self.inner
679            .next_back()
680            .map(|(range, value)| (range.end_wrapper.range, value))
681    }
682}
683
684// We can't just derive this automatically, because that would
685// expose irrelevant (and private) implementation details.
686// Instead implement it in the same way that the underlying BTreeMap does.
687impl<K: Debug, V: Debug> Debug for RangeInclusiveMap<K, V>
688where
689    K: Ord + Clone + StepLite,
690    V: Eq + Clone,
691{
692    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
693        f.debug_map().entries(self.iter()).finish()
694    }
695}
696
697impl<K, V> FromIterator<(RangeInclusive<K>, V)> for RangeInclusiveMap<K, V>
698where
699    K: Ord + Clone + StepLite,
700    V: Eq + Clone,
701{
702    fn from_iter<T: IntoIterator<Item = (RangeInclusive<K>, V)>>(iter: T) -> Self {
703        let mut range_map = RangeInclusiveMap::new();
704        range_map.extend(iter);
705        range_map
706    }
707}
708
709impl<K, V> Extend<(RangeInclusive<K>, V)> for RangeInclusiveMap<K, V>
710where
711    K: Ord + Clone + StepLite,
712    V: Eq + Clone,
713{
714    fn extend<T: IntoIterator<Item = (RangeInclusive<K>, V)>>(&mut self, iter: T) {
715        iter.into_iter().for_each(move |(k, v)| {
716            self.insert(k, v);
717        })
718    }
719}
720
721#[cfg(feature = "serde1")]
722impl<K, V> Serialize for RangeInclusiveMap<K, V>
723where
724    K: Ord + Clone + StepLite + Serialize,
725    V: Eq + Clone + Serialize,
726{
727    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
728    where
729        S: Serializer,
730    {
731        use serde::ser::SerializeSeq;
732        let mut seq = serializer.serialize_seq(Some(self.btm.len()))?;
733        for (k, v) in self.iter() {
734            seq.serialize_element(&((k.start(), k.end()), &v))?;
735        }
736        seq.end()
737    }
738}
739
740#[cfg(feature = "serde1")]
741impl<'de, K, V> Deserialize<'de> for RangeInclusiveMap<K, V>
742where
743    K: Ord + Clone + StepLite + Deserialize<'de>,
744    V: Eq + Clone + Deserialize<'de>,
745{
746    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
747    where
748        D: Deserializer<'de>,
749    {
750        deserializer.deserialize_seq(RangeInclusiveMapVisitor::new())
751    }
752}
753
754#[cfg(feature = "serde1")]
755struct RangeInclusiveMapVisitor<K, V> {
756    marker: PhantomData<fn() -> RangeInclusiveMap<K, V>>,
757}
758
759#[cfg(feature = "serde1")]
760impl<K, V> RangeInclusiveMapVisitor<K, V> {
761    fn new() -> Self {
762        RangeInclusiveMapVisitor {
763            marker: PhantomData,
764        }
765    }
766}
767
768#[cfg(feature = "serde1")]
769impl<'de, K, V> Visitor<'de> for RangeInclusiveMapVisitor<K, V>
770where
771    K: Ord + Clone + StepLite + Deserialize<'de>,
772    V: Eq + Clone + Deserialize<'de>,
773{
774    type Value = RangeInclusiveMap<K, V>;
775
776    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
777        formatter.write_str("RangeInclusiveMap")
778    }
779
780    fn visit_seq<A>(self, mut access: A) -> Result<Self::Value, A::Error>
781    where
782        A: SeqAccess<'de>,
783    {
784        let mut range_inclusive_map = RangeInclusiveMap::new();
785        while let Some(((start, end), value)) = access.next_element()? {
786            range_inclusive_map.insert(start..=end, value);
787        }
788        Ok(range_inclusive_map)
789    }
790}
791
792/// An iterator over all ranges not covered by a `RangeInclusiveMap`.
793///
794/// The iterator element type is `RangeInclusive<K>`.
795///
796/// This `struct` is created by the [`gaps`] method on [`RangeInclusiveMap`]. See its
797/// documentation for more.
798///
799/// [`gaps`]: RangeInclusiveMap::gaps
800pub struct Gaps<'a, K, V, StepFnsT> {
801    /// Would be redundant, but we need an extra flag to
802    /// avoid overflowing when dealing with inclusive ranges.
803    ///
804    /// All other things here are ignored if `done` is `true`.
805    candidate_needs_plus_one: bool,
806    candidate_start: &'a K,
807    query_end: &'a K,
808    btm_range_iter: alloc::collections::btree_map::Range<'a, RangeInclusiveStartWrapper<K>, V>,
809    _phantom: PhantomData<StepFnsT>,
810}
811
812// `Gaps` is always fused. (See definition of `next` below.)
813impl<'a, K, V, StepFnsT> core::iter::FusedIterator for Gaps<'a, K, V, StepFnsT>
814where
815    K: Ord + Clone,
816    StepFnsT: StepFns<K>,
817{
818}
819
820impl<'a, K, V, StepFnsT> Iterator for Gaps<'a, K, V, StepFnsT>
821where
822    K: Ord + Clone,
823    StepFnsT: StepFns<K>,
824{
825    type Item = RangeInclusive<K>;
826
827    fn next(&mut self) -> Option<Self::Item> {
828        for overlap in self.btm_range_iter.by_ref() {
829            let overlap = overlap.0;
830
831            // If the range in the map has advanced beyond the query range, return
832            // any tail gap.
833            if *self.query_end < *overlap.start() {
834                break;
835            }
836
837            let candidate_needs_plus_one =
838                core::mem::replace(&mut self.candidate_needs_plus_one, true);
839
840            let cur_candidate_start = core::mem::replace(&mut self.candidate_start, overlap.end());
841
842            let cur_candidate_start = if candidate_needs_plus_one {
843                StepFnsT::add_one(cur_candidate_start)
844            } else {
845                cur_candidate_start.clone()
846            };
847
848            if cur_candidate_start < *overlap.start() {
849                let gap = cur_candidate_start..=StepFnsT::sub_one(overlap.start());
850                return Some(gap);
851            }
852        }
853
854        // Now that we've run out of items, the only other possible
855        // gap is one at the end of the outer range.
856        let candidate_needs_plus_one = core::mem::replace(&mut self.candidate_needs_plus_one, true);
857
858        let cur_candidate_start = core::mem::replace(&mut self.candidate_start, self.query_end);
859        if candidate_needs_plus_one {
860            if *cur_candidate_start < *self.query_end {
861                return Some(StepFnsT::add_one(cur_candidate_start)..=self.query_end.clone());
862            }
863        } else if *cur_candidate_start <= *self.query_end {
864            // There's a gap at the end!
865            return Some(cur_candidate_start.clone()..=self.query_end.clone());
866        }
867
868        None
869    }
870}
871
872/// An iterator over all stored ranges partially or completely
873/// overlapped by a given range.
874///
875/// The iterator element type is `(&'a RangeInclusive<K>, &'a V)`.
876///
877/// This `struct` is created by the [`overlapping`] method on [`RangeInclusiveMap`]. See its
878/// documentation for more.
879///
880/// [`overlapping`]: RangeInclusiveMap::overlapping
881pub struct Overlapping<'a, K, V, R: Borrow<RangeInclusive<K>> = &'a RangeInclusive<K>> {
882    query_range: R,
883    btm_range_iter: alloc::collections::btree_map::Range<'a, RangeInclusiveStartWrapper<K>, V>,
884}
885
886// `Overlapping` is always fused. (See definition of `next` below.)
887impl<'a, K, V, R: Borrow<RangeInclusive<K>>> core::iter::FusedIterator for Overlapping<'a, K, V, R> where
888    K: Ord + Clone
889{
890}
891
892impl<'a, K, V, R: Borrow<RangeInclusive<K>>> Iterator for Overlapping<'a, K, V, R>
893where
894    K: Ord + Clone,
895{
896    type Item = (&'a RangeInclusive<K>, &'a V);
897
898    fn next(&mut self) -> Option<Self::Item> {
899        if let Some((k, v)) = self.btm_range_iter.next() {
900            if k.start() <= self.query_range.borrow().end() {
901                Some((&k.range, v))
902            } else {
903                // The rest of the items in the underlying iterator
904                // are past the query range. We can keep taking items
905                // from that iterator and this will remain true,
906                // so this is enough to make the iterator fused.
907                None
908            }
909        } else {
910            None
911        }
912    }
913}
914
915impl<'a, K, V, R: Borrow<RangeInclusive<K>>> DoubleEndedIterator for Overlapping<'a, K, V, R>
916where
917    K: Ord + Clone,
918{
919    fn next_back(&mut self) -> Option<Self::Item> {
920        while let Some((k, v)) = self.btm_range_iter.next_back() {
921            if k.start() <= self.query_range.borrow().end() {
922                return Some((&k.range, v));
923            }
924        }
925
926        None
927    }
928}
929
930impl<K: Ord + Clone + StepLite, V: Eq + Clone, const N: usize> From<[(RangeInclusive<K>, V); N]>
931    for RangeInclusiveMap<K, V>
932{
933    fn from(value: [(RangeInclusive<K>, V); N]) -> Self {
934        let mut map = Self::new();
935        for (range, value) in IntoIterator::into_iter(value) {
936            map.insert(range, value);
937        }
938        map
939    }
940}
941
942/// Create a [`RangeInclusiveMap`] from key-value pairs.
943///
944/// # Example
945///
946/// ```rust
947/// # use rangemap::range_inclusive_map;
948/// let map = range_inclusive_map!{
949///     0..=100 => "abc",
950///     100..=200 => "def",
951///     200..=300 => "ghi"
952/// };
953/// ```
954#[macro_export]
955macro_rules! range_inclusive_map {
956    ($($k:expr => $v:expr),* $(,)?) => {{
957        $crate::RangeInclusiveMap::from([$(($k, $v)),*])
958    }};
959}
960
961#[cfg(test)]
962mod tests {
963    use super::*;
964    use alloc as std;
965    use alloc::{format, string::String, vec, vec::Vec};
966    use proptest::prelude::*;
967    use test_strategy::proptest;
968
969    impl<K, V> Arbitrary for RangeInclusiveMap<K, V>
970    where
971        K: Ord + Clone + Debug + StepLite + Arbitrary + 'static,
972        V: Clone + Eq + Arbitrary + 'static,
973    {
974        type Parameters = ();
975        type Strategy = BoxedStrategy<Self>;
976
977        fn arbitrary_with(_parameters: Self::Parameters) -> Self::Strategy {
978            any::<Vec<(RangeInclusive<K>, V)>>()
979                .prop_map(|ranges| ranges.into_iter().collect::<RangeInclusiveMap<K, V>>())
980                .boxed()
981        }
982    }
983
984    #[proptest]
985    #[allow(clippy::len_zero)]
986    fn test_len(mut map: RangeInclusiveMap<u64, String>) {
987        assert_eq!(map.len(), map.iter().count());
988        assert_eq!(map.is_empty(), map.len() == 0);
989        map.clear();
990        assert_eq!(map.len(), 0);
991        assert!(map.is_empty());
992        assert_eq!(map.iter().count(), 0);
993    }
994
995    #[proptest]
996    fn test_first(set: RangeInclusiveMap<u64, String>) {
997        assert_eq!(
998            set.first_range_value(),
999            set.iter().min_by_key(|(range, _)| range.start())
1000        );
1001    }
1002
1003    #[proptest]
1004    fn test_last(set: RangeInclusiveMap<u64, String>) {
1005        assert_eq!(
1006            set.last_range_value(),
1007            set.iter().max_by_key(|(range, _)| range.end())
1008        );
1009    }
1010
1011    #[proptest]
1012    fn test_iter_reversible(set: RangeInclusiveMap<u64, String>) {
1013        let forward: Vec<_> = set.iter().collect();
1014        let mut backward: Vec<_> = set.iter().rev().collect();
1015        backward.reverse();
1016        assert_eq!(forward, backward);
1017    }
1018
1019    #[proptest]
1020    fn test_into_iter_reversible(set: RangeInclusiveMap<u64, String>) {
1021        let forward: Vec<_> = set.clone().into_iter().collect();
1022        let mut backward: Vec<_> = set.into_iter().rev().collect();
1023        backward.reverse();
1024        assert_eq!(forward, backward);
1025    }
1026
1027    #[proptest]
1028    fn test_overlapping_reversible(
1029        set: RangeInclusiveMap<u64, String>,
1030        range: RangeInclusive<u64>,
1031    ) {
1032        let forward: Vec<_> = set.overlapping(&range).collect();
1033        let mut backward: Vec<_> = set.overlapping(&range).rev().collect();
1034        backward.reverse();
1035        assert_eq!(forward, backward);
1036    }
1037
1038    #[proptest]
1039    fn test_arbitrary_map_u8(ranges: Vec<(RangeInclusive<u8>, String)>) {
1040        let ranges: Vec<_> = ranges
1041            .into_iter()
1042            .filter(|(range, _value)| range.start() != range.end())
1043            .collect();
1044        let set = ranges
1045            .iter()
1046            .fold(RangeInclusiveMap::new(), |mut set, (range, value)| {
1047                set.insert(range.clone(), value.clone());
1048                set
1049            });
1050
1051        for value in 0..u8::MAX {
1052            assert_eq!(
1053                set.get(&value),
1054                ranges
1055                    .iter()
1056                    .rev()
1057                    .find(|(range, _value)| range.contains(&value))
1058                    .map(|(_range, value)| value)
1059            );
1060        }
1061    }
1062
1063    #[proptest]
1064    #[allow(deprecated)]
1065    fn test_hash(left: RangeInclusiveMap<u64, u64>, right: RangeInclusiveMap<u64, u64>) {
1066        use core::hash::{Hash, Hasher, SipHasher};
1067
1068        let hash = |set: &RangeInclusiveMap<_, _>| {
1069            let mut hasher = SipHasher::new();
1070            set.hash(&mut hasher);
1071            hasher.finish()
1072        };
1073
1074        if left == right {
1075            assert!(
1076                hash(&left) == hash(&right),
1077                "if two values are equal, their hash must be equal"
1078            );
1079        }
1080
1081        // if the hashes are equal the values might not be the same (collision)
1082        if hash(&left) != hash(&right) {
1083            assert!(
1084                left != right,
1085                "if two value's hashes are not equal, they must not be equal"
1086            );
1087        }
1088    }
1089
1090    #[proptest]
1091    fn test_ord(left: RangeInclusiveMap<u64, u64>, right: RangeInclusiveMap<u64, u64>) {
1092        assert_eq!(
1093            left == right,
1094            left.cmp(&right).is_eq(),
1095            "ordering and equality must match"
1096        );
1097        assert_eq!(
1098            left.cmp(&right),
1099            left.partial_cmp(&right).unwrap(),
1100            "ordering is total for ordered parameters"
1101        );
1102    }
1103
1104    #[test]
1105    fn test_from_array() {
1106        let mut map = RangeInclusiveMap::new();
1107        map.insert(0..=100, "hello");
1108        map.insert(200..=300, "world");
1109        assert_eq!(
1110            map,
1111            RangeInclusiveMap::from([(0..=100, "hello"), (200..=300, "world")])
1112        );
1113    }
1114
1115    #[test]
1116    fn test_macro() {
1117        assert_eq!(
1118            range_inclusive_map![],
1119            RangeInclusiveMap::<i64, i64>::default()
1120        );
1121        assert_eq!(
1122            range_inclusive_map!(0..=100 => "abc", 100..=200 => "def", 200..=300 => "ghi"),
1123            [(0..=100, "abc"), (100..=200, "def"), (200..=300, "ghi")]
1124                .iter()
1125                .cloned()
1126                .collect(),
1127        );
1128    }
1129
1130    trait RangeInclusiveMapExt<K, V> {
1131        fn to_vec(&self) -> Vec<(RangeInclusive<K>, V)>;
1132    }
1133
1134    impl<K, V> RangeInclusiveMapExt<K, V> for RangeInclusiveMap<K, V, K>
1135    where
1136        K: Ord + Clone + StepLite,
1137        V: Eq + Clone,
1138    {
1139        fn to_vec(&self) -> Vec<(RangeInclusive<K>, V)> {
1140            self.iter().map(|(kr, v)| (kr.clone(), v.clone())).collect()
1141        }
1142    }
1143
1144    //
1145    // Insertion tests
1146    //
1147
1148    #[test]
1149    fn empty_map_is_empty() {
1150        let range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1151        assert_eq!(range_map.to_vec(), vec![]);
1152    }
1153
1154    #[test]
1155    fn insert_into_empty_map() {
1156        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1157        range_map.insert(0..=50, false);
1158        assert_eq!(range_map.to_vec(), vec![(0..=50, false)]);
1159    }
1160
1161    #[test]
1162    fn new_same_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, false);
1170        // 0 1 2 3 4 5 6 7 8 9
1171        // ◌ ●---------◌ ◌ ◌ ◌
1172        assert_eq!(range_map.to_vec(), vec![(1..=6, false)]);
1173    }
1174
1175    #[test]
1176    fn new_different_value_immediately_following_stored() {
1177        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1178        // 0 1 2 3 4 5 6 7 8 9
1179        // ◌ ●---● ◌ ◌ ◌ ◌ ◌ ◌
1180        range_map.insert(1..=3, false);
1181        // 0 1 2 3 4 5 6 7 8 9
1182        // ◌ ◌ ◌ ◌ ◆---◇ ◌ ◌ ◌
1183        range_map.insert(4..=6, true);
1184        // 0 1 2 3 4 5 6 7 8 9
1185        // ◌ ●---● ◌ ◌ ◌ ◌ ◌ ◌
1186        // ◌ ◌ ◌ ◌ ◆---◇ ◌ ◌ ◌
1187        assert_eq!(range_map.to_vec(), vec![(1..=3, false), (4..=6, true)]);
1188    }
1189
1190    #[test]
1191    fn new_same_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..=4, false);
1196        // 0 1 2 3 4 5 6 7 8 9
1197        // ◌ ◌ ◌ ◌ ●---● ◌ ◌ ◌
1198        range_map.insert(4..=6, false);
1199        // 0 1 2 3 4 5 6 7 8 9
1200        // ◌ ●---------● ◌ ◌ ◌
1201        assert_eq!(range_map.to_vec(), vec![(1..=6, false)]);
1202    }
1203
1204    #[test]
1205    fn new_different_value_overlapping_end_of_stored() {
1206        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1207        // 0 1 2 3 4 5 6 7 8 9
1208        // ◌ ●---● ◌ ◌ ◌ ◌ ◌ ◌
1209        range_map.insert(1..=3, false);
1210        // 0 1 2 3 4 5 6 7 8 9
1211        // ◌ ◌ ◌ ◆---◆ ◌ ◌ ◌ ◌
1212        range_map.insert(3..=5, true);
1213        // 0 1 2 3 4 5 6 7 8 9
1214        // ◌ ●-● ◌ ◌ ◌ ◌ ◌ ◌ ◌
1215        // ◌ ◌ ◌ ◆---◇ ◌ ◌ ◌ ◌
1216        assert_eq!(range_map.to_vec(), vec![(1..=2, false), (3..=5, true)]);
1217    }
1218
1219    #[test]
1220    fn new_same_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, false);
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        assert_eq!(range_map.to_vec(), vec![(1..=5, false)]);
1231    }
1232
1233    #[test]
1234    fn new_different_value_immediately_preceding_stored() {
1235        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1236        // 0 1 2 3 4 5 6 7 8 9
1237        // ◌ ◌ ◌ ◆---◆ ◌ ◌ ◌ ◌
1238        range_map.insert(3..=5, true);
1239        // 0 1 2 3 4 5 6 7 8 9
1240        // ◌ ●-● ◌ ◌ ◌ ◌ ◌ ◌ ◌
1241        range_map.insert(1..=2, false);
1242        // 0 1 2 3 4 5 6 7 8 9
1243        // ◌ ●-● ◌ ◌ ◌ ◌ ◌ ◌ ◌
1244        // ◌ ◌ ◌ ◆---◇ ◌ ◌ ◌ ◌
1245        assert_eq!(range_map.to_vec(), vec![(1..=2, false), (3..=5, true)]);
1246    }
1247
1248    #[test]
1249    fn new_same_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, false);
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        assert_eq!(range_map.to_vec(), vec![(1..=5, false)]);
1260    }
1261
1262    #[test]
1263    fn new_different_value_wholly_inside_stored() {
1264        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1265        // 0 1 2 3 4 5 6 7 8 9
1266        // ◌ ◆-------◆ ◌ ◌ ◌ ◌
1267        range_map.insert(1..=5, true);
1268        // 0 1 2 3 4 5 6 7 8 9
1269        // ◌ ◌ ●---● ◌ ◌ ◌ ◌ ◌ ◌
1270        range_map.insert(2..=4, false);
1271        // 0 1 2 3 4 5 6 7 8 9
1272        // ◌ ◆ ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌
1273        // ◌ ◌ ●---● ◌ ◌ ◌ ◌ ◌
1274        // ◌ ◌ ◌ ◌ ◌ ◆ ◌ ◌ ◌ ◌
1275        assert_eq!(
1276            range_map.to_vec(),
1277            vec![(1..=1, true), (2..=4, false), (5..=5, true)]
1278        );
1279    }
1280
1281    #[test]
1282    fn replace_at_end_of_existing_range_should_coalesce() {
1283        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1284        // 0 1 2 3 4 5 6 7 8 9
1285        // ◌ ●---● ◌ ◌ ◌ ◌ ◌ ◌
1286        range_map.insert(1..=3, false);
1287        // 0 1 2 3 4 5 6 7 8 9
1288        // ◌ ◌ ◌ ◌ ●---● ◌ ◌ ◌
1289        range_map.insert(4..=6, true);
1290        // 0 1 2 3 4 5 6 7 8 9
1291        // ◌ ◌ ◌ ◌ ●---● ◌ ◌ ◌
1292        range_map.insert(4..=6, false);
1293        // 0 1 2 3 4 5 6 7 8 9
1294        // ◌ ●---------● ◌ ◌ ◌
1295        assert_eq!(range_map.to_vec(), vec![(1..=6, false)]);
1296    }
1297
1298    #[test]
1299    // Test every permutation of a bunch of touching and overlapping ranges.
1300    fn lots_of_interesting_ranges() {
1301        use crate::dense::DenseU32RangeMap;
1302        use permutator::Permutation;
1303
1304        let mut ranges_with_values = [
1305            (2..=3, false),
1306            // A duplicate range
1307            (2..=3, false),
1308            // Almost a duplicate, but with a different value
1309            (2..=3, true),
1310            // A few small ranges, some of them overlapping others,
1311            // some of them touching others
1312            (3..=5, true),
1313            (4..=6, true),
1314            (6..=7, true),
1315            // A really big range
1316            (2..=6, true),
1317        ];
1318
1319        ranges_with_values.permutation().for_each(|permutation| {
1320            let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1321            let mut dense: DenseU32RangeMap<bool> = DenseU32RangeMap::new();
1322
1323            for (k, v) in permutation {
1324                // Insert it into both maps.
1325                range_map.insert(k.clone(), v);
1326                dense.insert(k, v);
1327
1328                // At every step, both maps should contain the same stuff.
1329                let sparse = range_map.to_vec();
1330                let dense = dense.to_vec();
1331                assert_eq!(sparse, dense);
1332            }
1333        });
1334    }
1335
1336    //
1337    // Get* tests
1338    //
1339
1340    #[test]
1341    fn get() {
1342        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1343        range_map.insert(0..=50, false);
1344        assert_eq!(range_map.get(&50), Some(&false));
1345        assert_eq!(range_map.get(&51), None);
1346    }
1347
1348    #[test]
1349    fn get_key_value() {
1350        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1351        range_map.insert(0..=50, false);
1352        assert_eq!(range_map.get_key_value(&50), Some((&(0..=50), &false)));
1353        assert_eq!(range_map.get_key_value(&51), None);
1354    }
1355
1356    //
1357    // Removal tests
1358    //
1359
1360    #[test]
1361    fn remove_from_empty_map() {
1362        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1363        range_map.remove(0..=50);
1364        assert_eq!(range_map.to_vec(), vec![]);
1365    }
1366
1367    #[test]
1368    fn remove_non_covered_range_before_stored() {
1369        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1370        range_map.insert(25..=75, false);
1371        range_map.remove(0..=24);
1372        assert_eq!(range_map.to_vec(), vec![(25..=75, false)]);
1373    }
1374
1375    #[test]
1376    fn remove_non_covered_range_after_stored() {
1377        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1378        range_map.insert(25..=75, false);
1379        range_map.remove(76..=100);
1380        assert_eq!(range_map.to_vec(), vec![(25..=75, false)]);
1381    }
1382
1383    #[test]
1384    fn remove_overlapping_start_of_stored() {
1385        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1386        range_map.insert(25..=75, false);
1387        range_map.remove(0..=25);
1388        assert_eq!(range_map.to_vec(), vec![(26..=75, false)]);
1389    }
1390
1391    #[test]
1392    fn remove_middle_of_stored() {
1393        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1394        range_map.insert(25..=75, false);
1395        range_map.remove(30..=70);
1396        assert_eq!(range_map.to_vec(), vec![(25..=29, false), (71..=75, false)]);
1397    }
1398
1399    #[test]
1400    fn remove_overlapping_end_of_stored() {
1401        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1402        range_map.insert(25..=75, false);
1403        range_map.remove(75..=100);
1404        assert_eq!(range_map.to_vec(), vec![(25..=74, false)]);
1405    }
1406
1407    #[test]
1408    fn remove_exactly_stored() {
1409        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1410        range_map.insert(25..=75, false);
1411        range_map.remove(25..=75);
1412        assert_eq!(range_map.to_vec(), vec![]);
1413    }
1414
1415    #[test]
1416    fn remove_superset_of_stored() {
1417        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1418        range_map.insert(25..=75, false);
1419        range_map.remove(0..=100);
1420        assert_eq!(range_map.to_vec(), vec![]);
1421    }
1422
1423    //
1424    // Test extremes of key ranges; we do addition/subtraction in
1425    // the range domain so I want to make sure I haven't accidentally
1426    // introduced some arithmetic overflow there.
1427    //
1428
1429    #[test]
1430    fn no_overflow_at_key_domain_extremes() {
1431        let mut range_map: RangeInclusiveMap<u8, bool> = RangeInclusiveMap::new();
1432        range_map.insert(0..=255, false);
1433        range_map.insert(0..=10, true);
1434        range_map.insert(245..=255, true);
1435        range_map.remove(0..=5);
1436        range_map.remove(0..=5);
1437        range_map.remove(250..=255);
1438        range_map.remove(250..=255);
1439        range_map.insert(0..=255, true);
1440        range_map.remove(1..=254);
1441        range_map.insert(254..=254, true);
1442        range_map.insert(255..=255, true);
1443        range_map.insert(255..=255, false);
1444        range_map.insert(0..=0, false);
1445        range_map.insert(1..=1, true);
1446        range_map.insert(0..=0, true);
1447    }
1448
1449    // Gaps tests
1450
1451    #[test]
1452    fn whole_range_is_a_gap() {
1453        // 0 1 2 3 4 5 6 7 8 9
1454        // ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌
1455        let range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1456        // 0 1 2 3 4 5 6 7 8 9
1457        // ◌ ◆-------------◆ ◌
1458        let outer_range = 1..=8;
1459        let mut gaps = range_map.gaps(&outer_range);
1460        // Should yield the entire outer range.
1461        assert_eq!(gaps.next(), Some(1..=8));
1462        assert_eq!(gaps.next(), None);
1463        // Gaps iterator should be fused.
1464        assert_eq!(gaps.next(), None);
1465        assert_eq!(gaps.next(), None);
1466    }
1467
1468    #[test]
1469    fn whole_range_is_covered_exactly() {
1470        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1471        // 0 1 2 3 4 5 6 7 8 9
1472        // ◌ ●---------● ◌ ◌ ◌
1473        range_map.insert(1..=6, ());
1474        // 0 1 2 3 4 5 6 7 8 9
1475        // ◌ ◆---------◆ ◌ ◌ ◌
1476        let outer_range = 1..=6;
1477        let mut gaps = range_map.gaps(&outer_range);
1478        // Should yield no gaps.
1479        assert_eq!(gaps.next(), None);
1480        // Gaps iterator should be fused.
1481        assert_eq!(gaps.next(), None);
1482        assert_eq!(gaps.next(), None);
1483    }
1484
1485    #[test]
1486    fn item_before_outer_range() {
1487        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1488        // 0 1 2 3 4 5 6 7 8 9
1489        // ◌ ●---● ◌ ◌ ◌ ◌ ◌ ◌
1490        range_map.insert(1..=3, ());
1491        // 0 1 2 3 4 5 6 7 8 9
1492        // ◌ ◌ ◌ ◌ ◌ ◆-----◆ ◌
1493        let outer_range = 5..=8;
1494        let mut gaps = range_map.gaps(&outer_range);
1495        // Should yield the entire outer range.
1496        assert_eq!(gaps.next(), Some(5..=8));
1497        assert_eq!(gaps.next(), None);
1498        // Gaps iterator should be fused.
1499        assert_eq!(gaps.next(), None);
1500        assert_eq!(gaps.next(), None);
1501    }
1502
1503    #[test]
1504    fn item_touching_start_of_outer_range() {
1505        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1506        // 0 1 2 3 4 5 6 7 8 9
1507        // ◌ ●-----● ◌ ◌ ◌ ◌ ◌
1508        range_map.insert(1..=4, ());
1509        // 0 1 2 3 4 5 6 7 8 9
1510        // ◌ ◌ ◌ ◌ ◌ ◆-----◆ ◌
1511        let outer_range = 5..=8;
1512        let mut gaps = range_map.gaps(&outer_range);
1513        // Should yield the entire outer range.
1514        assert_eq!(gaps.next(), Some(5..=8));
1515        assert_eq!(gaps.next(), None);
1516        // Gaps iterator should be fused.
1517        assert_eq!(gaps.next(), None);
1518        assert_eq!(gaps.next(), None);
1519    }
1520
1521    #[test]
1522    fn item_overlapping_start_of_outer_range() {
1523        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1524        // 0 1 2 3 4 5 6 7 8 9
1525        // ◌ ●-------● ◌ ◌ ◌ ◌
1526        range_map.insert(1..=5, ());
1527        // 0 1 2 3 4 5 6 7 8 9
1528        // ◌ ◌ ◌ ◌ ◌ ◆-----◆ ◌
1529        let outer_range = 5..=8;
1530        let mut gaps = range_map.gaps(&outer_range);
1531        // Should yield from just past the end of the stored item
1532        // to the end of the outer range.
1533        assert_eq!(gaps.next(), Some(6..=8));
1534        assert_eq!(gaps.next(), None);
1535        // Gaps iterator should be fused.
1536        assert_eq!(gaps.next(), None);
1537        assert_eq!(gaps.next(), None);
1538    }
1539
1540    #[test]
1541    fn item_starting_at_start_of_outer_range() {
1542        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1543        // 0 1 2 3 4 5 6 7 8 9
1544        // ◌ ◌ ◌ ◌ ◌ ●-● ◌ ◌ ◌
1545        range_map.insert(5..=6, ());
1546        // 0 1 2 3 4 5 6 7 8 9
1547        // ◌ ◌ ◌ ◌ ◌ ◆-----◆ ◌
1548        let outer_range = 5..=8;
1549        let mut gaps = range_map.gaps(&outer_range);
1550        // Should yield from just past the item onwards.
1551        assert_eq!(gaps.next(), Some(7..=8));
1552        assert_eq!(gaps.next(), None);
1553        // Gaps iterator should be fused.
1554        assert_eq!(gaps.next(), None);
1555        assert_eq!(gaps.next(), None);
1556    }
1557
1558    #[test]
1559    fn items_floating_inside_outer_range() {
1560        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1561        // 0 1 2 3 4 5 6 7 8 9
1562        // ◌ ◌ ◌ ◌ ◌ ◌ ●-● ◌ ◌
1563        range_map.insert(6..=7, ());
1564        // 0 1 2 3 4 5 6 7 8 9
1565        // ◌ ◌ ◌ ●-● ◌ ◌ ◌ ◌ ◌
1566        range_map.insert(3..=4, ());
1567        // 0 1 2 3 4 5 6 7 8 9
1568        // ◌ ◆-------------◆ ◌
1569        let outer_range = 1..=8;
1570        let mut gaps = range_map.gaps(&outer_range);
1571        // Should yield gaps at start, between items,
1572        // and at end.
1573        assert_eq!(gaps.next(), Some(1..=2));
1574        assert_eq!(gaps.next(), Some(5..=5));
1575        assert_eq!(gaps.next(), Some(8..=8));
1576        assert_eq!(gaps.next(), None);
1577        // Gaps iterator should be fused.
1578        assert_eq!(gaps.next(), None);
1579        assert_eq!(gaps.next(), None);
1580    }
1581
1582    #[test]
1583    fn item_ending_at_end_of_outer_range() {
1584        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1585        // 0 1 2 3 4 5 6 7 8 9
1586        // ◌ ◌ ◌ ◌ ◌ ◌ ◌ ●-● ◌
1587        range_map.insert(7..=8, ());
1588        // 0 1 2 3 4 5 6 7 8 9
1589        // ◌ ◌ ◌ ◌ ◌ ◆-----◆ ◌
1590        let outer_range = 5..=8;
1591        let mut gaps = range_map.gaps(&outer_range);
1592        // Should yield from the start of the outer range
1593        // up to just before the start of the stored item.
1594        assert_eq!(gaps.next(), Some(5..=6));
1595        assert_eq!(gaps.next(), None);
1596        // Gaps iterator should be fused.
1597        assert_eq!(gaps.next(), None);
1598        assert_eq!(gaps.next(), None);
1599    }
1600
1601    #[test]
1602    fn item_overlapping_end_of_outer_range() {
1603        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1604        // 0 1 2 3 4 5 6 7 8 9
1605        // ◌ ◌ ◌ ◌ ◌ ●---● ◌ ◌
1606        range_map.insert(5..=6, ());
1607        // 0 1 2 3 4 5 6 7 8 9
1608        // ◌ ◌ ◆-----◆ ◌ ◌ ◌ ◌
1609        let outer_range = 2..=5;
1610        let mut gaps = range_map.gaps(&outer_range);
1611        // Should yield from the start of the outer range
1612        // up to the start of the stored item.
1613        assert_eq!(gaps.next(), Some(2..=4));
1614        assert_eq!(gaps.next(), None);
1615        // Gaps iterator should be fused.
1616        assert_eq!(gaps.next(), None);
1617        assert_eq!(gaps.next(), None);
1618    }
1619
1620    #[test]
1621    fn item_touching_end_of_outer_range() {
1622        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1623        // 0 1 2 3 4 5 6 7 8 9
1624        // ◌ ◌ ◌ ◌ ◌ ●-----● ◌
1625        range_map.insert(5..=9, ());
1626        // 0 1 2 3 4 5 6 7 8 9
1627        // ◌ ◆-----◆ ◌ ◌ ◌ ◌ ◌
1628        let outer_range = 1..=4;
1629        let mut gaps = range_map.gaps(&outer_range);
1630        // Should yield the entire outer range.
1631        assert_eq!(gaps.next(), Some(1..=4));
1632        assert_eq!(gaps.next(), None);
1633        // Gaps iterator should be fused.
1634        assert_eq!(gaps.next(), None);
1635        assert_eq!(gaps.next(), None);
1636    }
1637
1638    #[test]
1639    fn item_after_outer_range() {
1640        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1641        // 0 1 2 3 4 5 6 7 8 9
1642        // ◌ ◌ ◌ ◌ ◌ ◌ ●---● ◌
1643        range_map.insert(6..=7, ());
1644        // 0 1 2 3 4 5 6 7 8 9
1645        // ◌ ◆-----◆ ◌ ◌ ◌ ◌ ◌
1646        let outer_range = 1..=4;
1647        let mut gaps = range_map.gaps(&outer_range);
1648        // Should yield the entire outer range.
1649        assert_eq!(gaps.next(), Some(1..=4));
1650        assert_eq!(gaps.next(), None);
1651        // Gaps iterator should be fused.
1652        assert_eq!(gaps.next(), None);
1653        assert_eq!(gaps.next(), None);
1654    }
1655
1656    #[test]
1657    fn zero_width_outer_range_with_items_away_from_both_sides() {
1658        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1659        // 0 1 2 3 4 5 6 7 8 9
1660        // ◌ ◆---◆ ◌ ◌ ◌ ◌ ◌ ◌
1661        range_map.insert(1..=3, ());
1662        // 0 1 2 3 4 5 6 7 8 9
1663        // ◌ ◌ ◌ ◌ ◌ ◆---◆ ◌ ◌
1664        range_map.insert(5..=7, ());
1665        // 0 1 2 3 4 5 6 7 8 9
1666        // ◌ ◌ ◌ ◌ ◆ ◌ ◌ ◌ ◌ ◌
1667        let outer_range = 4..=4;
1668        let mut gaps = range_map.gaps(&outer_range);
1669        // Should yield a zero-width gap.
1670        assert_eq!(gaps.next(), Some(4..=4));
1671        // Gaps iterator should be fused.
1672        assert_eq!(gaps.next(), None);
1673        assert_eq!(gaps.next(), None);
1674    }
1675
1676    #[test]
1677    fn zero_width_outer_range_with_items_touching_both_sides() {
1678        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1679        // 0 1 2 3 4 5 6 7 8 9
1680        // ◌ ◌ ◆-◆ ◌ ◌ ◌ ◌ ◌ ◌ ◌
1681        range_map.insert(2..=3, ());
1682        // 0 1 2 3 4 5 6 7 8 9
1683        // ◌ ◌ ◌ ◌ ◌ ◆---◆ ◌ ◌ ◌
1684        range_map.insert(5..=6, ());
1685        // 0 1 2 3 4 5 6 7 8 9
1686        // ◌ ◌ ◌ ◌ ◆ ◌ ◌ ◌ ◌ ◌
1687        let outer_range = 4..=4;
1688        let mut gaps = range_map.gaps(&outer_range);
1689        // Should yield no gaps.
1690        assert_eq!(gaps.next(), Some(4..=4));
1691        // Gaps iterator should be fused.
1692        assert_eq!(gaps.next(), None);
1693        assert_eq!(gaps.next(), None);
1694    }
1695
1696    #[test]
1697    fn empty_outer_range_with_item_straddling() {
1698        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1699        // 0 1 2 3 4 5 6 7 8 9
1700        // ◌ ◌ ◆-----◆ ◌ ◌ ◌ ◌ ◌
1701        range_map.insert(2..=5, ());
1702        // 0 1 2 3 4 5 6 7 8 9
1703        // ◌ ◌ ◌ ◌ ◆ ◌ ◌ ◌ ◌ ◌
1704        let outer_range = 4..=4;
1705        let mut gaps = range_map.gaps(&outer_range);
1706        // Should yield no gaps.
1707        assert_eq!(gaps.next(), None);
1708        // Gaps iterator should be fused.
1709        assert_eq!(gaps.next(), None);
1710        assert_eq!(gaps.next(), None);
1711    }
1712
1713    #[test]
1714    fn no_empty_gaps() {
1715        // Make two ranges different values so they don't
1716        // get coalesced.
1717        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1718        // 0 1 2 3 4 5 6 7 8 9
1719        // ◌ ◌ ◌ ◌ ◆-◆ ◌ ◌ ◌ ◌
1720        range_map.insert(4..=5, true);
1721        // 0 1 2 3 4 5 6 7 8 9
1722        // ◌ ◌ ◆-◆ ◌ ◌ ◌ ◌ ◌ ◌
1723        range_map.insert(2..=3, false);
1724        // 0 1 2 3 4 5 6 7 8 9
1725        // ◌ ●-------------● ◌
1726        let outer_range = 1..=8;
1727        let mut gaps = range_map.gaps(&outer_range);
1728        // Should yield gaps at start and end, but not between the
1729        // two touching items.
1730        assert_eq!(gaps.next(), Some(1..=1));
1731        assert_eq!(gaps.next(), Some(6..=8));
1732        assert_eq!(gaps.next(), None);
1733        // Gaps iterator should be fused.
1734        assert_eq!(gaps.next(), None);
1735        assert_eq!(gaps.next(), None);
1736    }
1737
1738    #[test]
1739    fn no_overflow_finding_gaps_at_key_domain_extremes() {
1740        // Items and outer range both at extremes.
1741        let mut range_map: RangeInclusiveMap<u8, bool> = RangeInclusiveMap::new();
1742        range_map.insert(0..=255, false);
1743        range_map.gaps(&(0..=255));
1744
1745        // Items at extremes with gaps in middle.
1746        let mut range_map: RangeInclusiveMap<u8, bool> = RangeInclusiveMap::new();
1747        range_map.insert(0..=255, false);
1748        range_map.gaps(&(0..=5));
1749        range_map.gaps(&(250..=255));
1750
1751        // Items just in from extremes.
1752        let mut range_map: RangeInclusiveMap<u8, bool> = RangeInclusiveMap::new();
1753        range_map.insert(0..=255, false);
1754        range_map.gaps(&(1..=5));
1755        range_map.gaps(&(250..=254));
1756
1757        // Outer range just in from extremes,
1758        // items at extremes.
1759        let mut range_map: RangeInclusiveMap<u8, bool> = RangeInclusiveMap::new();
1760        range_map.insert(1..=254, false);
1761        range_map.gaps(&(0..=5));
1762        range_map.gaps(&(250..=255));
1763    }
1764
1765    #[test]
1766    fn adjacent_unit_width_items() {
1767        // Items two items next to each other at the start, and at the end.
1768        let mut range_map: RangeInclusiveMap<u8, bool> = RangeInclusiveMap::new();
1769        range_map.insert(0..=0, false);
1770        range_map.insert(1..=1, true);
1771        range_map.insert(254..=254, false);
1772        range_map.insert(255..=255, true);
1773
1774        let outer_range = 0..=255;
1775        let mut gaps = range_map.gaps(&outer_range);
1776        // Should yield one big gap in the middle.
1777        assert_eq!(gaps.next(), Some(2..=253));
1778        // Gaps iterator should be fused.
1779        assert_eq!(gaps.next(), None);
1780        assert_eq!(gaps.next(), None);
1781    }
1782
1783    // Overlapping tests
1784
1785    #[test]
1786    fn overlapping_ref_with_empty_map() {
1787        // 0 1 2 3 4 5 6 7 8 9
1788        // ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌
1789        let range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1790        // 0 1 2 3 4 5 6 7 8 9
1791        // ◌ ◆-------------◆ ◌
1792        let query_range = 1..=8;
1793        let mut overlapping = range_map.overlapping(&query_range);
1794        // Should not yield any items.
1795        assert_eq!(overlapping.next(), None);
1796        // Gaps iterator should be fused.
1797        assert_eq!(overlapping.next(), None);
1798    }
1799
1800    #[test]
1801    fn overlapping_owned_with_empty_map() {
1802        // 0 1 2 3 4 5 6 7 8 9
1803        // ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌
1804        let range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1805        // 0 1 2 3 4 5 6 7 8 9
1806        // ◌ ◆-------------◆ ◌
1807        let query_range = 1..=8;
1808        let mut overlapping = range_map.overlapping(query_range);
1809        // Should not yield any items.
1810        assert_eq!(overlapping.next(), None);
1811        // Gaps iterator should be fused.
1812        assert_eq!(overlapping.next(), None);
1813    }
1814
1815    #[test]
1816    fn overlapping_partial_edges_complete_middle() {
1817        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1818
1819        // 0 1 2 3 4 5 6 7 8 9
1820        // ●-● ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌
1821        range_map.insert(0..=1, ());
1822        // 0 1 2 3 4 5 6 7 8 9
1823        // ◌ ◌ ◌ ●-● ◌ ◌ ◌ ◌ ◌
1824        range_map.insert(3..=4, ());
1825        // 0 1 2 3 4 5 6 7 8 9
1826        // ◌ ◌ ◌ ◌ ◌ ◌ ●-● ◌ ◌
1827        range_map.insert(6..=7, ());
1828
1829        // 0 1 2 3 4 5 6 7 8 9
1830        // ◌ ◆---------◆ ◌ ◌ ◌
1831        let query_range = 1..=6;
1832
1833        let mut overlapping = range_map.overlapping(&query_range);
1834
1835        // Should yield partially overlapped range at start.
1836        assert_eq!(overlapping.next(), Some((&(0..=1), &())));
1837        // Should yield completely overlapped range in middle.
1838        assert_eq!(overlapping.next(), Some((&(3..=4), &())));
1839        // Should yield partially overlapped range at end.
1840        assert_eq!(overlapping.next(), Some((&(6..=7), &())));
1841        // Gaps iterator should be fused.
1842        assert_eq!(overlapping.next(), None);
1843        assert_eq!(overlapping.next(), None);
1844    }
1845
1846    #[test]
1847    fn overlapping_non_overlapping_edges_complete_middle() {
1848        let mut range_map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1849
1850        // 0 1 2 3 4 5 6 7 8 9
1851        // ●-● ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌
1852        range_map.insert(0..=1, ());
1853        // 0 1 2 3 4 5 6 7 8 9
1854        // ◌ ◌ ◌ ●-● ◌ ◌ ◌ ◌ ◌
1855        range_map.insert(3..=4, ());
1856        // 0 1 2 3 4 5 6 7 8 9
1857        // ◌ ◌ ◌ ◌ ◌ ◌ ●-● ◌ ◌
1858        range_map.insert(6..=7, ());
1859
1860        // 0 1 2 3 4 5 6 7 8 9
1861        // ◌ ◌ ◆-----◆ ◌ ◌ ◌ ◌
1862        let query_range = 2..=5;
1863
1864        let mut overlapping = range_map.overlapping(&query_range);
1865
1866        // Should only yield the completely overlapped range in middle.
1867        // (Not the ranges that are touched by not covered to either side.)
1868        assert_eq!(overlapping.next(), Some((&(3..=4), &())));
1869        // Gaps iterator should be fused.
1870        assert_eq!(overlapping.next(), None);
1871        assert_eq!(overlapping.next(), None);
1872    }
1873
1874    ///
1875    /// impl Debug
1876    ///
1877
1878    #[test]
1879    fn map_debug_repr_looks_right() {
1880        let mut map: RangeInclusiveMap<u32, ()> = RangeInclusiveMap::new();
1881
1882        // Empty
1883        assert_eq!(format!("{:?}", map), "{}");
1884
1885        // One entry
1886        map.insert(2..=5, ());
1887        assert_eq!(format!("{:?}", map), "{2..=5: ()}");
1888
1889        // Many entries
1890        map.insert(7..=8, ());
1891        map.insert(10..=11, ());
1892        assert_eq!(format!("{:?}", map), "{2..=5: (), 7..=8: (), 10..=11: ()}");
1893    }
1894
1895    // impl Default where T: ?Default
1896
1897    #[test]
1898    fn always_default() {
1899        struct NoDefault;
1900        RangeInclusiveMap::<NoDefault, NoDefault>::default();
1901    }
1902
1903    // impl Serialize
1904
1905    #[cfg(feature = "serde1")]
1906    #[test]
1907    fn serialization() {
1908        let mut range_map: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1909        // 0 1 2 3 4 5 6 7 8 9
1910        // ◌ ◆---◆ ◌ ◌ ◌ ◌ ◌ ◌
1911        range_map.insert(1..=3, false);
1912        // 0 1 2 3 4 5 6 7 8 9
1913        // ◌ ◌ ◌ ◌ ◌ ◆---◆ ◌ ◌
1914        range_map.insert(5..=7, true);
1915        let output = serde_json::to_string(&range_map).expect("Failed to serialize");
1916        assert_eq!(output, "[[[1,3],false],[[5,7],true]]");
1917    }
1918
1919    // impl Deserialize
1920
1921    #[cfg(feature = "serde1")]
1922    #[test]
1923    fn deserialization() {
1924        let input = "[[[1,3],false],[[5,7],true]]";
1925        let range_map: RangeInclusiveMap<u32, bool> =
1926            serde_json::from_str(input).expect("Failed to deserialize");
1927        let reserialized = serde_json::to_string(&range_map).expect("Failed to re-serialize");
1928        assert_eq!(reserialized, input);
1929    }
1930
1931    // const fn
1932
1933    #[cfg(feature = "const_fn")]
1934    const _MAP: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new();
1935    #[cfg(feature = "const_fn")]
1936    const _MAP2: RangeInclusiveMap<u32, bool> = RangeInclusiveMap::new_with_step_fns();
1937
1938    #[cfg(feature = "quickcheck")]
1939    quickcheck::quickcheck! {
1940        fn prop(xs: RangeInclusiveMap<usize, usize>) -> bool {
1941            xs == xs
1942        }
1943    }
1944}