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