interval/
interval_set.rs

1// Copyright 2015 Pierre Talbot (IRCAM)
2
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9//! Closed and bounded generic interval set.
10//!
11//! It stores intervals in a set. The main advantage is the exact representation of an interval by allowing "holes". For example `[1..2] U [5..6]` is stored as `{[1..2], [5..6]}`. This structure is more space-efficient than a classic set collection (such as `BTreeSet`) if the data stored are mostly contiguous. Of course, it is less light-weight than [interval](../interval/index.html), but we keep the list of intervals as small as possible by merging overlapping intervals.
12//!
13//! ```rust
14//! use crate::interval::interval_set::*;
15//! use gcollections::ops::*;
16//!
17//! # fn main() {
18//! let a = [(1,2), (6,10)].to_interval_set();
19//! let b = [(3,5), (7,7)].to_interval_set();
20//! let a_union_b = [(1,5), (6,10)].to_interval_set();
21//! let a_intersect_b = [(7,7)].to_interval_set();
22//!
23//! assert_eq!(a.union(&b), a_union_b);
24//! assert_eq!(a.intersection(&b), a_intersect_b);
25//! # }
26//! ```
27//!
28//! # See also
29//! [interval](../interval/index.html)
30
31use crate::interval::Interval;
32use crate::interval::ToInterval;
33use crate::ops::*;
34use gcollections::ops::*;
35use gcollections::*;
36use serde::de::SeqAccess;
37use serde::de::Visitor;
38use serde::Deserialize;
39use serde::Serialize;
40use std::fmt;
41use std::fmt::{Display, Error, Formatter};
42use std::iter::{IntoIterator, Peekable};
43use std::marker::PhantomData;
44use std::ops::{Add, Mul, Sub};
45use trilean::SKleene;
46
47use num_traits::{Num, Zero};
48
49#[derive(Debug, Clone)]
50pub struct IntervalSet<Bound: Width> {
51    intervals: Vec<Interval<Bound>>,
52    size: Bound::Output,
53}
54
55impl<Bound> Serialize for IntervalSet<Bound>
56where
57    Bound: Width + Num + Serialize,
58    Interval<Bound>: Serialize,
59{
60    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
61    where
62        S: serde::Serializer,
63    {
64        if self.is_empty() {
65            serializer.serialize_none()
66        } else {
67            serializer.collect_seq(&self.intervals)
68        }
69    }
70}
71
72impl<'de, Bound> Deserialize<'de> for IntervalSet<Bound>
73where
74    Bound: Width + Num + Deserialize<'de>,
75{
76    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
77    where
78        D: serde::Deserializer<'de>,
79    {
80        struct IntervalSetVisitor<Bound> {
81            marker: PhantomData<fn() -> Interval<Bound>>,
82        }
83        impl<Bound> IntervalSetVisitor<Bound> {
84            fn new() -> Self {
85                IntervalSetVisitor {
86                    marker: PhantomData,
87                }
88            }
89        }
90        impl<'de, Bound> Visitor<'de> for IntervalSetVisitor<Bound>
91        where
92            Bound: Width + Deserialize<'de> + Num,
93        {
94            type Value = IntervalSet<Bound>;
95
96            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
97                formatter.write_str("sequence of intervals")
98            }
99
100            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
101            where
102                A: SeqAccess<'de>,
103            {
104                let mut intervals = Vec::new();
105                if let Some(size) = seq.size_hint() {
106                    intervals.reserve(size);
107                }
108                while let Some(interval) = seq.next_element::<Interval<Bound>>()? {
109                    intervals.push(interval);
110                }
111                let mut interval_set = IntervalSet::empty();
112                interval_set.extend(intervals);
113                Ok(interval_set)
114            }
115
116            fn visit_none<E>(self) -> Result<Self::Value, E>
117            where
118                E: serde::de::Error,
119            {
120                Ok(IntervalSet::empty())
121            }
122        }
123        deserializer.deserialize_any(IntervalSetVisitor::new())
124    }
125}
126
127impl<Bound: Width> IntervalKind for IntervalSet<Bound> {}
128
129impl<Bound: Width> Collection for IntervalSet<Bound> {
130    type Item = Bound;
131}
132
133impl<Bound: Width> IntoIterator for IntervalSet<Bound> {
134    type Item = Interval<Bound>;
135    type IntoIter = ::std::vec::IntoIter<Self::Item>;
136
137    fn into_iter(self) -> Self::IntoIter {
138        self.intervals.into_iter()
139    }
140}
141
142impl<'a, Bound: Width> IntoIterator for &'a IntervalSet<Bound> {
143    type Item = &'a Interval<Bound>;
144    type IntoIter = ::std::slice::Iter<'a, Interval<Bound>>;
145
146    fn into_iter(self) -> Self::IntoIter {
147        self.iter()
148    }
149}
150
151impl<'a, Bound: Width> IntoIterator for &'a mut IntervalSet<Bound> {
152    type Item = &'a mut Interval<Bound>;
153    type IntoIter = ::std::slice::IterMut<'a, Interval<Bound>>;
154
155    fn into_iter(self) -> Self::IntoIter {
156        self.iter_mut()
157    }
158}
159
160impl<Bound: Width> IntervalSet<Bound> {
161    pub fn iter(&self) -> ::std::slice::Iter<Interval<Bound>> {
162        self.intervals.iter()
163    }
164
165    pub fn iter_mut(&mut self) -> ::std::slice::IterMut<Interval<Bound>> {
166        self.intervals.iter_mut()
167    }
168}
169
170impl<Bound> IntervalSet<Bound>
171where
172    Bound: Width + Num,
173{
174    /// Counts the number of intervals contained in the set.
175    /// ```
176    /// # use interval::prelude::*;
177    /// let single_interval_set = IntervalSet::new(0, 1);
178    /// assert_eq!(single_interval_set.interval_count(), 1);
179    /// let double_interval_set = [(3,5), (7,7)].to_interval_set();
180    /// assert_eq!(double_interval_set.interval_count(), 2);
181    /// let empty_interval_set = IntervalSet::<usize>::empty();
182    /// assert_eq!(empty_interval_set.interval_count(), 0);
183    /// ```
184    pub fn interval_count(&self) -> usize {
185        self.intervals.len()
186    }
187
188    fn from_interval(i: Interval<Bound>) -> IntervalSet<Bound> {
189        let size = i.size().clone();
190        IntervalSet {
191            intervals: [i].to_vec(),
192            size,
193        }
194    }
195
196    fn front(&self) -> &Interval<Bound> {
197        debug_assert!(
198            !self.is_empty(),
199            "Cannot access the first interval of an empty set."
200        );
201        &self.intervals[0]
202    }
203
204    fn back_idx(&self) -> usize {
205        self.intervals.len() - 1
206    }
207
208    fn back(&self) -> &Interval<Bound> {
209        debug_assert!(
210            !self.is_empty(),
211            "Cannot access the last interval of an empty set."
212        );
213        &self.intervals[self.back_idx()]
214    }
215
216    fn span(&self) -> Interval<Bound> {
217        if self.is_empty() {
218            Interval::empty()
219        } else {
220            self.span_slice(0, self.back_idx())
221        }
222    }
223
224    fn span_slice(&self, left: usize, right: usize) -> Interval<Bound> {
225        Interval::new(self.intervals[left].lower(), self.intervals[right].upper())
226    }
227
228    fn push(&mut self, x: Interval<Bound>) {
229        debug_assert!(!x.is_empty(), "Cannot push empty interval.");
230        debug_assert!(self.is_empty() || !joinable(self.back(), &x),
231      "The intervals array must be ordered and intervals must not be joinable. For a safe push, use the union operation.");
232
233        self.size = self.size.clone() + x.size();
234        self.intervals.push(x);
235    }
236
237    fn pop(&mut self) -> Option<Interval<Bound>> {
238        if let Some(x) = self.intervals.pop() {
239            self.size = self.size.clone() - x.size();
240            Some(x)
241        } else {
242            None
243        }
244    }
245
246    fn join_or_push(&mut self, x: Interval<Bound>) {
247        if self.is_empty() {
248            self.push(x);
249        } else {
250            debug_assert!(!x.is_empty(), "Cannot push empty interval.");
251            debug_assert!(self.back().lower() <= x.lower(),
252        "This operation is only for pushing interval to the back of the array, possibly overlapping with the last element.");
253
254            let joint = if joinable(self.back(), &x) {
255                self.pop().unwrap().hull(&x)
256            } else {
257                x
258            };
259            self.push(joint);
260        }
261    }
262
263    /// Expects the given iterable to be in-order - as we are iterating through
264    /// it, each [`Interval<Bound>`] should belong on the upper end of the
265    /// [`IntervalSet`]. Otherwise this method will panic.
266    fn extend_at_back<I>(&mut self, iterable: I)
267    where
268        I: IntoIterator<Item = Interval<Bound>>,
269        Bound: PartialOrd,
270    {
271        for interval in iterable {
272            self.join_or_push(interval);
273        }
274    }
275
276    fn find_interval_between(
277        &self,
278        value: &Bound,
279        mut left: usize,
280        mut right: usize,
281    ) -> (usize, usize) {
282        debug_assert!(left <= right);
283        debug_assert!(right < self.intervals.len());
284        debug_assert!(self.span_slice(left, right).contains(value));
285
286        while left <= right {
287            let mid_idx = left + (right - left) / 2;
288            let mid = &self.intervals[mid_idx];
289            if &mid.lower() > value {
290                right = mid_idx - 1;
291            } else if &mid.upper() < value {
292                left = mid_idx + 1;
293            } else {
294                return (mid_idx, mid_idx);
295            }
296        }
297        (right, left)
298    }
299
300    // Returns the indexes of the left and right interval of `value`.
301    // If the value is outside `self`, returns None.
302    // If the value is inside one of the interval, the indexes will be equal.
303    fn find_interval(&self, value: &Bound) -> Option<(usize, usize)> {
304        if !self.span().contains(value) {
305            None
306        } else {
307            Some(self.find_interval_between(value, 0, self.back_idx()))
308        }
309    }
310
311    fn for_all_pairs<F>(&self, other: &IntervalSet<Bound>, f: F) -> IntervalSet<Bound>
312    where
313        F: Fn(&Interval<Bound>, &Interval<Bound>) -> Interval<Bound>,
314    {
315        let mut res = IntervalSet::empty();
316        for i in &self.intervals {
317            for j in &other.intervals {
318                res = res.union(&IntervalSet::from_interval(f(i, j)));
319            }
320        }
321        res
322    }
323
324    // Precondition: `f` must not change the size of the interval.
325    fn stable_map<F>(&self, f: F) -> IntervalSet<Bound>
326    where
327        F: Fn(&Interval<Bound>) -> Interval<Bound>,
328    {
329        IntervalSet {
330            intervals: self.intervals.iter().map(f).collect(),
331            size: self.size.clone(),
332        }
333    }
334
335    fn map<F>(&self, f: F) -> IntervalSet<Bound>
336    where
337        F: Fn(&Interval<Bound>) -> Interval<Bound>,
338    {
339        self.intervals
340            .iter()
341            .fold(IntervalSet::empty(), |mut r, i| {
342                r.push(f(i));
343                r
344            })
345    }
346}
347
348fn joinable<Bound>(first: &Interval<Bound>, second: &Interval<Bound>) -> bool
349where
350    Bound: Width + Num,
351{
352    if first.upper() == Bound::max_value() {
353        true
354    } else {
355        first.upper() + Bound::one() >= second.lower()
356    }
357}
358
359impl<Bound> Extend<Interval<Bound>> for IntervalSet<Bound>
360where
361    Bound: Width + Num,
362{
363    /// Inserts additional intervals into an interval set.
364    /// ```
365    /// # use interval::prelude::*;
366    /// let mut interval_set = IntervalSet::<u32>::empty();
367    /// assert_eq!(interval_set, Vec::new().to_interval_set());
368    /// interval_set.extend([Interval::new(2, 3), Interval::new(6, 7)]);
369    /// // Now the set contains two disjoint intervals.
370    /// assert_eq!(interval_set, [(2, 3), (6, 7)].to_interval_set());
371    /// // Unify the intervals with the missing items to create a single interval.
372    /// interval_set.extend([Interval::singleton(4), Interval::singleton(5)]);
373    /// assert_eq!(interval_set, [(2, 7)].to_interval_set());
374    /// ```
375    fn extend<I>(&mut self, iterable: I)
376    where
377        I: IntoIterator<Item = Interval<Bound>>,
378    {
379        let mut intervals: Vec<_> = iterable.into_iter().map(|i| i.to_interval()).collect();
380        intervals.sort_unstable_by_key(|i| i.lower());
381        let mut set = IntervalSet::empty();
382        set.extend_at_back(intervals);
383        *self = self.union(&set);
384    }
385}
386
387impl<Bound: Width + Num> Eq for IntervalSet<Bound> {}
388
389impl<Bound> PartialEq<IntervalSet<Bound>> for IntervalSet<Bound>
390where
391    Bound: Width + Num,
392{
393    // Checks whether two interval sets are the same.
394    /// ```
395    /// # use interval::prelude::*;
396    /// let single_interval = [(1, 5)].to_interval_set();
397    /// let equivalent_interval = [(1, 2), (2, 5)].to_interval_set();
398    /// assert_eq!(single_interval, equivalent_interval);
399    /// ```
400    /// Empty intervals are the same as each other, but not non-empty intervals.
401    /// ```
402    /// # use interval::prelude::*;
403    /// assert_eq!(IntervalSet::<usize>::empty(), IntervalSet::<usize>::empty());
404    /// assert_ne!(IntervalSet::empty(), [(2, 3), (8, 9)].to_interval_set());
405    /// ```
406    fn eq(&self, other: &IntervalSet<Bound>) -> bool {
407        if self.size() != other.size() {
408            false
409        } else {
410            self.intervals == other.intervals
411        }
412    }
413}
414
415impl<Bound> Range for IntervalSet<Bound>
416where
417    Bound: Width + Num,
418{
419    /// Constructs an interval set from a specified interval.
420    /// ```
421    /// # use interval::prelude::*;
422    /// let interval = IntervalSet::new(2, 4);
423    /// assert!(interval.contains(&2));
424    /// assert!(interval.contains(&3));
425    /// assert!(interval.contains(&4));
426    ///
427    /// assert!(!interval.contains(&1));
428    /// assert!(!interval.contains(&5));
429    /// ```
430    /// Constructing an empty interval set is done via the [IntervalSet::empty()] method.
431    /// ```
432    /// # use interval::prelude::*;
433    /// let empty_interval = IntervalSet::<u16>::empty();
434    /// ```
435    fn new(lb: Bound, ub: Bound) -> IntervalSet<Bound> {
436        debug_assert!(lb <= ub, "Cannot build empty interval set with an invalid range. use crate::IntervalSet::empty().");
437        let i = Interval::new(lb, ub);
438        IntervalSet::from_interval(i)
439    }
440}
441
442impl<Bound> Whole for IntervalSet<Bound>
443where
444    Bound: Width + Num,
445{
446    /// Constructs an interval set using the entire range an interval can represent.
447    /// The bounds of the interval set are bounded in the same way as [`Interval::whole`].
448    /// This is different for unsigned and signed integers:
449    /// ```
450    /// # use interval::prelude::*;
451    /// let unsigned_interval = IntervalSet::<u8>::whole();
452    /// assert_eq!(unsigned_interval, IntervalSet::new(0, 254));
453    ///
454    /// let signed_interval = IntervalSet::<i8>::whole();
455    /// assert_eq!(signed_interval, IntervalSet::new(-127, 127));
456    /// ```
457    fn whole() -> IntervalSet<Bound> {
458        let mut res = IntervalSet::empty();
459        res.push(Interval::whole());
460        res
461    }
462}
463
464impl<Bound> Bounded for IntervalSet<Bound>
465where
466    Bound: Width + Num + PartialOrd,
467{
468    /// Returns the smallest value contained in an interval set.
469    /// ```
470    /// # use interval::prelude::*;
471    /// assert_eq!([(8, 20)].to_interval_set().lower(), 8);
472    /// assert_eq!([(-5, 11), (10, 30)].to_interval_set().lower(), -5);
473    /// assert_eq!(IntervalSet::singleton(7).lower(), 7);
474    /// ```
475    /// However, this will panic on an empty interval.
476    /// ```should_panic
477    /// # use interval::prelude::*;
478    /// IntervalSet::<u8>::empty().lower(); // panics!
479    /// ```
480    fn lower(&self) -> Bound {
481        debug_assert!(
482            !self.is_empty(),
483            "Cannot access lower bound on empty interval."
484        );
485        self.front().lower()
486    }
487
488    /// Returns the largest value contained in an interval set.
489    /// ```
490    /// # use interval::prelude::*;
491    /// assert_eq!([(8, 20)].to_interval_set().upper(), 20);
492    /// assert_eq!([(-5, 11), (10, 30)].to_interval_set().upper(), 30);
493    /// assert_eq!(IntervalSet::singleton(7).upper(), 7);
494    /// ```
495    /// However, this will panic on an empty interval.
496    /// ```should_panic
497    /// # use interval::prelude::*;
498    /// IntervalSet::<u8>::empty().upper(); // panics!
499    /// ```
500    fn upper(&self) -> Bound {
501        debug_assert!(
502            !self.is_empty(),
503            "Cannot access upper bound on empty interval."
504        );
505        self.back().upper()
506    }
507}
508
509impl<Bound: Width + Num> Singleton for IntervalSet<Bound> {
510    /// Constructs an interval set containing a single value.
511    /// This set contains a single interval with the same upper and lower bounds.
512    /// ```
513    /// # use interval::prelude::*;
514    /// let interval_set_5 = IntervalSet::singleton(5);
515    /// assert_eq!(interval_set_5.size(), 1 as u32);
516    /// assert_eq!(interval_set_5.lower(), interval_set_5.upper());
517    /// assert!(interval_set_5.contains(&5));
518    /// assert!(!interval_set_5.is_empty());
519    /// ```
520    fn singleton(x: Bound) -> IntervalSet<Bound> {
521        IntervalSet::new(x.clone(), x)
522    }
523}
524
525impl<Bound: Width + Num> Empty for IntervalSet<Bound> {
526    /// Constructs an empty interval set.
527    /// The type needs to be specified or inferred as `Interval` is parametrized by its input.
528    /// ```
529    /// # use interval::prelude::*;
530    /// assert_eq!(IntervalSet::<i32>::empty().size(), 0);
531    /// assert_eq!(IntervalSet::<u32>::empty().size(), 0);
532    /// assert!(IntervalSet::<u16>::empty().is_empty());
533    /// ```
534    fn empty() -> IntervalSet<Bound> {
535        IntervalSet {
536            intervals: Vec::new(),
537            size: <<Bound as Width>::Output>::zero(),
538        }
539    }
540}
541
542/// `IsSingleton` and `IsEmpty` are defined automatically in `gcollections`.
543impl<Bound: Width + Num> Cardinality for IntervalSet<Bound> {
544    type Size = <Bound as Width>::Output;
545
546    /// Calculates the size of an interval set (the number of integers it contains).
547    /// This includes the endpoints of all intervals.
548    /// The size of the interval set is unsigned, but has the same number of bits as the interval bounds.
549    /// ```
550    /// # use interval::prelude::*;
551    /// assert_eq!(IntervalSet::<i32>::singleton(8).size(), 1 as u32);
552    /// assert_eq!(IntervalSet::<usize>::new(1, 10).size(), 10 as usize);
553    /// // Default is to use i32.
554    /// assert_eq!([(3, 5), (8, 9)].to_interval_set().size(), (3 + 2) as u32);
555    /// assert_eq!(IntervalSet::<i64>::empty().size(), 0);
556    /// // Doesn't overflow:
557    /// assert_eq!(IntervalSet::<usize>::whole().size(), usize::max_value());
558    /// ```
559    fn size(&self) -> <Bound as Width>::Output {
560        self.size.clone()
561    }
562}
563
564impl<Bound: Width + Num> Contains for IntervalSet<Bound> {
565    /// Calculates whether an interval contains a value.
566    /// ```
567    /// # use interval::prelude::*;
568    /// let interval_set = [(3, 5), (8, 9)].to_interval_set();
569    /// assert!(interval_set.contains(&3));
570    /// assert!(interval_set.contains(&4));
571    /// assert!(interval_set.contains(&5));
572    /// assert!(interval_set.contains(&8));
573    /// assert!(interval_set.contains(&9));
574    ///
575    /// assert!(!interval_set.contains(&1));
576    /// assert!(!interval_set.contains(&2));
577    /// assert!(!interval_set.contains(&6));
578    /// assert!(!interval_set.contains(&7));
579    /// assert!(!interval_set.contains(&10));
580    /// ```
581    fn contains(&self, value: &Bound) -> bool {
582        if let Some((left, right)) = self.find_interval(value) {
583            left == right
584        } else {
585            false
586        }
587    }
588}
589
590fn advance_one<I, F, Item>(a: &mut Peekable<I>, b: &mut Peekable<I>, choose: F) -> Item
591where
592    I: Iterator<Item = Item>,
593    F: Fn(&Item, &Item) -> bool,
594    Item: Bounded,
595{
596    static NON_EMPTY_PRECONDITION: &str =
597        "`advance_one` expects both interval iterators to be non_empty.";
598    let who_advance = {
599        let i = a.peek().expect(NON_EMPTY_PRECONDITION);
600        let j = b.peek().expect(NON_EMPTY_PRECONDITION);
601        choose(i, j)
602    };
603    let to_advance = if who_advance { a } else { b };
604    to_advance.next().unwrap()
605}
606
607fn advance_lower<I, Item, B>(a: &mut Peekable<I>, b: &mut Peekable<I>) -> Item
608where
609    I: Iterator<Item = Item>,
610    Item: Bounded + Collection<Item = B>,
611    B: Ord,
612{
613    advance_one(a, b, |i, j| i.lower() < j.lower())
614}
615
616// Advance the one with the lower upper bound.
617fn advance_lub<I, Item, B>(a: &mut Peekable<I>, b: &mut Peekable<I>) -> Item
618where
619    I: Iterator<Item = Item>,
620    Item: Bounded + Collection<Item = B>,
621    B: Ord,
622{
623    advance_one(a, b, |i, j| i.upper() < j.upper())
624}
625
626fn from_lower_iterator<I, Bound>(a: &mut Peekable<I>, b: &mut Peekable<I>) -> IntervalSet<Bound>
627where
628    I: Iterator<Item = Interval<Bound>>,
629    Bound: Width + Num,
630{
631    if a.peek().is_none() || b.peek().is_none() {
632        IntervalSet::empty()
633    } else {
634        let first = advance_lower(a, b);
635        IntervalSet::from_interval(first)
636    }
637}
638
639impl<Bound> Union<Bound> for IntervalSet<Bound>
640where
641    Bound: Width + Num + Clone,
642{
643    type Output = IntervalSet<Bound>;
644
645    /// Adds a value to the interval set.
646    /// The value does not have to below to an existing interval,
647    /// but if it does, those intervals will be merged.
648    /// ```
649    /// # use interval::prelude::*;
650    /// let interval_set = [(1, 4), (6, 7)].to_interval_set();
651    /// assert_eq!(interval_set.union(&10), [(1, 4), (6, 7), (10, 10)].to_interval_set());
652    ///
653    /// assert_eq!(interval_set.union(&3), interval_set);
654    /// assert_eq!(interval_set.union(&6), interval_set);
655    ///
656    /// assert_eq!(interval_set.union(&0), [(0, 4), (6, 7)].to_interval_set());
657    /// assert_eq!(interval_set.union(&8), [(1, 4), (6, 8)].to_interval_set());
658    ///
659    /// assert_eq!(interval_set.union(&5), [(1, 7)].to_interval_set());
660    /// ```
661    fn union(&self, rhs: &Bound) -> IntervalSet<Bound> {
662        self.union(&IntervalSet::singleton(rhs.clone()))
663    }
664}
665
666impl<Bound: Width + Num> Union for IntervalSet<Bound> {
667    type Output = IntervalSet<Bound>;
668
669    /// Calculates the union of two interval sets.
670    /// This returns an interval set containing all the values in the two that were unified.
671    /// ```
672    /// # use interval::prelude::*;
673    /// let a = [(1, 3), (8, 8), (10, 11)].to_interval_set();
674    /// let b = [(2, 5), (7, 8), (12, 15)].to_interval_set();
675    /// assert_eq!(a.union(&b), [(1, 5), (7, 8), (10, 15)].to_interval_set());
676    /// ```
677    fn union(&self, rhs: &IntervalSet<Bound>) -> IntervalSet<Bound> {
678        let a = &mut self.intervals.iter().cloned().peekable();
679        let b = &mut rhs.intervals.iter().cloned().peekable();
680        let mut res = from_lower_iterator(a, b);
681        while a.peek().is_some() && b.peek().is_some() {
682            let lower = advance_lower(a, b);
683            res.join_or_push(lower);
684        }
685        res.extend_at_back(a);
686        res.extend_at_back(b);
687        res
688    }
689}
690
691// Returns `false` when one of the iterator is consumed.
692// Iterators are not consumed if the intervals are already overlapping.
693fn advance_to_first_overlapping<I, Item, B>(a: &mut Peekable<I>, b: &mut Peekable<I>) -> bool
694where
695    I: Iterator<Item = Item>,
696    Item: Bounded + Overlap + Collection<Item = B>,
697    B: Ord,
698{
699    while a.peek().is_some() && b.peek().is_some() {
700        let overlapping = {
701            let i = a.peek().unwrap();
702            let j = b.peek().unwrap();
703            i.overlap(j)
704        };
705        if overlapping {
706            return true;
707        } else {
708            advance_lower(a, b);
709        }
710    }
711    false
712}
713
714impl<Bound> Intersection<Bound> for IntervalSet<Bound>
715where
716    Bound: Width + Num + Clone,
717{
718    type Output = IntervalSet<Bound>;
719
720    /// Calculates whether a value is contained in an interval.
721    /// Returns the value as an interval set if it is in the interval
722    /// and an empty interval set if not.
723    /// ```
724    /// # use interval::prelude::*;
725    /// let interval_set = [(1, 4), (6, 7)].to_interval_set();
726    /// assert_eq!(interval_set.intersection(&10), IntervalSet::empty());
727    ///
728    /// assert_eq!(interval_set.intersection(&3), IntervalSet::singleton(3));
729    /// assert_eq!(interval_set.intersection(&6), IntervalSet::singleton(6));
730    /// ```
731    fn intersection(&self, rhs: &Bound) -> IntervalSet<Bound> {
732        self.intersection(&IntervalSet::singleton(rhs.clone()))
733    }
734}
735
736impl<Bound: Width + Num> Intersection for IntervalSet<Bound> {
737    type Output = IntervalSet<Bound>;
738
739    /// Calculates the intersection of two interval sets.
740    /// This returns an interval set containing all the values in the both.
741    /// ```
742    /// # use interval::prelude::*;
743    /// let a = [(1, 3), (8, 8), (10, 11)].to_interval_set();
744    /// let b = [(2, 5), (7, 8), (12, 15)].to_interval_set();
745    /// assert_eq!(a.intersection(&b), [(2, 3), (8, 8)].to_interval_set());
746    /// ```
747    fn intersection(&self, rhs: &IntervalSet<Bound>) -> IntervalSet<Bound> {
748        let a = &mut self.intervals.iter().cloned().peekable();
749        let b = &mut rhs.intervals.iter().cloned().peekable();
750        let mut res = IntervalSet::empty();
751        while advance_to_first_overlapping(a, b) {
752            {
753                let i = a.peek().unwrap();
754                let j = b.peek().unwrap();
755                res.push(i.intersection(j));
756            }
757            advance_lub(a, b); // advance the one with the lowest upper bound.
758        }
759        res
760    }
761}
762
763fn push_left_complement<Bound: Width + Num>(x: &Interval<Bound>, res: &mut IntervalSet<Bound>) {
764    let min = <Bound as Width>::min_value();
765    if x.lower() != min {
766        res.push(Interval::new(min, x.lower() - Bound::one()));
767    }
768}
769
770fn push_right_complement<Bound: Width + Num>(x: &Interval<Bound>, res: &mut IntervalSet<Bound>) {
771    let max = <Bound as Width>::max_value();
772    if x.upper() != max {
773        res.push(Interval::new(x.upper() + Bound::one(), max));
774    }
775}
776
777impl<Bound: Width + Num> Complement for IntervalSet<Bound> {
778    /// Calculates all values that are excluded from the interval set.
779    /// Positive and negative infinity are represented with `Interval::whole().lower()` and `Interval::whole().upper()`;
780    /// ```
781    /// # use interval::prelude::*;
782    /// assert_eq!(IntervalSet::<i64>::empty().complement(), IntervalSet::whole());
783    ///
784    /// let neg_inf = IntervalSet::<i32>::whole().lower();
785    /// let pos_inf = IntervalSet::<i32>::whole().upper();
786    /// assert_eq!(IntervalSet::singleton(5).complement(), [(neg_inf, 4), (6, pos_inf)].to_interval_set());
787    /// assert_eq!([(2, 5), (8, 10)].to_interval_set().complement(), [(neg_inf, 1), (6, 7), (11, pos_inf)].to_interval_set());
788    /// ```
789    fn complement(&self) -> IntervalSet<Bound> {
790        let mut res = IntervalSet::empty();
791        if self.is_empty() {
792            res.push(Interval::whole());
793        } else {
794            let one = Bound::one();
795            push_left_complement(self.front(), &mut res);
796            for i in 1..self.intervals.len() {
797                let current = &self.intervals[i];
798                let previous = &self.intervals[i - 1];
799                res.push(Interval::new(
800                    previous.upper() + one.clone(),
801                    current.lower() - one.clone(),
802                ));
803            }
804            push_right_complement(self.back(), &mut res);
805        }
806        res
807    }
808}
809
810impl<Bound> Difference<Bound> for IntervalSet<Bound>
811where
812    Bound: Width + Num + Clone,
813{
814    type Output = IntervalSet<Bound>;
815
816    /// Calculates the interval set after removing a single value.
817    /// This returns the original interval set if the value is not in the interval set.
818    /// ```
819    /// # use interval::prelude::*;
820    /// let interval_set = [(1, 3), (5, 9)].to_interval_set();
821    /// assert_eq!(interval_set.difference(&4), interval_set);
822    /// assert_eq!(interval_set.difference(&5), [(1, 3), (6, 9)].to_interval_set());
823    /// assert_eq!(interval_set.difference(&7), [(1, 3), (5, 6), (8, 9)].to_interval_set());
824    /// ```
825    fn difference(&self, rhs: &Bound) -> IntervalSet<Bound> {
826        self.difference(&IntervalSet::singleton(rhs.clone()))
827    }
828}
829
830impl<Bound: Width + Num> Difference for IntervalSet<Bound> {
831    type Output = IntervalSet<Bound>;
832
833    /// Calculates the interval set containing all items in the left set,
834    /// but not in the right set.
835    /// The difference is not symmetric.
836    /// ```
837    /// # use interval::prelude::*;
838    /// let a = [(1, 3), (8, 8), (10, 11)].to_interval_set();
839    /// let b = [(2, 5), (7, 8), (12, 15)].to_interval_set();
840    /// assert_eq!(a.difference(&b), [(1, 1), (10, 11)].to_interval_set());
841    /// assert_eq!(b.difference(&a), [(4, 5), (7, 7), (12, 15)].to_interval_set());
842    /// ```
843    fn difference(&self, rhs: &IntervalSet<Bound>) -> IntervalSet<Bound> {
844        self.intersection(&rhs.complement())
845    }
846}
847
848impl<Bound> SymmetricDifference<Bound> for IntervalSet<Bound>
849where
850    Bound: Width + Num + Clone,
851{
852    type Output = IntervalSet<Bound>;
853
854    /// If the value is in the interval set, this return the interval set without the value.
855    /// If the value is not in the interval set, this returns the interval set extended with the value.
856    /// ```
857    /// # use interval::prelude::*;
858    /// let interval_set = [(1, 3), (5, 9)].to_interval_set();
859    /// assert_eq!(interval_set.symmetric_difference(&4), [(1, 9)].to_interval_set());
860    /// assert_eq!(interval_set.symmetric_difference(&4), interval_set.union(&4));
861
862    /// assert_eq!(interval_set.symmetric_difference(&5), [(1, 3), (6, 9)].to_interval_set());
863    /// assert_eq!(interval_set.symmetric_difference(&5), interval_set.difference(&5));
864    /// ```
865    fn symmetric_difference(&self, rhs: &Bound) -> IntervalSet<Bound> {
866        self.symmetric_difference(&IntervalSet::singleton(rhs.clone()))
867    }
868}
869
870impl<Bound: Width + Num> SymmetricDifference for IntervalSet<Bound> {
871    type Output = IntervalSet<Bound>;
872
873    /// Calculates the interval set containing that are in either the left set or the right set,
874    /// but not both.
875    /// ```
876    /// # use interval::prelude::*;
877    /// let a = [(1, 3), (8, 8), (10, 11)].to_interval_set();
878    /// let b = [(2, 5), (7, 8), (12, 15)].to_interval_set();
879    /// let symmetric_difference = [(1, 1), (4, 5), (7, 7), (10, 15)].to_interval_set();
880    /// assert_eq!(a.symmetric_difference(&b), symmetric_difference);
881    /// assert_eq!(b.symmetric_difference(&a), symmetric_difference);
882    ///
883    /// assert_eq!(IntervalSet::union(&a.difference(&b), &b.difference(&a)), symmetric_difference);
884    /// ```
885    fn symmetric_difference(&self, rhs: &IntervalSet<Bound>) -> IntervalSet<Bound> {
886        let union = self.union(rhs);
887        let intersection = self.intersection(rhs);
888        union.difference(&intersection)
889    }
890}
891
892impl<Bound: Width + Num> Overlap for IntervalSet<Bound> {
893    /// Calculates whether two interval contain any shared values.
894    /// ```
895    /// # use interval::prelude::*;
896    /// let a = [(1, 3), (7, 8)].to_interval_set();
897    /// let b = [(4, 6)].to_interval_set();
898    /// assert!(!a.overlap(&b));
899    /// assert!(!b.overlap(&a));
900    ///
901    /// let a = [(1, 3)].to_interval_set();
902    /// let b = [(3, 4), (8, 10)].to_interval_set();
903    /// assert!(a.overlap(&b));
904    /// assert!(b.overlap(&a));
905    /// ```
906    fn overlap(&self, rhs: &IntervalSet<Bound>) -> bool {
907        let a = &mut self.intervals.iter().cloned().peekable();
908        let b = &mut rhs.intervals.iter().cloned().peekable();
909        advance_to_first_overlapping(a, b)
910    }
911}
912
913impl<Bound: Width + Num> Overlap<Bound> for IntervalSet<Bound> {
914    /// Calculates whether a value is included in the interval set.
915    /// This returns the same result as the [`IntervalSet::contains`]
916    /// ```
917    /// # use interval::prelude::*;
918    /// let interval_set = [(3, 5), (8, 9)].to_interval_set();
919    /// assert!(interval_set.overlap(&3));
920    /// assert!(interval_set.overlap(&8));
921    /// assert!(interval_set.overlap(&9));
922    ///
923    /// assert!(!interval_set.overlap(&1));
924    /// assert!(!interval_set.overlap(&7));
925    /// assert!(!interval_set.overlap(&10));
926    /// ```
927    fn overlap(&self, value: &Bound) -> bool {
928        if let Some((l, u)) = self.find_interval(value) {
929            l == u
930        } else {
931            false
932        }
933    }
934}
935
936impl<Bound: Width + Num> Overlap<Optional<Bound>> for IntervalSet<Bound> {
937    /// Calculates whether an optional value is included in the interval set.
938    /// If the optional empty, this returns false.
939    /// This returns the same result as the [`IntervalSet::contains`]
940    /// ```
941    /// # use interval::prelude::*;
942    /// let interval_set = [(3, 5), (8, 9)].to_interval_set();
943    /// assert!(interval_set.overlap(&Optional::singleton(3)));
944    /// assert!(interval_set.overlap(&Optional::singleton(9)));
945    ///
946    /// assert!(!interval_set.overlap(&Optional::singleton(1)));
947    /// assert!(!interval_set.overlap(&Optional::singleton(10)));
948    ///
949    /// assert!(!interval_set.overlap(&Optional::empty()));
950    /// ```
951    fn overlap(&self, value: &Optional<Bound>) -> bool {
952        value.as_ref().map_or(false, |b| self.overlap(b))
953    }
954}
955
956macro_rules! primitive_interval_set_overlap
957{
958  ( $( $source:ty ),* ) =>
959  {$(
960    impl Overlap<IntervalSet<$source>> for $source {
961      #[doc = concat!(
962        r#"
963        Calculates whether a value is included in an interval set.
964        ```
965        # use interval::prelude::*;
966        let interval_set: IntervalSet<"#, stringify!($source), r#"> = [(3, 5), (8, 9)].to_interval_set();
967        assert!((3 as "#, stringify!($source), r#").overlap(&interval_set));
968        assert!((8 as "#, stringify!($source), r#").overlap(&interval_set));
969        assert!((9 as "#, stringify!($source), r#").overlap(&interval_set));
970        ///
971        assert!(!(1 as "#, stringify!($source), r#").overlap(&interval_set));
972        assert!(!(7 as "#, stringify!($source), r#").overlap(&interval_set));
973        assert!(!(10 as "#, stringify!($source), r#").overlap(&interval_set));
974        ```
975        "#
976      )]
977      fn overlap(&self, other: &IntervalSet<$source>) -> bool {
978        other.overlap(self)
979      }
980    }
981  )*}
982}
983
984primitive_interval_set_overlap!(i8, u8, i16, u16, i32, u32, i64, u64, isize, usize);
985
986impl<Bound: Width + Num> Disjoint for IntervalSet<Bound> {
987    /// Calculates whether two interval do *not* contain any shared values.
988    /// ```
989    /// # use interval::prelude::*;
990    /// let a = [(1, 3), (7, 8)].to_interval_set();
991    /// let b = [(4, 6)].to_interval_set();
992    /// assert!(a.is_disjoint(&b));
993    /// assert!(b.is_disjoint(&a));
994    ///
995    /// let a = [(1, 3)].to_interval_set();
996    /// let b = [(3, 4), (8, 10)].to_interval_set();
997    /// assert!(!a.is_disjoint(&b));
998    /// assert!(!b.is_disjoint(&a));
999    /// ```
1000    fn is_disjoint(&self, rhs: &IntervalSet<Bound>) -> bool {
1001        !self.overlap(rhs)
1002    }
1003}
1004
1005impl<Bound: Width + Num> ShrinkLeft for IntervalSet<Bound>
1006where
1007    <Bound as Width>::Output: Clone,
1008{
1009    /// Updates the lower bound of an interval set to be greater than or equal to a value.
1010    /// ```
1011    /// # use interval::prelude::*;
1012    /// let interval_set = [(4, 5), (8, 8)].to_interval_set();
1013    /// assert_eq!(interval_set.shrink_left(2), interval_set);
1014    /// assert_eq!(interval_set.shrink_left(4), interval_set);
1015    /// assert_eq!(interval_set.shrink_left(5), [(5, 5), (8, 8)].to_interval_set());
1016    /// assert_eq!(interval_set.shrink_left(7), IntervalSet::singleton(8));
1017    /// assert_eq!(interval_set.shrink_left(8), IntervalSet::singleton(8));
1018    /// assert_eq!(interval_set.shrink_left(9), IntervalSet::empty());
1019    /// ```
1020    fn shrink_left(&self, lb: Bound) -> IntervalSet<Bound> {
1021        if let Some((left, _)) = self.find_interval(&lb) {
1022            let mut res = IntervalSet::empty();
1023            if self.intervals[left].upper() >= lb {
1024                res.push(Interval::new(lb, self.intervals[left].upper()));
1025            }
1026            for i in (left + 1)..self.intervals.len() {
1027                res.push(self.intervals[i].clone());
1028            }
1029            res
1030        } else if self.is_empty() || lb > self.back().upper() {
1031            IntervalSet::empty()
1032        } else {
1033            self.clone()
1034        }
1035    }
1036}
1037
1038impl<Bound: Width + Num> ShrinkRight for IntervalSet<Bound>
1039where
1040    <Bound as Width>::Output: Clone,
1041{
1042    /// Updates the upper bound of an interval set to be less than or equal to a value.
1043    /// ```
1044    /// # use interval::prelude::*;
1045    /// let interval_set = [(3, 3), (7, 8)].to_interval_set();
1046    /// assert_eq!(interval_set.shrink_right(9), interval_set);
1047    /// assert_eq!(interval_set.shrink_right(8), interval_set);
1048    /// assert_eq!(interval_set.shrink_right(7), [(3, 3), (7, 7)].to_interval_set());
1049    /// assert_eq!(interval_set.shrink_right(6), IntervalSet::singleton(3));
1050    /// assert_eq!(interval_set.shrink_right(3), IntervalSet::singleton(3));
1051    /// assert_eq!(interval_set.shrink_right(2), IntervalSet::empty());
1052    /// ```
1053    fn shrink_right(&self, ub: Bound) -> IntervalSet<Bound> {
1054        if let Some((_, right)) = self.find_interval(&ub) {
1055            let mut res = IntervalSet::empty();
1056            for i in 0..right {
1057                res.push(self.intervals[i].clone());
1058            }
1059            if self.intervals[right].lower() <= ub {
1060                res.push(Interval::new(self.intervals[right].lower(), ub));
1061            }
1062            res
1063        } else if self.is_empty() || ub < self.front().lower() {
1064            IntervalSet::empty()
1065        } else {
1066            self.clone()
1067        }
1068    }
1069}
1070
1071impl<Bound: Width + Num> Subset for IntervalSet<Bound> {
1072    /// Calculates whether one interval set is contained in another.
1073    /// The empty interval set is a subset of everything.
1074    /// ```
1075    /// # use interval::prelude::*;
1076    /// let interval_set = [(3, 3), (7, 8)].to_interval_set();
1077    /// assert!(interval_set.is_subset(&[(3, 8)].to_interval_set()));
1078    /// assert!(interval_set.is_subset(&[(3, 4), (7, 9)].to_interval_set()));
1079    /// assert!(interval_set.is_subset(&interval_set));
1080    ///
1081    /// assert!(!interval_set.is_subset(&[(3, 3)].to_interval_set()));
1082    /// assert!(!interval_set.is_subset(&[(7, 9)].to_interval_set()));
1083    /// assert!(!interval_set.is_subset(&[(3, 3), (8, 9)].to_interval_set()));
1084    ///
1085    /// assert!(IntervalSet::<usize>::empty().is_subset(&IntervalSet::empty()));
1086    /// assert!(IntervalSet::empty().is_subset(&interval_set));
1087    /// ```
1088    fn is_subset(&self, other: &IntervalSet<Bound>) -> bool {
1089        if self.is_empty() {
1090            true
1091        } else if self.size() > other.size() || !self.span().is_subset(&other.span()) {
1092            false
1093        } else {
1094            let mut left = 0;
1095            let right = other.intervals.len() - 1;
1096            for interval in &self.intervals {
1097                let (l, r) = other.find_interval_between(&interval.lower(), left, right);
1098                if l == r && interval.is_subset(&other.intervals[l]) {
1099                    left = l;
1100                } else {
1101                    return false;
1102                }
1103            }
1104            true
1105        }
1106    }
1107}
1108
1109impl<Bound: Width + Num> ProperSubset for IntervalSet<Bound> {
1110    /// Calculates whether one interval set is contained in another,
1111    /// but they are not equal.
1112    /// The empty interval set is a proper subset of everything, except itself.
1113    /// ```
1114    /// # use interval::prelude::*;
1115    /// let interval_set = [(3, 3), (7, 8)].to_interval_set();
1116    /// assert!(interval_set.is_proper_subset(&[(3, 8)].to_interval_set()));
1117    /// assert!(interval_set.is_proper_subset(&[(3, 4), (7, 9)].to_interval_set()));
1118    ///
1119    /// assert!(!interval_set.is_proper_subset(&interval_set));
1120    /// assert!(!interval_set.is_proper_subset(&[(3, 3)].to_interval_set()));
1121    /// assert!(!interval_set.is_proper_subset(&[(7, 9)].to_interval_set()));
1122    /// assert!(!interval_set.is_proper_subset(&[(3, 3), (8, 9)].to_interval_set()));
1123    ///
1124    /// assert!(IntervalSet::empty().is_proper_subset(&interval_set));
1125    /// assert!(!IntervalSet::<usize>::empty().is_proper_subset(&IntervalSet::empty()));
1126    /// ```
1127    fn is_proper_subset(&self, other: &IntervalSet<Bound>) -> bool {
1128        self.is_subset(other) && self.size() != other.size()
1129    }
1130}
1131
1132forward_all_binop!(impl<Bound: +Num+Width> Add for IntervalSet<Bound>, add);
1133
1134impl<'a, 'b, Bound: Num + Width> Add<&'b IntervalSet<Bound>> for &'a IntervalSet<Bound> {
1135    type Output = IntervalSet<Bound>;
1136
1137    /// Calculates all values that could result in the addition of two items from each interval set.
1138    /// ```
1139    /// # use interval::prelude::*;
1140    /// let a = [(1, 2), (5, 6)].to_interval_set();
1141    /// let b = [(1, 1), (4, 5)].to_interval_set();
1142    /// assert_eq!(a + b, [(2, 3), (5, 7), (9, 11)].to_interval_set());
1143    /// ```
1144    /// This method preserves empty interval sets.
1145    /// ```
1146    /// # use interval::prelude::*;
1147    /// let a = [(1, 1), (4, 5)].to_interval_set();
1148    /// let b = IntervalSet::empty();
1149    /// assert!((a + b).is_empty());
1150    /// ```
1151    fn add(self, other: &IntervalSet<Bound>) -> IntervalSet<Bound> {
1152        self.for_all_pairs(other, |i, j| i + j)
1153    }
1154}
1155
1156forward_all_binop!(impl<Bound: +Num+Width+Clone> Add for IntervalSet<Bound>, add, Bound);
1157
1158impl<'a, 'b, Bound: Num + Width + Clone> Add<&'b Bound> for &'a IntervalSet<Bound> {
1159    type Output = IntervalSet<Bound>;
1160
1161    /// Adds a constant to an interval set.
1162    /// ```
1163    /// # use interval::prelude::*;
1164    /// assert_eq!([(3, 3), (7, 8)].to_interval_set() + 2, [(5, 5), (9, 10)].to_interval_set());
1165    /// ```
1166    /// This method preserves empty interval sets.
1167    /// ```
1168    /// # use interval::prelude::*;
1169    /// assert!((IntervalSet::empty() + 4).is_empty());
1170    /// ```
1171    /// It is not possible to add an interval set to a constant.
1172    /// ```compile_fail
1173    /// # use interval::prelude::*;
1174    /// let _ = 4 + IntervalSet::new(5, 9); // doesn't compile
1175    /// ```
1176    fn add(self, other: &Bound) -> IntervalSet<Bound> {
1177        self.stable_map(|x| x + other.clone())
1178    }
1179}
1180
1181forward_all_binop!(impl<Bound: +Num+Width> Sub for IntervalSet<Bound>, sub);
1182
1183impl<'a, 'b, Bound: Num + Width> Sub<&'b IntervalSet<Bound>> for &'a IntervalSet<Bound> {
1184    type Output = IntervalSet<Bound>;
1185
1186    fn sub(self, other: &IntervalSet<Bound>) -> IntervalSet<Bound> {
1187        self.for_all_pairs(other, |i, j| i - j)
1188    }
1189}
1190
1191forward_all_binop!(impl<Bound: +Num+Width+Clone> Sub for IntervalSet<Bound>, sub, Bound);
1192
1193impl<'a, 'b, Bound: Num + Width + Clone> Sub<&'b Bound> for &'a IntervalSet<Bound> {
1194    type Output = IntervalSet<Bound>;
1195
1196    /// Subtracts a constant from an interval set.
1197    /// ```
1198    /// # use interval::prelude::*;
1199    /// assert_eq!([(3, 3), (7, 8)].to_interval_set() - 2, [(1, 1), (5, 6)].to_interval_set());
1200    /// ```
1201    /// This method preserves empty interval sets.
1202    /// ```
1203    /// # use interval::prelude::*;
1204    /// assert!((IntervalSet::empty() - 4).is_empty());
1205    /// ```
1206    /// It is not possible to substract an interval set from a constant.
1207    /// ```compile_fail
1208    /// # use interval::prelude::*;
1209    /// let _ = 10 - IntervalSet::new(5, 9); // doesn't compile
1210    /// ```
1211    fn sub(self, other: &Bound) -> IntervalSet<Bound> {
1212        self.stable_map(|x| x - other.clone())
1213    }
1214}
1215
1216forward_all_binop!(impl<Bound: +Num+Width> Mul for IntervalSet<Bound>, mul);
1217
1218impl<'a, 'b, Bound: Num + Width> Mul<&'b IntervalSet<Bound>> for &'a IntervalSet<Bound> {
1219    type Output = IntervalSet<Bound>;
1220
1221    /// Calculates all values that could result in the multiplication of two items from each interval set.
1222    /// Caution: the resulting interval set is an over-approxmation for the same reason as [`Interval::mul`](../interval/struct.Interval.html#method.mul-3).
1223    /// ```
1224    /// # use interval::prelude::*;
1225    /// let a = [(1, 2), (5, 6)].to_interval_set();
1226    /// let b = [(0, 0), (3, 4)].to_interval_set();
1227    /// assert_eq!(a * b, [(0, 0), (3, 8), (15, 24)].to_interval_set());
1228    /// ```
1229    /// This method preserves empty interval sets.
1230    /// ```
1231    /// # use interval::prelude::*;
1232    /// assert!((IntervalSet::empty() * [(0, 0), (3, 4)].to_interval_set()).is_empty());
1233    /// ```
1234    fn mul(self, other: &IntervalSet<Bound>) -> IntervalSet<Bound> {
1235        self.for_all_pairs(other, |i, j| i * j)
1236    }
1237}
1238
1239forward_all_binop!(impl<Bound: +Num+Width+Clone> Mul for IntervalSet<Bound>, mul, Bound);
1240
1241impl<'a, 'b, Bound: Num + Width + Clone> Mul<&'b Bound> for &'a IntervalSet<Bound> {
1242    type Output = IntervalSet<Bound>;
1243
1244    /// Multiplies an interval set by a constant.
1245    /// Caution: the resulting interval set is an over-approxmation for the same reason as [`Interval::mul`](../interval/struct.Interval.html#method.mul-7).
1246    /// ```
1247    /// # use interval::prelude::*;
1248    /// assert_eq!([(1, 2), (5, 6)].to_interval_set() * 2, [(2, 4), (10, 12)].to_interval_set());
1249    /// ```
1250    /// This method preserves empty interval sets.
1251    /// ```
1252    /// # use interval::prelude::*;
1253    /// assert!((IntervalSet::empty() * 11).is_empty());
1254    /// ```
1255    /// It is not possible to multiply a constant by an interval set.
1256    /// ```compile_fail
1257    /// # use interval::prelude::*;
1258    /// let _ = 4 * IntervalSet::new(5, 9); // doesn't compile
1259    /// ```
1260    fn mul(self, other: &Bound) -> IntervalSet<Bound> {
1261        if self.is_empty() {
1262            IntervalSet::empty()
1263        } else if other == &Bound::zero() {
1264            IntervalSet::singleton(Bound::zero())
1265        } else if other == &Bound::one() {
1266            self.clone()
1267        } else {
1268            self.map(|i| i * other.clone())
1269        }
1270    }
1271}
1272
1273pub trait ToIntervalSet<Bound>
1274where
1275    Bound: Width,
1276{
1277    /// Converts a value to an interval set.
1278    /// For example,
1279    /// ```
1280    /// # use interval::prelude::*;
1281    /// assert_eq!((3, 4).to_interval_set(), IntervalSet::new(3, 4));
1282    /// assert_eq!([(2, 5), (7, 8)].to_interval_set(), IntervalSet::union(&IntervalSet::new(2, 5), &IntervalSet::new(7, 8)));
1283    /// ```
1284    fn to_interval_set(self) -> IntervalSet<Bound>;
1285}
1286
1287impl<Bound: Width + Num> ToIntervalSet<Bound> for (Bound, Bound) {
1288    /// Converts a tuple to an interval set using the first element as the lower bound
1289    /// and second element as the upper bound.
1290    /// ```
1291    /// # use interval::prelude::*;
1292    /// assert_eq!((2, 6).to_interval_set(), IntervalSet::new(2, 6));
1293    /// ```
1294    /// The first and second elements need the same type.
1295    /// ```compile_fail
1296    /// # use interval::prelude::*;
1297    /// let _ = (8 as u8, 9 as i8).to_interval_set(); // doesn't compile
1298    /// ```
1299    fn to_interval_set(self) -> IntervalSet<Bound> {
1300        [self].to_interval_set()
1301    }
1302}
1303
1304impl<Bound> ToIntervalSet<Bound> for Vec<(Bound, Bound)>
1305where
1306    Bound: Width + Num,
1307{
1308    /// Converts a vector of intervals to an interval set.
1309    /// ```
1310    /// # use interval::prelude::*;
1311    /// assert_eq!(vec![(2, 5)].to_interval_set().interval_count(), 1);
1312    /// assert_eq!(vec![(1, 5), (11, 20)].to_interval_set().interval_count(), 2);
1313    /// assert!(Vec::<(usize, usize)>::new().to_interval_set().is_empty());
1314    /// ```
1315    fn to_interval_set(self) -> IntervalSet<Bound> {
1316        let mut intervals = IntervalSet::empty();
1317        let mut to_add: Vec<_> = self.into_iter().map(|i| i.to_interval()).collect();
1318        to_add.sort_unstable_by_key(|i| i.lower());
1319        intervals.extend_at_back(to_add);
1320        intervals
1321    }
1322}
1323
1324impl<Bound> ToIntervalSet<Bound> for &[(Bound, Bound)]
1325where
1326    Bound: Width + Num + Copy,
1327{
1328    /// Converts an array to an interval set.
1329    /// ```
1330    /// # use interval::prelude::*;
1331    /// assert_eq!([(2, 5)].to_interval_set().interval_count(), 1);
1332    /// assert_eq!([(1, 5), (11, 20)].to_interval_set().interval_count(), 2);
1333    /// assert!(<&[(usize, usize)]>::default().to_interval_set().is_empty());
1334    /// ```
1335    fn to_interval_set(self) -> IntervalSet<Bound> {
1336        self.to_vec().to_interval_set()
1337    }
1338}
1339
1340impl<Bound, const N: usize> ToIntervalSet<Bound> for [(Bound, Bound); N]
1341where
1342    Bound: Width + Num + Clone,
1343{
1344    /// Converts a fixed-length array to an interval set.
1345    /// ```
1346    /// # use interval::prelude::*;
1347    /// assert_eq!([(2, 5)].to_interval_set().interval_count(), 1);
1348    /// assert_eq!([(1, 5), (11, 20)].to_interval_set().interval_count(), 2);
1349    /// assert!(([] as [(usize, usize); 0]).to_interval_set().is_empty());
1350    /// ```
1351    fn to_interval_set(self) -> IntervalSet<Bound> {
1352        self.to_vec().to_interval_set()
1353    }
1354}
1355
1356impl<Bound: Display + Width + Num> Display for IntervalSet<Bound>
1357where
1358    <Bound as Width>::Output: Display,
1359{
1360    /// Formats an interval set.
1361    /// Empty interval sets are displayed as the empty set "{}".
1362    /// Single intervals are displayed as the isolated interval.
1363    /// Combined intervals are displayed as a sorted set of intervals.
1364    /// See [`Interval::fmt`](../interval/struct.Interval.html#method.fmt-1) for more detail on how intervals are formatted.
1365    /// ```
1366    /// # use interval::prelude::*;
1367    /// assert_eq!(format!("{}", [(3, 5)].to_interval_set()), "[3..5]");
1368    /// assert_eq!(format!("{}", [(4, 4), (8, 9)].to_interval_set()), "{[4..4][8..9]}");
1369    /// assert_eq!(format!("{}", IntervalSet::<u32>::empty()), "{}");
1370    /// ```
1371    fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
1372        if self.intervals.len() == 1 {
1373            self.intervals[0].fmt(formatter)
1374        } else {
1375            formatter.write_str("{")?;
1376            for interval in &self.intervals {
1377                formatter.write_fmt(format_args!("{}", interval))?;
1378            }
1379            formatter.write_str("}")
1380        }
1381    }
1382}
1383
1384impl<Bound> Join for IntervalSet<Bound>
1385where
1386    Bound: Width + Num,
1387{
1388    fn join(self, other: IntervalSet<Bound>) -> IntervalSet<Bound> {
1389        self.intersection(&other)
1390    }
1391}
1392
1393impl<Bound> Meet for IntervalSet<Bound>
1394where
1395    Bound: Width + Num,
1396{
1397    fn meet(self, other: IntervalSet<Bound>) -> IntervalSet<Bound> {
1398        self.union(&other)
1399    }
1400}
1401
1402impl<Bound> Entailment for IntervalSet<Bound>
1403where
1404    Bound: Width + Num,
1405{
1406    fn entail(&self, other: &IntervalSet<Bound>) -> SKleene {
1407        if self.is_subset(other) {
1408            SKleene::True
1409        } else if other.is_subset(self) {
1410            SKleene::False
1411        } else {
1412            SKleene::Unknown
1413        }
1414    }
1415}
1416
1417impl<Bound> Top for IntervalSet<Bound>
1418where
1419    Bound: Width + Num,
1420{
1421    fn top() -> IntervalSet<Bound> {
1422        IntervalSet::empty()
1423    }
1424}
1425
1426impl<Bound> Bot for IntervalSet<Bound>
1427where
1428    Bound: Width + Num,
1429{
1430    fn bot() -> IntervalSet<Bound> {
1431        IntervalSet::whole()
1432    }
1433}
1434
1435#[allow(non_upper_case_globals)]
1436#[cfg(test)]
1437mod tests {
1438    use serde_test::{assert_tokens, Token};
1439
1440    use super::*;
1441
1442    const extend_example: [(i32, i32); 2] = [(11, 33), (-55, -44)];
1443
1444    fn test_inside_outside(is: IntervalSet<i32>, inside: Vec<i32>, outside: Vec<i32>) {
1445        for i in &inside {
1446            assert!(
1447                is.contains(i),
1448                "{} is not contained inside {}, but it should.",
1449                i,
1450                is
1451            );
1452        }
1453        for i in &outside {
1454            assert!(
1455                !is.contains(i),
1456                "{} is contained inside {}, but it should not.",
1457                i,
1458                is
1459            );
1460        }
1461    }
1462
1463    // precondition: `intervals` must be a valid intern representation of the interval set.
1464    fn make_interval_set(intervals: Vec<(i32, i32)>) -> IntervalSet<i32> {
1465        intervals.to_interval_set()
1466    }
1467
1468    fn test_result(test_id: String, result: &IntervalSet<i32>, expected: &IntervalSet<i32>) {
1469        assert!(
1470            result.intervals == expected.intervals,
1471            "{} | {} is different from the expected value: {}.",
1472            test_id,
1473            result,
1474            expected
1475        );
1476    }
1477
1478    fn test_binary_op_sym<F>(
1479        test_id: String,
1480        a: Vec<(i32, i32)>,
1481        b: Vec<(i32, i32)>,
1482        op: F,
1483        expected: Vec<(i32, i32)>,
1484    ) where
1485        F: Fn(&IntervalSet<i32>, &IntervalSet<i32>) -> IntervalSet<i32>,
1486    {
1487        test_binary_op(
1488            test_id.clone(),
1489            a.clone(),
1490            b.clone(),
1491            |i, j| op(i, j),
1492            expected.clone(),
1493        );
1494        test_binary_op(test_id, b, a, op, expected);
1495    }
1496
1497    fn test_binary_op<F>(
1498        test_id: String,
1499        a: Vec<(i32, i32)>,
1500        b: Vec<(i32, i32)>,
1501        op: F,
1502        expected: Vec<(i32, i32)>,
1503    ) where
1504        F: Fn(&IntervalSet<i32>, &IntervalSet<i32>) -> IntervalSet<i32>,
1505    {
1506        println!("Info: {}.", test_id);
1507        let a = make_interval_set(a);
1508        let b = make_interval_set(b);
1509        let expected = make_interval_set(expected);
1510        test_result(test_id, &op(&a, &b), &expected);
1511    }
1512
1513    fn test_binary_value_op<F>(
1514        test_id: String,
1515        a: Vec<(i32, i32)>,
1516        b: i32,
1517        op: F,
1518        expected: Vec<(i32, i32)>,
1519    ) where
1520        F: Fn(&IntervalSet<i32>, i32) -> IntervalSet<i32>,
1521    {
1522        println!("Info: {}.", test_id);
1523        let a = make_interval_set(a);
1524        let expected = make_interval_set(expected);
1525        test_result(test_id, &op(&a, b), &expected);
1526    }
1527
1528    fn test_binary_bool_op_sym<F>(
1529        test_id: String,
1530        a: Vec<(i32, i32)>,
1531        b: Vec<(i32, i32)>,
1532        op: F,
1533        expected: bool,
1534    ) where
1535        F: Fn(&IntervalSet<i32>, &IntervalSet<i32>) -> bool,
1536    {
1537        test_binary_bool_op(
1538            test_id.clone(),
1539            a.clone(),
1540            b.clone(),
1541            |i, j| op(i, j),
1542            expected,
1543        );
1544        test_binary_bool_op(test_id, b, a, op, expected);
1545    }
1546
1547    fn test_binary_bool_op<F>(
1548        test_id: String,
1549        a: Vec<(i32, i32)>,
1550        b: Vec<(i32, i32)>,
1551        op: F,
1552        expected: bool,
1553    ) where
1554        F: Fn(&IntervalSet<i32>, &IntervalSet<i32>) -> bool,
1555    {
1556        println!("Info: {}.", test_id);
1557        let a = make_interval_set(a);
1558        let b = make_interval_set(b);
1559        assert_eq!(op(&a, &b), expected);
1560    }
1561
1562    fn test_binary_value_bool_op<V, F>(
1563        test_id: String,
1564        a: Vec<(i32, i32)>,
1565        b: V,
1566        op: F,
1567        expected: bool,
1568    ) where
1569        F: Fn(&IntervalSet<i32>, &V) -> bool,
1570    {
1571        println!("Info: {}.", test_id);
1572        let a = make_interval_set(a);
1573        assert_eq!(op(&a, &b), expected);
1574    }
1575
1576    fn test_op<F>(test_id: String, a: Vec<(i32, i32)>, op: F, expected: Vec<(i32, i32)>)
1577    where
1578        F: Fn(&IntervalSet<i32>) -> IntervalSet<i32>,
1579    {
1580        println!("Info: {}.", test_id);
1581        let a = make_interval_set(a);
1582        let expected = make_interval_set(expected);
1583        let result = op(&a);
1584        test_result(test_id, &result, &expected);
1585    }
1586
1587    #[test]
1588    fn test_contains() {
1589        let cases = vec![
1590            (vec![], vec![], vec![-2, -1, 0, 1, 2]),
1591            (vec![(1, 2)], vec![1, 2], vec![-1, 0, 3, 4]),
1592            (
1593                vec![(1, 2), (7, 9)],
1594                vec![1, 2, 7, 8, 9],
1595                vec![-1, 0, 3, 4, 5, 6, 10, 11],
1596            ),
1597            (
1598                vec![(1, 2), (4, 5), (7, 9)],
1599                vec![1, 2, 4, 5, 7, 8, 9],
1600                vec![-1, 0, 3, 6, 10, 11],
1601            ),
1602        ];
1603
1604        for (is, inside, outside) in cases {
1605            let is = make_interval_set(is);
1606            test_inside_outside(is, inside, outside);
1607        }
1608    }
1609
1610    #[test]
1611    fn test_complement() {
1612        let min = <i32 as Width>::min_value();
1613        let max = <i32 as Width>::max_value();
1614
1615        let cases = vec![
1616            (1, vec![], vec![(min, max)]),
1617            (2, vec![(min, max)], vec![]),
1618            (3, vec![(0, 0)], vec![(min, -1), (1, max)]),
1619            (4, vec![(-5, 5)], vec![(min, -6), (6, max)]),
1620            (5, vec![(-5, -1), (1, 5)], vec![(min, -6), (0, 0), (6, max)]),
1621            (6, vec![(min, -1), (1, 5)], vec![(0, 0), (6, max)]),
1622            (7, vec![(-5, -1), (1, max)], vec![(min, -6), (0, 0)]),
1623            (8, vec![(min, -1), (1, max)], vec![(0, 0)]),
1624            (
1625                9,
1626                vec![(-5, -3), (0, 1), (3, 5)],
1627                vec![(min, -6), (-2, -1), (2, 2), (6, max)],
1628            ),
1629        ];
1630
1631        for (id, a, expected) in cases {
1632            test_op(
1633                format!("test #{} of complement", id),
1634                a.clone(),
1635                |x| x.complement(),
1636                expected,
1637            );
1638            test_op(
1639                format!("test #{} of complement(complement)", id),
1640                a.clone(),
1641                |x| x.complement().complement(),
1642                a,
1643            );
1644        }
1645    }
1646
1647    #[test]
1648    fn test_union() {
1649        // Note: the first number is the test id, so it should be easy to identify which test has failed.
1650        // The two first vectors are the operands and the expected result is last.
1651        let sym_cases = vec![
1652            // identity tests
1653            (1, vec![], vec![], vec![]),
1654            (2, vec![], vec![(1, 2)], vec![(1, 2)]),
1655            (3, vec![], vec![(1, 2), (7, 9)], vec![(1, 2), (7, 9)]),
1656            (4, vec![(1, 2), (7, 9)], vec![(1, 2)], vec![(1, 2), (7, 9)]),
1657            (
1658                5,
1659                vec![(1, 2), (7, 9)],
1660                vec![(1, 2), (7, 9)],
1661                vec![(1, 2), (7, 9)],
1662            ),
1663            // front tests
1664            (
1665                6,
1666                vec![(-3, -1)],
1667                vec![(1, 2), (7, 9)],
1668                vec![(-3, -1), (1, 2), (7, 9)],
1669            ),
1670            (
1671                7,
1672                vec![(-3, 0)],
1673                vec![(1, 2), (7, 9)],
1674                vec![(-3, 2), (7, 9)],
1675            ),
1676            (
1677                8,
1678                vec![(-3, 1)],
1679                vec![(1, 2), (7, 9)],
1680                vec![(-3, 2), (7, 9)],
1681            ),
1682            // middle tests
1683            (9, vec![(2, 7)], vec![(1, 2), (7, 9)], vec![(1, 9)]),
1684            (10, vec![(3, 7)], vec![(1, 2), (7, 9)], vec![(1, 9)]),
1685            (
1686                11,
1687                vec![(4, 5)],
1688                vec![(1, 2), (7, 9)],
1689                vec![(1, 2), (4, 5), (7, 9)],
1690            ),
1691            (12, vec![(2, 8)], vec![(1, 2), (7, 9)], vec![(1, 9)]),
1692            (13, vec![(2, 6)], vec![(1, 2), (7, 9)], vec![(1, 9)]),
1693            (14, vec![(3, 6)], vec![(1, 2), (7, 9)], vec![(1, 9)]),
1694            // back tests
1695            (15, vec![(8, 9)], vec![(1, 2), (7, 9)], vec![(1, 2), (7, 9)]),
1696            (
1697                16,
1698                vec![(8, 10)],
1699                vec![(1, 2), (7, 9)],
1700                vec![(1, 2), (7, 10)],
1701            ),
1702            (
1703                17,
1704                vec![(9, 10)],
1705                vec![(1, 2), (7, 9)],
1706                vec![(1, 2), (7, 10)],
1707            ),
1708            (
1709                18,
1710                vec![(6, 10)],
1711                vec![(1, 2), (7, 9)],
1712                vec![(1, 2), (6, 10)],
1713            ),
1714            (
1715                19,
1716                vec![(10, 11)],
1717                vec![(1, 2), (7, 9)],
1718                vec![(1, 2), (7, 11)],
1719            ),
1720            (
1721                20,
1722                vec![(11, 12)],
1723                vec![(1, 2), (7, 9)],
1724                vec![(1, 2), (7, 9), (11, 12)],
1725            ),
1726            // mixed tests
1727            (
1728                21,
1729                vec![(-3, -1), (4, 5), (11, 12)],
1730                vec![(1, 2), (7, 9)],
1731                vec![(-3, -1), (1, 2), (4, 5), (7, 9), (11, 12)],
1732            ),
1733            (
1734                22,
1735                vec![(-3, 0), (3, 6), (10, 11)],
1736                vec![(1, 2), (7, 9)],
1737                vec![(-3, 11)],
1738            ),
1739            (
1740                23,
1741                vec![(-3, 1), (3, 7), (9, 11)],
1742                vec![(1, 2), (7, 9)],
1743                vec![(-3, 11)],
1744            ),
1745            (
1746                24,
1747                vec![(-3, 5), (7, 11)],
1748                vec![(1, 2), (7, 9)],
1749                vec![(-3, 5), (7, 11)],
1750            ),
1751            (
1752                25,
1753                vec![(-3, 5), (7, 8), (12, 12)],
1754                vec![(1, 2), (7, 9)],
1755                vec![(-3, 5), (7, 9), (12, 12)],
1756            ),
1757            // englobing tests
1758            (26, vec![(-1, 11)], vec![(1, 2), (7, 9)], vec![(-1, 11)]),
1759        ];
1760
1761        for (id, a, b, expected) in sym_cases {
1762            test_binary_op_sym(
1763                format!("test #{} of union", id),
1764                a,
1765                b,
1766                |x, y| x.union(y),
1767                expected,
1768            );
1769        }
1770    }
1771
1772    #[test]
1773    fn test_intersection() {
1774        // Note: the first number is the test id, so it should be easy to identify which test has failed.
1775        // The two first vectors are the operands and the expected result is last.
1776        let sym_cases = vec![
1777            // identity tests
1778            (1, vec![], vec![], vec![]),
1779            (2, vec![], vec![(1, 2)], vec![]),
1780            (3, vec![], vec![(1, 2), (7, 9)], vec![]),
1781            (4, vec![(1, 2), (7, 9)], vec![(1, 2)], vec![(1, 2)]),
1782            (
1783                5,
1784                vec![(1, 2), (7, 9)],
1785                vec![(1, 2), (7, 9)],
1786                vec![(1, 2), (7, 9)],
1787            ),
1788            // front tests
1789            (6, vec![(-3, -1)], vec![(1, 2), (7, 9)], vec![]),
1790            (7, vec![(-3, 0)], vec![(1, 2), (7, 9)], vec![]),
1791            (8, vec![(-3, 1)], vec![(1, 2), (7, 9)], vec![(1, 1)]),
1792            // middle tests
1793            (9, vec![(2, 7)], vec![(1, 2), (7, 9)], vec![(2, 2), (7, 7)]),
1794            (10, vec![(3, 7)], vec![(1, 2), (7, 9)], vec![(7, 7)]),
1795            (11, vec![(4, 5)], vec![(1, 2), (7, 9)], vec![]),
1796            (12, vec![(2, 8)], vec![(1, 2), (7, 9)], vec![(2, 2), (7, 8)]),
1797            (13, vec![(2, 6)], vec![(1, 2), (7, 9)], vec![(2, 2)]),
1798            (14, vec![(3, 6)], vec![(1, 2), (7, 9)], vec![]),
1799            // back tests
1800            (15, vec![(8, 9)], vec![(1, 2), (7, 9)], vec![(8, 9)]),
1801            (16, vec![(8, 10)], vec![(1, 2), (7, 9)], vec![(8, 9)]),
1802            (17, vec![(9, 10)], vec![(1, 2), (7, 9)], vec![(9, 9)]),
1803            (18, vec![(6, 10)], vec![(1, 2), (7, 9)], vec![(7, 9)]),
1804            (19, vec![(10, 11)], vec![(1, 2), (7, 9)], vec![]),
1805            (20, vec![(11, 12)], vec![(1, 2), (7, 9)], vec![]),
1806            // mixed tests
1807            (
1808                21,
1809                vec![(-3, -1), (4, 5), (11, 12)],
1810                vec![(1, 2), (7, 9)],
1811                vec![],
1812            ),
1813            (
1814                22,
1815                vec![(-3, 0), (3, 6), (10, 11)],
1816                vec![(1, 2), (7, 9)],
1817                vec![],
1818            ),
1819            (
1820                23,
1821                vec![(-3, 1), (3, 7), (9, 11)],
1822                vec![(1, 2), (7, 9)],
1823                vec![(1, 1), (7, 7), (9, 9)],
1824            ),
1825            (
1826                24,
1827                vec![(-3, 5), (7, 11)],
1828                vec![(1, 2), (7, 9)],
1829                vec![(1, 2), (7, 9)],
1830            ),
1831            (
1832                25,
1833                vec![(-3, 5), (7, 8), (12, 12)],
1834                vec![(1, 2), (7, 9)],
1835                vec![(1, 2), (7, 8)],
1836            ),
1837            // englobing tests
1838            (
1839                26,
1840                vec![(-1, 11)],
1841                vec![(1, 2), (7, 9)],
1842                vec![(1, 2), (7, 9)],
1843            ),
1844        ];
1845
1846        for (id, a, b, expected) in sym_cases {
1847            test_binary_op_sym(
1848                format!("test #{} of intersection", id),
1849                a,
1850                b,
1851                |x, y| x.intersection(y),
1852                expected,
1853            );
1854        }
1855    }
1856
1857    #[test]
1858    fn test_to_interval_set() {
1859        // This example should not panic, and should yield the correct result.
1860        let intervals = vec![(3, 8), (2, 5)].to_interval_set();
1861        assert_eq!(intervals.interval_count(), 1);
1862        assert_eq!(intervals.lower(), 2);
1863        assert_eq!(intervals.upper(), 8);
1864    }
1865
1866    #[test]
1867    #[should_panic(
1868        expected = "This operation is only for pushing interval to the back of the array, possibly overlapping with the last element."
1869    )]
1870    fn test_extend_back() {
1871        // Calling extend_at_back with unordered input should panic.
1872        let mut set = IntervalSet::empty();
1873        let intervals = extend_example.map(|i| i.to_interval());
1874        set.extend_at_back(intervals);
1875        assert_eq!(set.interval_count(), 2);
1876    }
1877
1878    #[test]
1879    fn test_extend_empty() {
1880        // Calling extend with unordered input should not panic.
1881        let mut set = IntervalSet::empty();
1882        let intervals = extend_example.map(|i| i.to_interval());
1883        set.extend(intervals);
1884        assert_eq!(set.interval_count(), 2);
1885    }
1886
1887    #[test]
1888    fn test_extend_non_empty() {
1889        // Extending an IntervalSet with intervals that belong at the start or
1890        // the middle of the set should not panic.
1891        let mut intervals = vec![(10, 15), (20, 30)].to_interval_set();
1892        let at_start = vec![(0, 5).to_interval()];
1893        intervals.extend(at_start);
1894        let in_middle = vec![(17, 18).to_interval()];
1895        intervals.extend(in_middle);
1896
1897        assert_eq!(intervals.interval_count(), 4);
1898        assert_eq!(intervals.lower(), 0);
1899        assert_eq!(intervals.upper(), 30);
1900    }
1901
1902    #[test]
1903    fn test_difference() {
1904        // Note: the first number is the test id, so it should be easy to identify which test has failed.
1905        // The two first vectors are the operands and the two last are expected results (the first
1906        // for a.difference(b) and the second for b.difference(a)).
1907        let cases = vec![
1908            // identity tests
1909            (1, vec![], vec![], vec![], vec![]),
1910            (2, vec![], vec![(1, 2)], vec![], vec![(1, 2)]),
1911            (
1912                3,
1913                vec![],
1914                vec![(1, 2), (7, 9)],
1915                vec![],
1916                vec![(1, 2), (7, 9)],
1917            ),
1918            (4, vec![(1, 2), (7, 9)], vec![(1, 2)], vec![(7, 9)], vec![]),
1919            (
1920                5,
1921                vec![(1, 2), (7, 9)],
1922                vec![(1, 2), (7, 9)],
1923                vec![],
1924                vec![],
1925            ),
1926            // front tests
1927            (
1928                6,
1929                vec![(-3, -1)],
1930                vec![(1, 2), (7, 9)],
1931                vec![(-3, -1)],
1932                vec![(1, 2), (7, 9)],
1933            ),
1934            (
1935                7,
1936                vec![(-3, 0)],
1937                vec![(1, 2), (7, 9)],
1938                vec![(-3, 0)],
1939                vec![(1, 2), (7, 9)],
1940            ),
1941            (
1942                8,
1943                vec![(-3, 1)],
1944                vec![(1, 2), (7, 9)],
1945                vec![(-3, 0)],
1946                vec![(2, 2), (7, 9)],
1947            ),
1948            // middle tests
1949            (
1950                9,
1951                vec![(2, 7)],
1952                vec![(1, 2), (7, 9)],
1953                vec![(3, 6)],
1954                vec![(1, 1), (8, 9)],
1955            ),
1956            (
1957                10,
1958                vec![(3, 7)],
1959                vec![(1, 2), (7, 9)],
1960                vec![(3, 6)],
1961                vec![(1, 2), (8, 9)],
1962            ),
1963            (
1964                11,
1965                vec![(4, 5)],
1966                vec![(1, 2), (7, 9)],
1967                vec![(4, 5)],
1968                vec![(1, 2), (7, 9)],
1969            ),
1970            (
1971                12,
1972                vec![(2, 8)],
1973                vec![(1, 2), (7, 9)],
1974                vec![(3, 6)],
1975                vec![(1, 1), (9, 9)],
1976            ),
1977            (
1978                13,
1979                vec![(2, 6)],
1980                vec![(1, 2), (7, 9)],
1981                vec![(3, 6)],
1982                vec![(1, 1), (7, 9)],
1983            ),
1984            (
1985                14,
1986                vec![(3, 6)],
1987                vec![(1, 2), (7, 9)],
1988                vec![(3, 6)],
1989                vec![(1, 2), (7, 9)],
1990            ),
1991            // back tests
1992            (
1993                15,
1994                vec![(8, 9)],
1995                vec![(1, 2), (7, 9)],
1996                vec![],
1997                vec![(1, 2), (7, 7)],
1998            ),
1999            (
2000                16,
2001                vec![(8, 10)],
2002                vec![(1, 2), (7, 9)],
2003                vec![(10, 10)],
2004                vec![(1, 2), (7, 7)],
2005            ),
2006            (
2007                17,
2008                vec![(9, 10)],
2009                vec![(1, 2), (7, 9)],
2010                vec![(10, 10)],
2011                vec![(1, 2), (7, 8)],
2012            ),
2013            (
2014                18,
2015                vec![(6, 10)],
2016                vec![(1, 2), (7, 9)],
2017                vec![(6, 6), (10, 10)],
2018                vec![(1, 2)],
2019            ),
2020            (
2021                19,
2022                vec![(10, 11)],
2023                vec![(1, 2), (7, 9)],
2024                vec![(10, 11)],
2025                vec![(1, 2), (7, 9)],
2026            ),
2027            (
2028                20,
2029                vec![(11, 12)],
2030                vec![(1, 2), (7, 9)],
2031                vec![(11, 12)],
2032                vec![(1, 2), (7, 9)],
2033            ),
2034            // mixed tests
2035            (
2036                21,
2037                vec![(-3, -1), (4, 5), (11, 12)],
2038                vec![(1, 2), (7, 9)],
2039                vec![(-3, -1), (4, 5), (11, 12)],
2040                vec![(1, 2), (7, 9)],
2041            ),
2042            (
2043                22,
2044                vec![(-3, 0), (3, 6), (10, 11)],
2045                vec![(1, 2), (7, 9)],
2046                vec![(-3, 0), (3, 6), (10, 11)],
2047                vec![(1, 2), (7, 9)],
2048            ),
2049            (
2050                23,
2051                vec![(-3, 1), (3, 7), (9, 11)],
2052                vec![(1, 2), (7, 9)],
2053                vec![(-3, 0), (3, 6), (10, 11)],
2054                vec![(2, 2), (8, 8)],
2055            ),
2056            (
2057                24,
2058                vec![(-3, 5), (7, 11)],
2059                vec![(1, 2), (7, 9)],
2060                vec![(-3, 0), (3, 5), (10, 11)],
2061                vec![],
2062            ),
2063            (
2064                25,
2065                vec![(-3, 5), (7, 8), (12, 12)],
2066                vec![(1, 2), (7, 9)],
2067                vec![(-3, 0), (3, 5), (12, 12)],
2068                vec![(9, 9)],
2069            ),
2070            // englobing tests
2071            (
2072                26,
2073                vec![(-1, 11)],
2074                vec![(1, 2), (7, 9)],
2075                vec![(-1, 0), (3, 6), (10, 11)],
2076                vec![],
2077            ),
2078        ];
2079
2080        for (id, a, b, expected, expected_sym) in cases {
2081            test_binary_op(
2082                format!("test #{} of difference", id),
2083                a.clone(),
2084                b.clone(),
2085                |x, y| x.difference(y),
2086                expected,
2087            );
2088            test_binary_op(
2089                format!("test #{} of difference", id),
2090                b,
2091                a,
2092                |x, y| x.difference(y),
2093                expected_sym,
2094            );
2095        }
2096    }
2097
2098    #[test]
2099    fn test_symmetric_difference() {
2100        // Note: the first number is the test id, so it should be easy to identify which test has failed.
2101        // The two first vectors are the operands and the expected result is last.
2102        let sym_cases = vec![
2103            // identity tests
2104            (1, vec![], vec![], vec![]),
2105            (2, vec![], vec![(1, 2)], vec![(1, 2)]),
2106            (3, vec![], vec![(1, 2), (7, 9)], vec![(1, 2), (7, 9)]),
2107            (4, vec![(1, 2), (7, 9)], vec![(1, 2)], vec![(7, 9)]),
2108            (5, vec![(1, 2), (7, 9)], vec![(1, 2), (7, 9)], vec![]),
2109            // front tests
2110            (
2111                6,
2112                vec![(-3, -1)],
2113                vec![(1, 2), (7, 9)],
2114                vec![(-3, -1), (1, 2), (7, 9)],
2115            ),
2116            (
2117                7,
2118                vec![(-3, 0)],
2119                vec![(1, 2), (7, 9)],
2120                vec![(-3, 2), (7, 9)],
2121            ),
2122            (
2123                8,
2124                vec![(-3, 1)],
2125                vec![(1, 2), (7, 9)],
2126                vec![(-3, 0), (2, 2), (7, 9)],
2127            ),
2128            // middle tests
2129            (
2130                9,
2131                vec![(2, 7)],
2132                vec![(1, 2), (7, 9)],
2133                vec![(1, 1), (3, 6), (8, 9)],
2134            ),
2135            (10, vec![(3, 7)], vec![(1, 2), (7, 9)], vec![(1, 6), (8, 9)]),
2136            (
2137                11,
2138                vec![(4, 5)],
2139                vec![(1, 2), (7, 9)],
2140                vec![(1, 2), (4, 5), (7, 9)],
2141            ),
2142            (
2143                12,
2144                vec![(2, 8)],
2145                vec![(1, 2), (7, 9)],
2146                vec![(1, 1), (3, 6), (9, 9)],
2147            ),
2148            (13, vec![(2, 6)], vec![(1, 2), (7, 9)], vec![(1, 1), (3, 9)]),
2149            (14, vec![(3, 6)], vec![(1, 2), (7, 9)], vec![(1, 9)]),
2150            // back tests
2151            (15, vec![(8, 9)], vec![(1, 2), (7, 9)], vec![(1, 2), (7, 7)]),
2152            (
2153                16,
2154                vec![(8, 10)],
2155                vec![(1, 2), (7, 9)],
2156                vec![(1, 2), (7, 7), (10, 10)],
2157            ),
2158            (
2159                17,
2160                vec![(9, 10)],
2161                vec![(1, 2), (7, 9)],
2162                vec![(1, 2), (7, 8), (10, 10)],
2163            ),
2164            (
2165                18,
2166                vec![(6, 10)],
2167                vec![(1, 2), (7, 9)],
2168                vec![(1, 2), (6, 6), (10, 10)],
2169            ),
2170            (
2171                19,
2172                vec![(10, 11)],
2173                vec![(1, 2), (7, 9)],
2174                vec![(1, 2), (7, 11)],
2175            ),
2176            (
2177                20,
2178                vec![(11, 12)],
2179                vec![(1, 2), (7, 9)],
2180                vec![(1, 2), (7, 9), (11, 12)],
2181            ),
2182            // mixed tests
2183            (
2184                21,
2185                vec![(-3, -1), (4, 5), (11, 12)],
2186                vec![(1, 2), (7, 9)],
2187                vec![(-3, -1), (1, 2), (4, 5), (7, 9), (11, 12)],
2188            ),
2189            (
2190                22,
2191                vec![(-3, 0), (3, 6), (10, 11)],
2192                vec![(1, 2), (7, 9)],
2193                vec![(-3, 11)],
2194            ),
2195            (
2196                23,
2197                vec![(-3, 1), (3, 7), (9, 11)],
2198                vec![(1, 2), (7, 9)],
2199                vec![(-3, 0), (2, 6), (8, 8), (10, 11)],
2200            ),
2201            (
2202                24,
2203                vec![(-3, 5), (7, 11)],
2204                vec![(1, 2), (7, 9)],
2205                vec![(-3, 0), (3, 5), (10, 11)],
2206            ),
2207            (
2208                25,
2209                vec![(-3, 5), (7, 8), (12, 12)],
2210                vec![(1, 2), (7, 9)],
2211                vec![(-3, 0), (3, 5), (9, 9), (12, 12)],
2212            ),
2213            // englobing tests
2214            (
2215                26,
2216                vec![(-1, 11)],
2217                vec![(1, 2), (7, 9)],
2218                vec![(-1, 0), (3, 6), (10, 11)],
2219            ),
2220        ];
2221
2222        for (id, a, b, expected) in sym_cases {
2223            test_binary_op_sym(
2224                format!("test #{} of symmetric difference", id),
2225                a,
2226                b,
2227                |x, y| x.symmetric_difference(y),
2228                expected,
2229            );
2230        }
2231    }
2232
2233    #[test]
2234    fn test_overlap_and_is_disjoint() {
2235        // Note: the first number is the test id, so it should be easy to identify which test has failed.
2236        // The two first vectors are the operands and the expected result is last.
2237        let sym_cases = vec![
2238            // identity tests
2239            (1, vec![], vec![], false),
2240            (2, vec![], vec![(1, 2)], false),
2241            (3, vec![], vec![(1, 2), (7, 9)], false),
2242            (4, vec![(1, 2), (7, 9)], vec![(1, 2)], true),
2243            (5, vec![(1, 2), (7, 9)], vec![(1, 2), (7, 9)], true),
2244            // front tests
2245            (6, vec![(-3, -1)], vec![(1, 2), (7, 9)], false),
2246            (7, vec![(-3, 0)], vec![(1, 2), (7, 9)], false),
2247            (8, vec![(-3, 1)], vec![(1, 2), (7, 9)], true),
2248            // middle tests
2249            (9, vec![(2, 7)], vec![(1, 2), (7, 9)], true),
2250            (10, vec![(3, 7)], vec![(1, 2), (7, 9)], true),
2251            (11, vec![(4, 5)], vec![(1, 2), (7, 9)], false),
2252            (12, vec![(2, 8)], vec![(1, 2), (7, 9)], true),
2253            (13, vec![(2, 6)], vec![(1, 2), (7, 9)], true),
2254            (14, vec![(3, 6)], vec![(1, 2), (7, 9)], false),
2255            // back tests
2256            (15, vec![(8, 9)], vec![(1, 2), (7, 9)], true),
2257            (16, vec![(8, 10)], vec![(1, 2), (7, 9)], true),
2258            (17, vec![(9, 10)], vec![(1, 2), (7, 9)], true),
2259            (18, vec![(6, 10)], vec![(1, 2), (7, 9)], true),
2260            (19, vec![(10, 11)], vec![(1, 2), (7, 9)], false),
2261            (20, vec![(11, 12)], vec![(1, 2), (7, 9)], false),
2262            // mixed tests
2263            (
2264                21,
2265                vec![(-3, -1), (4, 5), (11, 12)],
2266                vec![(1, 2), (7, 9)],
2267                false,
2268            ),
2269            (
2270                22,
2271                vec![(-3, 0), (3, 6), (10, 11)],
2272                vec![(1, 2), (7, 9)],
2273                false,
2274            ),
2275            (
2276                23,
2277                vec![(-3, 1), (3, 7), (9, 11)],
2278                vec![(1, 2), (7, 9)],
2279                true,
2280            ),
2281            (24, vec![(-3, 5), (7, 11)], vec![(1, 2), (7, 9)], true),
2282            (
2283                25,
2284                vec![(-3, 5), (7, 8), (12, 12)],
2285                vec![(1, 2), (7, 9)],
2286                true,
2287            ),
2288            // englobing tests
2289            (26, vec![(-1, 11)], vec![(1, 2), (7, 9)], true),
2290        ];
2291
2292        for (id, a, b, expected) in sym_cases {
2293            test_binary_bool_op_sym(
2294                format!("test #{} of overlap", id),
2295                a.clone(),
2296                b.clone(),
2297                |x, y| x.overlap(y),
2298                expected,
2299            );
2300            test_binary_bool_op_sym(
2301                format!("test #{} of is_disjoint", id),
2302                a,
2303                b,
2304                |x, y| x.is_disjoint(y),
2305                !expected,
2306            );
2307        }
2308    }
2309
2310    fn overlap_cases() -> Vec<(u32, Vec<(i32, i32)>, i32, bool)> {
2311        vec![
2312            (1, vec![], 0, false),
2313            (2, vec![(1, 2)], 0, false),
2314            (3, vec![(1, 2)], 1, true),
2315            (4, vec![(1, 2)], 2, true),
2316            (5, vec![(1, 2)], 3, false),
2317            (6, vec![(1, 3), (5, 7)], 2, true),
2318            (7, vec![(1, 3), (5, 7)], 6, true),
2319            (8, vec![(1, 3), (5, 7)], 4, false),
2320            (9, vec![(1, 3), (5, 7)], 0, false),
2321            (10, vec![(1, 3), (5, 7)], 8, false),
2322        ]
2323    }
2324
2325    #[test]
2326    fn test_overlap_bound() {
2327        let cases = overlap_cases();
2328
2329        for (id, a, b, expected) in cases {
2330            test_binary_value_bool_op(
2331                format!("test #{} of overlap_bound", id),
2332                a.clone(),
2333                b,
2334                |x, y| x.overlap(y),
2335                expected,
2336            );
2337            test_binary_value_bool_op(
2338                format!("test #{} of overlap_bound", id),
2339                a,
2340                b,
2341                |x, y| y.overlap(x),
2342                expected,
2343            );
2344        }
2345    }
2346
2347    #[test]
2348    fn test_overlap_option() {
2349        let mut cases: Vec<(u32, Vec<(i32, i32)>, Optional<i32>, bool)> = overlap_cases()
2350            .into_iter()
2351            .map(|(id, a, b, e)| (id, a, Optional::singleton(b), e))
2352            .collect();
2353        cases.extend(
2354            vec![
2355                (11, vec![], Optional::empty(), false),
2356                (12, vec![(1, 2)], Optional::empty(), false),
2357                (13, vec![(1, 3), (5, 7)], Optional::empty(), false),
2358            ]
2359            .into_iter(),
2360        );
2361
2362        for (id, a, b, expected) in cases {
2363            test_binary_value_bool_op(
2364                format!("test #{} of overlap_option", id),
2365                a.clone(),
2366                b,
2367                |x, y| x.overlap(y),
2368                expected,
2369            );
2370        }
2371    }
2372
2373    #[test]
2374    fn test_shrink() {
2375        let min = <i32 as Width>::min_value();
2376        let max = <i32 as Width>::max_value();
2377
2378        // Second and third args are the test value.
2379        // The fourth is the result of a shrink_left and the fifth of a shrink_right.
2380        let cases = vec![
2381            (1, vec![], 0, vec![], vec![]),
2382            (2, vec![(min, max)], 0, vec![(0, max)], vec![(min, 0)]),
2383            (3, vec![(0, 0)], 0, vec![(0, 0)], vec![(0, 0)]),
2384            (4, vec![(0, 0)], -1, vec![(0, 0)], vec![]),
2385            (5, vec![(0, 0)], 1, vec![], vec![(0, 0)]),
2386            (6, vec![(-5, 5)], 0, vec![(0, 5)], vec![(-5, 0)]),
2387            (7, vec![(-5, 5)], -5, vec![(-5, 5)], vec![(-5, -5)]),
2388            (8, vec![(-5, 5)], 5, vec![(5, 5)], vec![(-5, 5)]),
2389            (9, vec![(-5, -1), (1, 5)], 0, vec![(1, 5)], vec![(-5, -1)]),
2390            (
2391                10,
2392                vec![(-5, -1), (1, 5)],
2393                1,
2394                vec![(1, 5)],
2395                vec![(-5, -1), (1, 1)],
2396            ),
2397            (
2398                11,
2399                vec![(-5, -1), (1, 5)],
2400                -1,
2401                vec![(-1, -1), (1, 5)],
2402                vec![(-5, -1)],
2403            ),
2404            (
2405                12,
2406                vec![(min, -1), (1, 5)],
2407                min,
2408                vec![(min, -1), (1, 5)],
2409                vec![(min, min)],
2410            ),
2411            (
2412                13,
2413                vec![(min, -1), (1, 5)],
2414                max,
2415                vec![],
2416                vec![(min, -1), (1, 5)],
2417            ),
2418            (
2419                14,
2420                vec![(-5, -1), (1, max)],
2421                max,
2422                vec![(max, max)],
2423                vec![(-5, -1), (1, max)],
2424            ),
2425            (
2426                15,
2427                vec![(min, -1), (1, max)],
2428                0,
2429                vec![(1, max)],
2430                vec![(min, -1)],
2431            ),
2432            (
2433                16,
2434                vec![(-5, -3), (0, 1), (3, 5)],
2435                1,
2436                vec![(1, 1), (3, 5)],
2437                vec![(-5, -3), (0, 1)],
2438            ),
2439        ];
2440
2441        for (id, a, v, expected_left, expected_right) in cases {
2442            test_binary_value_op(
2443                format!("test #{} of shrink_left", id),
2444                a.clone(),
2445                v,
2446                |x, v| x.shrink_left(v),
2447                expected_left,
2448            );
2449            test_binary_value_op(
2450                format!("test #{} of shrink_right", id),
2451                a,
2452                v,
2453                |x, v| x.shrink_right(v),
2454                expected_right,
2455            );
2456        }
2457    }
2458
2459    #[test]
2460    fn test_subset() {
2461        // Note: the first number is the test id, so it should be easy to identify which test has failed.
2462        // The two first vectors are the operands and the four last are expected results (resp.
2463        // `a.is_subset(b)`, `b.is_subset(a)`, `a.is_proper_subset(b)` and `b.is_proper_subset(a)`.
2464        let cases = vec![
2465            // identity tests
2466            (1, vec![], vec![], true, true, false, false),
2467            (2, vec![], vec![(1, 2)], true, false, true, false),
2468            (3, vec![], vec![(1, 2), (7, 9)], true, false, true, false),
2469            (
2470                4,
2471                vec![(1, 2), (7, 9)],
2472                vec![(1, 2)],
2473                false,
2474                true,
2475                false,
2476                true,
2477            ),
2478            (
2479                5,
2480                vec![(1, 2), (7, 9)],
2481                vec![(1, 2), (7, 9)],
2482                true,
2483                true,
2484                false,
2485                false,
2486            ),
2487            // middle tests
2488            (
2489                6,
2490                vec![(2, 7)],
2491                vec![(1, 2), (7, 9)],
2492                false,
2493                false,
2494                false,
2495                false,
2496            ),
2497            (
2498                7,
2499                vec![(3, 7)],
2500                vec![(1, 2), (7, 9)],
2501                false,
2502                false,
2503                false,
2504                false,
2505            ),
2506            (
2507                8,
2508                vec![(4, 5)],
2509                vec![(1, 2), (7, 9)],
2510                false,
2511                false,
2512                false,
2513                false,
2514            ),
2515            (
2516                9,
2517                vec![(2, 8)],
2518                vec![(1, 2), (7, 9)],
2519                false,
2520                false,
2521                false,
2522                false,
2523            ),
2524            // mixed tests
2525            (
2526                10,
2527                vec![(-3, -1), (4, 5), (11, 12)],
2528                vec![(-2, -1), (7, 9)],
2529                false,
2530                false,
2531                false,
2532                false,
2533            ),
2534            (
2535                11,
2536                vec![(-3, 0), (3, 6), (10, 11)],
2537                vec![(-2, -1), (4, 4), (10, 10)],
2538                false,
2539                true,
2540                false,
2541                true,
2542            ),
2543            (
2544                12,
2545                vec![(-3, 0), (3, 6), (10, 11)],
2546                vec![(-3, 0), (3, 6), (10, 11)],
2547                true,
2548                true,
2549                false,
2550                false,
2551            ),
2552            // englobing tests
2553            (
2554                13,
2555                vec![(-1, 11)],
2556                vec![(1, 2), (7, 9)],
2557                false,
2558                true,
2559                false,
2560                true,
2561            ),
2562        ];
2563
2564        for (id, a, b, expected, expected_sym, expected_proper, expected_proper_sym) in cases {
2565            test_binary_bool_op(
2566                format!("test #{} of subset", id),
2567                a.clone(),
2568                b.clone(),
2569                |x, y| x.is_subset(y),
2570                expected,
2571            );
2572            test_binary_bool_op(
2573                format!("test #{} of subset", id),
2574                b.clone(),
2575                a.clone(),
2576                |x, y| x.is_subset(y),
2577                expected_sym,
2578            );
2579            test_binary_bool_op(
2580                format!("test #{} of proper subset", id),
2581                a.clone(),
2582                b.clone(),
2583                |x, y| x.is_proper_subset(y),
2584                expected_proper,
2585            );
2586            test_binary_bool_op(
2587                format!("test #{} of proper subset", id),
2588                b.clone(),
2589                a.clone(),
2590                |x, y| x.is_proper_subset(y),
2591                expected_proper_sym,
2592            );
2593        }
2594    }
2595
2596    #[test]
2597    fn test_arithmetics() {
2598        // Second and third args are the test values.
2599        // 4, 5, 6 and 7 are the results of `a + b`, `a - b`, `b - a` and `a * b`
2600        let cases = vec![
2601            (1, vec![], vec![], vec![], vec![], vec![], vec![]),
2602            (
2603                2,
2604                vec![],
2605                vec![(1, 1), (3, 5)],
2606                vec![],
2607                vec![],
2608                vec![],
2609                vec![],
2610            ),
2611            (
2612                3,
2613                vec![(1, 1), (3, 5)],
2614                vec![(0, 0)],
2615                vec![(1, 1), (3, 5)],
2616                vec![(1, 1), (3, 5)],
2617                vec![(-5, -3), (-1, -1)],
2618                vec![(0, 0)],
2619            ),
2620            (
2621                4,
2622                vec![(1, 1), (3, 5)],
2623                vec![(1, 1)],
2624                vec![(2, 2), (4, 6)],
2625                vec![(0, 0), (2, 4)],
2626                vec![(-4, -2), (0, 0)],
2627                vec![(1, 1), (3, 5)],
2628            ),
2629            (
2630                5,
2631                vec![(1, 1), (3, 5)],
2632                vec![(0, 1), (4, 5)],
2633                vec![(1, 10)],
2634                vec![(-4, 5)],
2635                vec![(-5, 4)],
2636                vec![(0, 5), (12, 25)],
2637            ),
2638        ];
2639
2640        for (id, a, b, e_add, e_sub, e_sub_sym, e_mul) in cases {
2641            test_binary_op_sym(
2642                format!("test #{} of `a+b`", id),
2643                a.clone(),
2644                b.clone(),
2645                |x, y| x + y,
2646                e_add,
2647            );
2648            test_binary_op(
2649                format!("test #{} of `a-b`", id),
2650                a.clone(),
2651                b.clone(),
2652                |x, y| x - y,
2653                e_sub,
2654            );
2655            test_binary_op(
2656                format!("test #{} of `b-a`", id),
2657                b.clone(),
2658                a.clone(),
2659                |x, y| x - y,
2660                e_sub_sym,
2661            );
2662            test_binary_op_sym(
2663                format!("test #{} of `a*b`", id),
2664                a.clone(),
2665                b.clone(),
2666                |x, y| x * y,
2667                e_mul,
2668            );
2669        }
2670    }
2671
2672    #[test]
2673    fn test_arithmetics_bound() {
2674        let i1_35 = vec![(1, 1), (3, 5)];
2675        // Second and third args are the test value.
2676        // 4, 5 and 6 are the results of `a + b`, `a - b` and `a * b`
2677        let cases = vec![
2678            (1, vec![], 0, vec![], vec![], vec![]),
2679            (2, vec![(0, 0)], 0, vec![(0, 0)], vec![(0, 0)], vec![(0, 0)]),
2680            (
2681                3,
2682                i1_35.clone(),
2683                0,
2684                i1_35.clone(),
2685                i1_35.clone(),
2686                vec![(0, 0)],
2687            ),
2688            (4, vec![], 1, vec![], vec![], vec![]),
2689            (
2690                5,
2691                vec![(0, 0)],
2692                1,
2693                vec![(1, 1)],
2694                vec![(-1, -1)],
2695                vec![(0, 0)],
2696            ),
2697            (
2698                6,
2699                i1_35.clone(),
2700                1,
2701                vec![(2, 2), (4, 6)],
2702                vec![(0, 0), (2, 4)],
2703                i1_35.clone(),
2704            ),
2705            (7, vec![], 3, vec![], vec![], vec![]),
2706            (
2707                8,
2708                vec![(0, 0)],
2709                3,
2710                vec![(3, 3)],
2711                vec![(-3, -3)],
2712                vec![(0, 0)],
2713            ),
2714            (
2715                9,
2716                i1_35.clone(),
2717                3,
2718                vec![(4, 4), (6, 8)],
2719                vec![(-2, -2), (0, 2)],
2720                vec![(3, 3), (9, 15)],
2721            ),
2722        ];
2723
2724        for (id, a, b, e_add, e_sub, e_mul) in cases {
2725            test_binary_value_op(
2726                format!("test #{} of `a+b`", id),
2727                a.clone(),
2728                b.clone(),
2729                |x, y| x + y,
2730                e_add,
2731            );
2732            test_binary_value_op(
2733                format!("test #{} of `a-b`", id),
2734                a.clone(),
2735                b.clone(),
2736                |x, y| x - y,
2737                e_sub,
2738            );
2739            test_binary_value_op(
2740                format!("test #{} of `a*b`", id),
2741                a.clone(),
2742                b.clone(),
2743                |x, y| x * y,
2744                e_mul,
2745            );
2746        }
2747    }
2748
2749    #[test]
2750    fn test_lattice() {
2751        use gcollections::ops::lattice::test::*;
2752        use trilean::SKleene::*;
2753        let whole = IntervalSet::<i32>::whole();
2754        let empty = IntervalSet::<i32>::empty();
2755        let a = vec![(0, 5), (10, 15)].to_interval_set();
2756        let b = vec![(5, 10)].to_interval_set();
2757        let c = vec![(6, 9)].to_interval_set();
2758        let d = vec![(4, 6), (8, 10)].to_interval_set();
2759        let e = vec![(5, 5), (10, 10)].to_interval_set();
2760        let f = vec![(6, 6), (8, 9)].to_interval_set();
2761        let g = vec![(0, 15)].to_interval_set();
2762        let h = vec![(4, 10)].to_interval_set();
2763        let tester = LatticeTester::new(
2764            0,
2765            /* data_a */
2766            vec![
2767                empty.clone(),
2768                empty.clone(),
2769                whole.clone(),
2770                a.clone(),
2771                b.clone(),
2772                c.clone(),
2773            ],
2774            /* data_b */
2775            vec![
2776                whole.clone(),
2777                a.clone(),
2778                a.clone(),
2779                b.clone(),
2780                c.clone(),
2781                d.clone(),
2782            ],
2783            /* a |= b*/ vec![True, True, False, Unknown, False, Unknown],
2784            /* a |_| b */
2785            vec![
2786                empty.clone(),
2787                empty.clone(),
2788                a.clone(),
2789                e.clone(),
2790                c.clone(),
2791                f.clone(),
2792            ],
2793            /* a |-| b */
2794            vec![
2795                whole.clone(),
2796                a.clone(),
2797                whole.clone(),
2798                g.clone(),
2799                b.clone(),
2800                h.clone(),
2801            ],
2802        );
2803        tester.test_all();
2804    }
2805
2806    #[test]
2807    fn test_iterator() {
2808        let empty = IntervalSet::<i32>::empty();
2809        let mut a = [(0, 5), (10, 15)].to_interval_set();
2810        let mut iter = a.clone().into_iter();
2811        assert_eq!(
2812            iter.next(),
2813            Some(Interval::new(0, 5)),
2814            "test 1 of test_iterator"
2815        );
2816        assert_eq!(
2817            iter.next(),
2818            Some(Interval::new(10, 15)),
2819            "test 2 of test_iterator"
2820        );
2821        assert_eq!(iter.next(), None, "test 3 of test_iterator");
2822        for _x in a.clone() {}
2823        for _x in &a {}
2824        for _x in &mut a {}
2825        for _x in empty {
2826            assert!(
2827                false,
2828                "test 4 of test_iterator: empty interval must not yield an element."
2829            );
2830        }
2831    }
2832
2833    #[test]
2834    fn test_ser_de_single_interval_set() {
2835        assert_tokens(
2836            &IntervalSet::from_interval(Interval::new(8, 12)),
2837            &[
2838                Token::Seq { len: Some(1) },
2839                Token::Tuple { len: 2 },
2840                Token::I32(8),
2841                Token::I32(12),
2842                Token::TupleEnd,
2843                Token::SeqEnd,
2844            ],
2845        );
2846    }
2847
2848    #[test]
2849    fn test_ser_de_multiple_interval_set() {
2850        assert_tokens(
2851            &[(20, 21), (3, 5), (-10, -5)].to_interval_set(),
2852            &[
2853                Token::Seq { len: Some(3) },
2854                Token::Tuple { len: 2 },
2855                Token::I32(-10),
2856                Token::I32(-5),
2857                Token::TupleEnd,
2858                Token::Tuple { len: 2 },
2859                Token::I32(3),
2860                Token::I32(5),
2861                Token::TupleEnd,
2862                Token::Tuple { len: 2 },
2863                Token::I32(20),
2864                Token::I32(21),
2865                Token::TupleEnd,
2866                Token::SeqEnd,
2867            ],
2868        );
2869    }
2870
2871    #[test]
2872    fn test_ser_de_empty_interval_set() {
2873        assert_tokens(&IntervalSet::<i32>::empty(), &[Token::None]);
2874    }
2875}