rangemap/
inclusive_set.rs

1use core::borrow::Borrow;
2use core::fmt::{self, Debug};
3use core::iter::{DoubleEndedIterator, FromIterator};
4use core::ops::{BitAnd, BitOr, RangeInclusive};
5
6#[cfg(feature = "serde1")]
7use core::marker::PhantomData;
8#[cfg(feature = "serde1")]
9use serde::{
10    de::{Deserialize, Deserializer, SeqAccess, Visitor},
11    ser::{Serialize, Serializer},
12};
13
14use crate::std_ext::*;
15use crate::RangeInclusiveMap;
16
17/// Intersection iterator over two [`RangeInclusiveSet`].
18pub type Intersection<'a, T> = crate::operations::Intersection<'a, RangeInclusive<T>, Iter<'a, T>>;
19
20/// Union iterator over two [`RangeInclusiveSet`].
21pub type Union<'a, T> = crate::operations::Union<'a, RangeInclusive<T>, Iter<'a, T>>;
22
23#[derive(Clone, Hash, Eq, PartialEq, PartialOrd, Ord)]
24/// A set whose items are stored as ranges bounded
25/// inclusively below and above `(start..=end)`.
26///
27/// See [`RangeInclusiveMap`]'s documentation for more details.
28///
29/// [`RangeInclusiveMap`]: struct.RangeInclusiveMap.html
30pub struct RangeInclusiveSet<T, StepFnsT = T> {
31    rm: RangeInclusiveMap<T, (), StepFnsT>,
32}
33
34impl<T, StepFnsT> Default for RangeInclusiveSet<T, StepFnsT> {
35    fn default() -> Self {
36        Self {
37            rm: RangeInclusiveMap::default(),
38        }
39    }
40}
41
42impl<T> RangeInclusiveSet<T, T>
43where
44    T: Ord + Clone + StepLite,
45{
46    /// Makes a new empty `RangeInclusiveSet`.
47    #[cfg(feature = "const_fn")]
48    pub const fn new() -> Self {
49        Self::new_with_step_fns()
50    }
51
52    /// Makes a new empty `RangeInclusiveSet`.
53    #[cfg(not(feature = "const_fn"))]
54    pub fn new() -> Self {
55        Self::new_with_step_fns()
56    }
57}
58
59impl<T, StepFnsT> RangeInclusiveSet<T, StepFnsT>
60where
61    T: Ord + Clone,
62    StepFnsT: StepFns<T>,
63{
64    /// Makes a new empty `RangeInclusiveSet`, specifying successor and
65    /// predecessor functions defined separately from `T` itself.
66    ///
67    /// This is useful as a workaround for Rust's "orphan rules",
68    /// which prevent you from implementing `StepLite` for `T` if `T`
69    /// is a foreign type.
70    ///
71    /// **NOTE:** This will likely be deprecated and then eventually
72    /// removed once the standard library's [Step](core::iter::Step)
73    /// trait is stabilised, as most crates will then likely implement [Step](core::iter::Step)
74    /// for their types where appropriate.
75    ///
76    /// See [this issue](https://github.com/rust-lang/rust/issues/42168)
77    /// for details about that stabilization process.
78    #[cfg(not(feature = "const_fn"))]
79    pub fn new_with_step_fns() -> Self {
80        Self {
81            rm: RangeInclusiveMap::new_with_step_fns(),
82        }
83    }
84
85    #[cfg(feature = "const_fn")]
86    pub const fn new_with_step_fns() -> Self {
87        Self {
88            rm: RangeInclusiveMap::new_with_step_fns(),
89        }
90    }
91
92    /// Returns a reference to the range covering the given key, if any.
93    pub fn get(&self, value: &T) -> Option<&RangeInclusive<T>> {
94        self.rm.get_key_value(value).map(|(range, _)| range)
95    }
96
97    /// Returns `true` if any range in the set covers the specified value.
98    pub fn contains(&self, value: &T) -> bool {
99        self.rm.contains_key(value)
100    }
101
102    /// Gets an ordered iterator over all ranges,
103    /// ordered by range.
104    pub fn iter(&self) -> Iter<'_, T> {
105        Iter {
106            inner: self.rm.iter(),
107        }
108    }
109
110    /// Clears the set, removing all elements.
111    pub fn clear(&mut self) {
112        self.rm.clear();
113    }
114
115    /// Returns the number of elements in the set.
116    pub fn len(&self) -> usize {
117        self.rm.len()
118    }
119
120    /// Returns true if the set contains no elements.
121    pub fn is_empty(&self) -> bool {
122        self.rm.is_empty()
123    }
124
125    /// Insert a range into the set.
126    ///
127    /// If the inserted range either overlaps or is immediately adjacent
128    /// any existing range, then the ranges will be coalesced into
129    /// a single contiguous range.
130    ///
131    /// # Panics
132    ///
133    /// Panics if range `start > end`.
134    pub fn insert(&mut self, range: RangeInclusive<T>) {
135        self.rm.insert(range, ());
136    }
137
138    /// Removes a range from the set, if all or any of it was present.
139    ///
140    /// If the range to be removed _partially_ overlaps any ranges
141    /// in the set, then those ranges will be contracted to no
142    /// longer cover the removed range.
143    ///
144    /// # Panics
145    ///
146    /// Panics if range `start > end`.
147    pub fn remove(&mut self, range: RangeInclusive<T>) {
148        self.rm.remove(range);
149    }
150
151    /// Gets an iterator over all the maximally-sized ranges
152    /// contained in `outer_range` that are not covered by
153    /// any range stored in the set.
154    ///
155    /// The iterator element type is `RangeInclusive<T>`.
156    pub fn gaps<'a>(&'a self, outer_range: &'a RangeInclusive<T>) -> Gaps<'a, T, StepFnsT> {
157        Gaps {
158            inner: self.rm.gaps(outer_range),
159        }
160    }
161
162    /// Gets an iterator over all the stored ranges that are
163    /// either partially or completely overlapped by the given range.
164    ///
165    /// The iterator element type is `RangeInclusive<T>`.
166    pub fn overlapping<R: Borrow<RangeInclusive<T>>>(&self, range: R) -> Overlapping<T, R> {
167        Overlapping {
168            inner: self.rm.overlapping(range),
169        }
170    }
171
172    /// Returns `true` if any range in the set completely or partially
173    /// overlaps the given range.
174    pub fn overlaps(&self, range: &RangeInclusive<T>) -> bool {
175        self.overlapping(range).next().is_some()
176    }
177
178    /// Returns the first range in the set, if one exists. The range is the minimum range in this
179    /// set.
180    pub fn first(&self) -> Option<&RangeInclusive<T>> {
181        self.rm.first_range_value().map(|(range, _)| range)
182    }
183
184    /// Returns the last range in the set, if one exists. The range is the maximum range in this
185    /// set.
186    pub fn last(&self) -> Option<&RangeInclusive<T>> {
187        self.rm.last_range_value().map(|(range, _)| range)
188    }
189
190    /// Return an iterator over the union of two range sets.
191    pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, T> {
192        Union::new(self.iter(), other.iter())
193    }
194
195    /// Return an iterator over the intersection of two range sets.
196    pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, T> {
197        Intersection::new(self.iter(), other.iter())
198    }
199}
200
201/// An iterator over the ranges of a `RangeInclusiveSet`.
202///
203/// This `struct` is created by the [`iter`] method on [`RangeInclusiveSet`]. See its
204/// documentation for more.
205///
206/// [`iter`]: RangeInclusiveSet::iter
207pub struct Iter<'a, T> {
208    inner: super::inclusive_map::Iter<'a, T, ()>,
209}
210
211impl<'a, T> Iterator for Iter<'a, T> {
212    type Item = &'a RangeInclusive<T>;
213
214    fn next(&mut self) -> Option<Self::Item> {
215        self.inner.next().map(|(range, _)| range)
216    }
217
218    fn size_hint(&self) -> (usize, Option<usize>) {
219        self.inner.size_hint()
220    }
221}
222
223impl<'a, K> DoubleEndedIterator for Iter<'a, K>
224where
225    K: 'a,
226{
227    fn next_back(&mut self) -> Option<Self::Item> {
228        self.inner.next_back().map(|(range, _)| range)
229    }
230}
231
232/// An owning iterator over the ranges of a `RangeInclusiveSet`.
233///
234/// This `struct` is created by the [`into_iter`] method on [`RangeInclusiveSet`]
235/// (provided by the `IntoIterator` trait). See its documentation for more.
236///
237/// [`into_iter`]: IntoIterator::into_iter
238pub struct IntoIter<T> {
239    inner: super::inclusive_map::IntoIter<T, ()>,
240}
241
242impl<T> IntoIterator for RangeInclusiveSet<T> {
243    type Item = RangeInclusive<T>;
244    type IntoIter = IntoIter<T>;
245    fn into_iter(self) -> Self::IntoIter {
246        IntoIter {
247            inner: self.rm.into_iter(),
248        }
249    }
250}
251
252impl<T> Iterator for IntoIter<T> {
253    type Item = RangeInclusive<T>;
254    fn next(&mut self) -> Option<RangeInclusive<T>> {
255        self.inner.next().map(|(range, _)| range)
256    }
257    fn size_hint(&self) -> (usize, Option<usize>) {
258        self.inner.size_hint()
259    }
260}
261
262impl<K> DoubleEndedIterator for IntoIter<K> {
263    fn next_back(&mut self) -> Option<Self::Item> {
264        self.inner.next_back().map(|(range, _)| range)
265    }
266}
267
268// We can't just derive this automatically, because that would
269// expose irrelevant (and private) implementation details.
270// Instead implement it in the same way that the underlying BTreeSet does.
271impl<T: Debug> Debug for RangeInclusiveSet<T>
272where
273    T: Ord + Clone + StepLite,
274{
275    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276        f.debug_set().entries(self.iter()).finish()
277    }
278}
279
280impl<T> FromIterator<RangeInclusive<T>> for RangeInclusiveSet<T>
281where
282    T: Ord + Clone + StepLite,
283{
284    fn from_iter<I: IntoIterator<Item = RangeInclusive<T>>>(iter: I) -> Self {
285        let mut range_set = RangeInclusiveSet::new();
286        range_set.extend(iter);
287        range_set
288    }
289}
290
291impl<T> Extend<RangeInclusive<T>> for RangeInclusiveSet<T>
292where
293    T: Ord + Clone + StepLite,
294{
295    fn extend<I: IntoIterator<Item = RangeInclusive<T>>>(&mut self, iter: I) {
296        iter.into_iter().for_each(move |range| {
297            self.insert(range);
298        })
299    }
300}
301
302#[cfg(feature = "serde1")]
303impl<T> Serialize for RangeInclusiveSet<T>
304where
305    T: Ord + Clone + StepLite + Serialize,
306{
307    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
308    where
309        S: Serializer,
310    {
311        use serde::ser::SerializeSeq;
312        let mut seq = serializer.serialize_seq(Some(self.rm.btm.len()))?;
313        for range in self.iter() {
314            seq.serialize_element(&(&range.start(), &range.end()))?;
315        }
316        seq.end()
317    }
318}
319
320#[cfg(feature = "serde1")]
321impl<'de, T> Deserialize<'de> for RangeInclusiveSet<T>
322where
323    T: Ord + Clone + StepLite + Deserialize<'de>,
324{
325    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
326    where
327        D: Deserializer<'de>,
328    {
329        deserializer.deserialize_seq(RangeInclusiveSetVisitor::new())
330    }
331}
332
333#[cfg(feature = "serde1")]
334struct RangeInclusiveSetVisitor<T> {
335    marker: PhantomData<fn() -> RangeInclusiveSet<T>>,
336}
337
338#[cfg(feature = "serde1")]
339impl<T> RangeInclusiveSetVisitor<T> {
340    fn new() -> Self {
341        RangeInclusiveSetVisitor {
342            marker: PhantomData,
343        }
344    }
345}
346
347#[cfg(feature = "serde1")]
348impl<'de, T> Visitor<'de> for RangeInclusiveSetVisitor<T>
349where
350    T: Ord + Clone + StepLite + Deserialize<'de>,
351{
352    type Value = RangeInclusiveSet<T>;
353
354    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
355        formatter.write_str("RangeInclusiveSet")
356    }
357
358    fn visit_seq<A>(self, mut access: A) -> Result<Self::Value, A::Error>
359    where
360        A: SeqAccess<'de>,
361    {
362        let mut range_inclusive_set = RangeInclusiveSet::new();
363        while let Some((start, end)) = access.next_element()? {
364            range_inclusive_set.insert(start..=end);
365        }
366        Ok(range_inclusive_set)
367    }
368}
369
370/// An iterator over all ranges not covered by a `RangeInclusiveSet`.
371///
372/// This `struct` is created by the [`gaps`] method on [`RangeInclusiveSet`]. See its
373/// documentation for more.
374///
375/// [`gaps`]: RangeInclusiveSet::gaps
376pub struct Gaps<'a, T, StepFnsT> {
377    inner: crate::inclusive_map::Gaps<'a, T, (), StepFnsT>,
378}
379
380// `Gaps` is always fused. (See definition of `next` below.)
381impl<'a, T, StepFnsT> core::iter::FusedIterator for Gaps<'a, T, StepFnsT>
382where
383    T: Ord + Clone,
384    StepFnsT: StepFns<T>,
385{
386}
387
388impl<'a, T, StepFnsT> Iterator for Gaps<'a, T, StepFnsT>
389where
390    T: Ord + Clone,
391    StepFnsT: StepFns<T>,
392{
393    type Item = RangeInclusive<T>;
394
395    fn next(&mut self) -> Option<Self::Item> {
396        self.inner.next()
397    }
398}
399
400/// An iterator over all stored ranges partially or completely
401/// overlapped by a given range.
402///
403/// This `struct` is created by the [`overlapping`] method on [`RangeInclusiveSet`]. See its
404/// documentation for more.
405///
406/// [`overlapping`]: RangeInclusiveSet::overlapping
407pub struct Overlapping<'a, T, R: Borrow<RangeInclusive<T>> = &'a RangeInclusive<T>> {
408    inner: crate::inclusive_map::Overlapping<'a, T, (), R>,
409}
410
411// `Overlapping` is always fused. (See definition of `next` below.)
412impl<'a, T, R: Borrow<RangeInclusive<T>>> core::iter::FusedIterator for Overlapping<'a, T, R> where
413    T: Ord + Clone
414{
415}
416
417impl<'a, T, R: Borrow<RangeInclusive<T>>> Iterator for Overlapping<'a, T, R>
418where
419    T: Ord + Clone,
420{
421    type Item = &'a RangeInclusive<T>;
422
423    fn next(&mut self) -> Option<Self::Item> {
424        self.inner.next().map(|(k, _v)| k)
425    }
426}
427
428impl<'a, T, R: Borrow<RangeInclusive<T>>> DoubleEndedIterator for Overlapping<'a, T, R>
429where
430    T: Ord + Clone,
431{
432    fn next_back(&mut self) -> Option<Self::Item> {
433        self.inner.next_back().map(|(k, _v)| k)
434    }
435}
436
437impl<T: Ord + Clone + StepLite, const N: usize> From<[RangeInclusive<T>; N]>
438    for RangeInclusiveSet<T>
439{
440    fn from(value: [RangeInclusive<T>; N]) -> Self {
441        let mut set = Self::new();
442        for value in IntoIterator::into_iter(value) {
443            set.insert(value);
444        }
445        set
446    }
447}
448
449/// Create a [`RangeInclusiveSet`] from a list of ranges.
450///
451/// # Example
452///
453/// ```rust
454/// # use rangemap::range_inclusive_set;
455/// let set = range_inclusive_set![0..=100, 200..=300, 400..=500];
456/// ```
457#[macro_export]
458macro_rules! range_inclusive_set {
459    ($($range:expr),* $(,)?) => {{
460        $crate::RangeInclusiveSet::from([$($range),*])
461    }};
462}
463
464impl<T: Ord + Clone + StepLite> BitAnd for &RangeInclusiveSet<T> {
465    type Output = RangeInclusiveSet<T>;
466
467    fn bitand(self, other: Self) -> Self::Output {
468        self.intersection(other).collect()
469    }
470}
471
472impl<T: Ord + Clone + StepLite> BitOr for &RangeInclusiveSet<T> {
473    type Output = RangeInclusiveSet<T>;
474
475    fn bitor(self, other: Self) -> Self::Output {
476        self.union(other).collect()
477    }
478}
479
480#[cfg(test)]
481mod tests {
482    use super::*;
483    use alloc as std;
484    use alloc::{format, vec, vec::Vec};
485    use proptest::prelude::*;
486    use test_strategy::proptest;
487
488    impl<T> Arbitrary for RangeInclusiveSet<T>
489    where
490        T: Ord + Clone + StepLite + Debug + Arbitrary + 'static,
491    {
492        type Parameters = ();
493        type Strategy = BoxedStrategy<Self>;
494
495        fn arbitrary_with(_parameters: Self::Parameters) -> Self::Strategy {
496            any::<Vec<RangeInclusive<T>>>()
497                .prop_map(|ranges| ranges.into_iter().collect::<RangeInclusiveSet<T>>())
498                .boxed()
499        }
500    }
501
502    #[proptest]
503    fn test_first(set: RangeInclusiveSet<u64>) {
504        assert_eq!(set.first(), set.iter().min_by_key(|range| range.start()));
505    }
506
507    #[proptest]
508    #[allow(clippy::len_zero)]
509    fn test_len(mut map: RangeInclusiveSet<u64>) {
510        assert_eq!(map.len(), map.iter().count());
511        assert_eq!(map.is_empty(), map.len() == 0);
512        map.clear();
513        assert_eq!(map.len(), 0);
514        assert!(map.is_empty());
515        assert_eq!(map.iter().count(), 0);
516    }
517
518    #[proptest]
519    fn test_last(set: RangeInclusiveSet<u64>) {
520        assert_eq!(set.last(), set.iter().max_by_key(|range| range.end()));
521    }
522
523    #[proptest]
524    fn test_iter_reversible(set: RangeInclusiveSet<u64>) {
525        let forward: Vec<_> = set.iter().collect();
526        let mut backward: Vec<_> = set.iter().rev().collect();
527        backward.reverse();
528        assert_eq!(forward, backward);
529    }
530
531    #[proptest]
532    fn test_into_iter_reversible(set: RangeInclusiveSet<u64>) {
533        let forward: Vec<_> = set.clone().into_iter().collect();
534        let mut backward: Vec<_> = set.into_iter().rev().collect();
535        backward.reverse();
536        assert_eq!(forward, backward);
537    }
538
539    #[proptest]
540    fn test_overlapping_reversible(set: RangeInclusiveSet<u64>, range: RangeInclusive<u64>) {
541        let forward: Vec<_> = set.overlapping(&range).collect();
542        let mut backward: Vec<_> = set.overlapping(&range).rev().collect();
543        backward.reverse();
544        assert_eq!(forward, backward);
545    }
546
547    // neccessary due to assertion on empty ranges
548    fn filter_ranges<T: Ord>(ranges: Vec<RangeInclusive<T>>) -> Vec<RangeInclusive<T>> {
549        ranges
550            .into_iter()
551            .filter(|range| range.start() != range.end())
552            .collect()
553    }
554
555    #[proptest]
556    fn test_arbitrary_set_u8(ranges: Vec<RangeInclusive<u8>>) {
557        let ranges: Vec<_> = filter_ranges(ranges);
558        let set = ranges
559            .iter()
560            .fold(RangeInclusiveSet::new(), |mut set, range| {
561                set.insert(range.clone());
562                set
563            });
564
565        for value in 0..u8::MAX {
566            assert_eq!(
567                set.contains(&value),
568                ranges.iter().any(|range| range.contains(&value))
569            );
570        }
571    }
572
573    #[proptest]
574    #[allow(deprecated)]
575    fn test_hash(left: RangeInclusiveSet<u64>, right: RangeInclusiveSet<u64>) {
576        use core::hash::{Hash, Hasher, SipHasher};
577
578        let hash = |set: &RangeInclusiveSet<_>| {
579            let mut hasher = SipHasher::new();
580            set.hash(&mut hasher);
581            hasher.finish()
582        };
583
584        if left == right {
585            assert!(
586                hash(&left) == hash(&right),
587                "if two values are equal, their hash must be equal"
588            );
589        }
590
591        // if the hashes are equal the values might not be the same (collision)
592        if hash(&left) != hash(&right) {
593            assert!(
594                left != right,
595                "if two value's hashes are not equal, they must not be equal"
596            );
597        }
598    }
599
600    #[proptest]
601    fn test_ord(left: RangeInclusiveSet<u64>, right: RangeInclusiveSet<u64>) {
602        assert_eq!(
603            left == right,
604            left.cmp(&right).is_eq(),
605            "ordering and equality must match"
606        );
607        assert_eq!(
608            left.cmp(&right),
609            left.partial_cmp(&right).unwrap(),
610            "ordering is total for ordered parameters"
611        );
612    }
613
614    #[test]
615    fn test_from_array() {
616        let mut set = RangeInclusiveSet::new();
617        set.insert(0..=100);
618        set.insert(200..=300);
619        assert_eq!(set, RangeInclusiveSet::from([0..=100, 200..=300]));
620    }
621
622    #[test]
623    fn test_macro() {
624        assert_eq!(range_inclusive_set![], RangeInclusiveSet::<i64>::default());
625        assert_eq!(
626            range_inclusive_set![0..=100, 200..=300, 400..=500],
627            [0..=100, 200..=300, 400..=500].iter().cloned().collect(),
628        );
629    }
630
631    #[proptest]
632    fn test_union_overlaps_u8(left: RangeInclusiveSet<u8>, right: RangeInclusiveSet<u8>) {
633        let mut union = RangeInclusiveSet::new();
634        for range in left.union(&right) {
635            // there should not be any overlaps in the ranges returned by the union
636            assert!(union.overlapping(&range).next().is_none());
637            union.insert(range);
638        }
639    }
640
641    #[proptest]
642    fn test_union_contains_u8(left: RangeInclusiveSet<u8>, right: RangeInclusiveSet<u8>) {
643        let union = (&left) | (&right);
644
645        // value should be in the union if and only if it is in either set
646        for value in 0..u8::MAX {
647            assert_eq!(
648                union.contains(&value),
649                left.contains(&value) || right.contains(&value)
650            );
651        }
652    }
653
654    #[proptest]
655    fn test_intersection_contains_u8(left: RangeInclusiveSet<u8>, right: RangeInclusiveSet<u8>) {
656        let intersection = (&left) & (&right);
657
658        // value should be in the intersection if and only if it is in both sets
659        for value in 0..u8::MAX {
660            assert_eq!(
661                intersection.contains(&value),
662                left.contains(&value) && right.contains(&value)
663            );
664        }
665    }
666
667    #[proptest]
668    fn test_intersection_overlaps_u8(left: RangeInclusiveSet<u8>, right: RangeInclusiveSet<u8>) {
669        let mut union = RangeInclusiveSet::new();
670        for range in left.intersection(&right) {
671            // there should not be any overlaps in the ranges returned by the
672            // intersection
673            assert!(union.overlapping(&range).next().is_none());
674            union.insert(range);
675        }
676    }
677
678    trait RangeInclusiveSetExt<T> {
679        fn to_vec(&self) -> Vec<RangeInclusive<T>>;
680    }
681
682    impl<T> RangeInclusiveSetExt<T> for RangeInclusiveSet<T>
683    where
684        T: Ord + Clone + StepLite,
685    {
686        fn to_vec(&self) -> Vec<RangeInclusive<T>> {
687            self.iter().cloned().collect()
688        }
689    }
690
691    #[test]
692    fn empty_set_is_empty() {
693        let range_set: RangeInclusiveSet<u32> = RangeInclusiveSet::new();
694        assert_eq!(range_set.to_vec(), vec![]);
695    }
696
697    #[test]
698    fn insert_into_empty_map() {
699        let mut range_set: RangeInclusiveSet<u32> = RangeInclusiveSet::new();
700        range_set.insert(0..=50);
701        assert_eq!(range_set.to_vec(), vec![0..=50]);
702    }
703
704    #[test]
705    fn remove_partially_overlapping() {
706        let mut range_set: RangeInclusiveSet<u32> = RangeInclusiveSet::new();
707        range_set.insert(0..=50);
708        range_set.remove(25..=75);
709        assert_eq!(range_set.to_vec(), vec![0..=24]);
710    }
711
712    #[test]
713    fn gaps_between_items_floating_inside_outer_range() {
714        let mut range_set: RangeInclusiveSet<u32> = RangeInclusiveSet::new();
715        // 0 1 2 3 4 5 6 7 8 9
716        // ◌ ◌ ◌ ◌ ◌ ●-● ◌ ◌ ◌
717        range_set.insert(5..=6);
718        // 0 1 2 3 4 5 6 7 8 9
719        // ◌ ◌ ●-● ◌ ◌ ◌ ◌ ◌ ◌
720        range_set.insert(2..=3);
721        // 0 1 2 3 4 5 6 7 8 9
722        // ◌ ◆-------------◆ ◌
723        let outer_range = 1..=8;
724        let mut gaps = range_set.gaps(&outer_range);
725        // Should yield gaps at start, between items,
726        // and at end.
727        assert_eq!(gaps.next(), Some(1..=1));
728        assert_eq!(gaps.next(), Some(4..=4));
729        assert_eq!(gaps.next(), Some(7..=8));
730        assert_eq!(gaps.next(), None);
731        // Gaps iterator should be fused.
732        assert_eq!(gaps.next(), None);
733        assert_eq!(gaps.next(), None);
734    }
735
736    #[test]
737    fn overlapping_partial_edges_complete_middle() {
738        let mut range_set: RangeInclusiveSet<u32> = RangeInclusiveSet::new();
739
740        // 0 1 2 3 4 5 6 7 8 9
741        // ●-● ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌
742        range_set.insert(0..=1);
743        // 0 1 2 3 4 5 6 7 8 9
744        // ◌ ◌ ◌ ●-● ◌ ◌ ◌ ◌ ◌
745        range_set.insert(3..=4);
746        // 0 1 2 3 4 5 6 7 8 9
747        // ◌ ◌ ◌ ◌ ◌ ◌ ●-● ◌ ◌
748        range_set.insert(6..=7);
749
750        // 0 1 2 3 4 5 6 7 8 9
751        // ◌ ◆---------◆ ◌ ◌ ◌
752        let query_range = 1..=6;
753
754        let mut overlapping = range_set.overlapping(&query_range);
755
756        // Should yield partially overlapped range at start.
757        assert_eq!(overlapping.next(), Some(&(0..=1)));
758        // Should yield completely overlapped range in middle.
759        assert_eq!(overlapping.next(), Some(&(3..=4)));
760        // Should yield partially overlapped range at end.
761        assert_eq!(overlapping.next(), Some(&(6..=7)));
762        // Gaps iterator should be fused.
763        assert_eq!(overlapping.next(), None);
764        assert_eq!(overlapping.next(), None);
765    }
766
767    ///
768    /// impl Debug
769    ///
770
771    #[test]
772    fn set_debug_repr_looks_right() {
773        let mut set: RangeInclusiveSet<u32> = RangeInclusiveSet::new();
774
775        // Empty
776        assert_eq!(format!("{:?}", set), "{}");
777
778        // One entry
779        set.insert(2..=5);
780        assert_eq!(format!("{:?}", set), "{2..=5}");
781
782        // Many entries
783        set.insert(7..=8);
784        set.insert(10..=11);
785        assert_eq!(format!("{:?}", set), "{2..=5, 7..=8, 10..=11}");
786    }
787
788    // impl Default where T: ?Default
789
790    #[test]
791    fn always_default() {
792        struct NoDefault;
793        RangeInclusiveSet::<NoDefault>::default();
794    }
795
796    // impl Serialize
797
798    #[cfg(feature = "serde1")]
799    #[test]
800    fn serialization() {
801        let mut range_set: RangeInclusiveSet<u32> = RangeInclusiveSet::new();
802        // 0 1 2 3 4 5 6 7 8 9
803        // ◌ ◆---◆ ◌ ◌ ◌ ◌ ◌ ◌
804        range_set.insert(1..=3);
805        // 0 1 2 3 4 5 6 7 8 9
806        // ◌ ◌ ◌ ◌ ◌ ◆---◆ ◌ ◌
807        range_set.insert(5..=7);
808        let output = serde_json::to_string(&range_set).expect("Failed to serialize");
809        assert_eq!(output, "[[1,3],[5,7]]");
810    }
811
812    // impl Deserialize
813
814    #[cfg(feature = "serde1")]
815    #[test]
816    fn deserialization() {
817        let input = "[[1,3],[5,7]]";
818        let range_set: RangeInclusiveSet<u32> =
819            serde_json::from_str(input).expect("Failed to deserialize");
820        let reserialized = serde_json::to_string(&range_set).expect("Failed to re-serialize");
821        assert_eq!(reserialized, input);
822    }
823
824    // const fn
825
826    #[cfg(feature = "const_fn")]
827    const _SET: RangeInclusiveSet<u32> = RangeInclusiveSet::new();
828    #[cfg(feature = "const_fn")]
829    const _SET2: RangeInclusiveSet<u32> = RangeInclusiveSet::new_with_step_fns();
830}