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 = vec![(1,2), (6,10)].to_interval_set();
19//! let b = vec![(3,5), (7,7)].to_interval_set();
20//! let a_union_b = vec![(1,5), (6,10)].to_interval_set();
21//! let a_intersect_b = vec![(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 trilean::SKleene;
35use gcollections::*;
36use gcollections::ops::*;
37use std::iter::{Peekable, IntoIterator};
38use std::fmt::{Formatter, Display, Error};
39use std::ops::{Add, Sub, Mul};
40
41use num_traits::{Zero, Num};
42
43#[derive(Debug, Clone)]
44pub struct IntervalSet<Bound: Width> {
45  intervals: Vec<Interval<Bound>>,
46  size: Bound::Output
47}
48
49impl<Bound: Width> IntervalKind for IntervalSet<Bound> {}
50
51impl<Bound: Width> Collection for IntervalSet<Bound>
52{
53  type Item = Bound;
54}
55
56impl<Bound: Width> IntoIterator for IntervalSet<Bound>
57{
58  type Item = Interval<Bound>;
59  type IntoIter = ::std::vec::IntoIter<Self::Item>;
60
61  fn into_iter(self) -> Self::IntoIter {
62    self.intervals.into_iter()
63  }
64}
65
66impl<'a, Bound: Width> IntoIterator for &'a IntervalSet<Bound>
67{
68  type Item = &'a Interval<Bound>;
69  type IntoIter = ::std::slice::Iter<'a, Interval<Bound>>;
70
71  fn into_iter(self) -> Self::IntoIter {
72    self.iter()
73  }
74}
75
76impl<'a, Bound: Width> IntoIterator for &'a mut IntervalSet<Bound>
77{
78  type Item = &'a mut Interval<Bound>;
79  type IntoIter = ::std::slice::IterMut<'a, Interval<Bound>>;
80
81  fn into_iter(self) -> Self::IntoIter {
82    self.iter_mut()
83  }
84}
85
86impl<Bound: Width> IntervalSet<Bound>
87{
88  pub fn iter(&self) -> ::std::slice::Iter<Interval<Bound>> {
89    self.intervals.iter()
90  }
91
92  pub fn iter_mut(&mut self) -> ::std::slice::IterMut<Interval<Bound>> {
93    self.intervals.iter_mut()
94  }
95}
96
97impl<Bound> IntervalSet<Bound> where
98 Bound: Width + Num
99{
100  pub fn interval_count(&self) -> usize {
101    self.intervals.len()
102  }
103
104  fn from_interval(i: Interval<Bound>) -> IntervalSet<Bound> {
105    let size = i.size().clone();
106    IntervalSet {
107      intervals: vec![i],
108      size
109    }
110  }
111
112  fn front(&self) -> &Interval<Bound> {
113    debug_assert!(!self.is_empty(), "Cannot access the first interval of an empty set.");
114    &self.intervals[0]
115  }
116
117  fn back_idx(&self) -> usize {
118    self.intervals.len() - 1
119  }
120
121  fn back(&self) -> &Interval<Bound> {
122    debug_assert!(!self.is_empty(), "Cannot access the last interval of an empty set.");
123    &self.intervals[self.back_idx()]
124  }
125
126  fn span(&self) -> Interval<Bound> {
127    if self.is_empty() {
128      Interval::empty()
129    }
130    else {
131      self.span_slice(0, self.back_idx())
132    }
133  }
134
135  fn span_slice(&self, left: usize, right: usize) -> Interval<Bound> {
136    Interval::new(
137      self.intervals[left].lower(),
138      self.intervals[right].upper()
139    )
140  }
141
142  fn push(&mut self, x: Interval<Bound>) {
143    debug_assert!(!x.is_empty(), "Cannot push empty interval.");
144    debug_assert!(self.is_empty() || !joinable(self.back(), &x),
145      "The intervals array must be ordered and intervals must not be joinable. For a safe push, use the union operation.");
146
147    self.size = self.size.clone() + x.size();
148    self.intervals.push(x);
149  }
150
151  fn pop(&mut self) -> Option<Interval<Bound>> {
152    if let Some(x) = self.intervals.pop() {
153      self.size = self.size.clone() - x.size();
154      Some(x)
155    } else {
156      None
157    }
158  }
159
160  fn join_or_push(&mut self, x: Interval<Bound>) {
161    if self.is_empty() {
162      self.push(x);
163    }
164    else {
165      debug_assert!(!x.is_empty(), "Cannot push empty interval.");
166      debug_assert!(self.back().lower() <= x.lower(),
167        "This operation is only for pushing interval to the back of the array, possibly overlapping with the last element.");
168
169      let joint =
170        if joinable(self.back(), &x) {
171          self.pop().unwrap().hull(&x)
172        }
173        else {
174          x
175        };
176      self.push(joint);
177    }
178  }
179
180  /// Expects the given iterable to be in-order - as we are iterating through
181  /// it, each [`Interval<Bound>`] should belong on the upper end of the
182  /// [`IntervalSet`]. Otherwise this method will panic.
183  fn extend_at_back<I>(&mut self, iterable: I) where
184   I: IntoIterator<Item=Interval<Bound>>,
185   Bound: PartialOrd
186  {
187    for interval in iterable {
188      self.join_or_push(interval);
189    }
190  }
191
192  fn find_interval_between(&self, value: &Bound,
193    mut left: usize, mut right: usize) -> (usize, usize)
194  {
195    debug_assert!(left <= right);
196    debug_assert!(right < self.intervals.len());
197    debug_assert!(self.span_slice(left, right).contains(value));
198
199    while left <= right {
200      let mid_idx = left + (right - left) / 2;
201      let mid = &self.intervals[mid_idx];
202      if &mid.lower() > value {
203        right = mid_idx - 1;
204      }
205      else if &mid.upper() < value {
206        left = mid_idx + 1;
207      }
208      else {
209        return (mid_idx, mid_idx)
210      }
211    }
212    (right, left)
213  }
214
215  // Returns the indexes of the left and right interval of `value`.
216  // If the value is outside `self`, returns None.
217  // If the value is inside one of the interval, the indexes will be equal.
218  fn find_interval(&self, value: &Bound) -> Option<(usize, usize)> {
219    if !self.span().contains(value) {
220      None
221    }
222    else {
223      Some(self.find_interval_between(value, 0, self.back_idx()))
224    }
225  }
226
227  fn for_all_pairs<F>(&self, other: &IntervalSet<Bound>, f: F) -> IntervalSet<Bound> where
228   F: Fn(&Interval<Bound>, &Interval<Bound>) -> Interval<Bound>
229  {
230    let mut res = IntervalSet::empty();
231    for i in &self.intervals {
232      for j in &other.intervals {
233        res = res.union(&IntervalSet::from_interval(f(i,j)));
234      }
235    }
236    res
237  }
238
239  // Precondition: `f` must not change the size of the interval.
240  fn stable_map<F>(&self, f: F) -> IntervalSet<Bound> where
241   F: Fn(&Interval<Bound>) -> Interval<Bound>
242  {
243    IntervalSet {
244      intervals: self.intervals.iter().map(f).collect(),
245      size: self.size.clone()
246    }
247  }
248
249  fn map<F>(&self, f: F) -> IntervalSet<Bound> where
250   F: Fn(&Interval<Bound>) -> Interval<Bound>
251  {
252    self.intervals.iter().fold(IntervalSet::empty(),
253      |mut r, i| { r.push(f(i)); r })
254  }
255}
256
257fn joinable<Bound>(first: &Interval<Bound>, second: &Interval<Bound>) -> bool where
258 Bound: Width + Num
259{
260  if first.upper() == Bound::max_value() { true }
261  else { first.upper() + Bound::one() >= second.lower() }
262}
263
264impl<Bound> Extend<Interval<Bound>> for IntervalSet<Bound> where
265 Bound: Width + Num
266{
267  fn extend<I>(&mut self, iterable: I) where
268   I: IntoIterator<Item=Interval<Bound>>
269  {
270    let mut intervals: Vec<_> = iterable.into_iter().map(|i| i.to_interval()).collect();
271    intervals.sort_unstable_by_key(|i| i.lower());
272    let mut set = IntervalSet::empty();
273    set.extend_at_back(intervals);
274    *self = self.union(&set);
275  }
276}
277
278impl<Bound: Width + Num> Eq for IntervalSet<Bound> {}
279
280impl<Bound> PartialEq<IntervalSet<Bound>> for IntervalSet<Bound> where
281 Bound: Width + Num
282{
283  fn eq(&self, other: &IntervalSet<Bound>) -> bool {
284    if self.size() != other.size() { false }
285    else {
286      self.intervals == other.intervals
287    }
288  }
289}
290
291impl<Bound> Range for IntervalSet<Bound> where
292 Bound: Width + Num
293{
294  fn new(lb: Bound, ub: Bound) -> IntervalSet<Bound> {
295    debug_assert!(lb <= ub, "Cannot build empty interval set with an invalid range. use crate::intervalSet::empty().");
296    let i = Interval::new(lb, ub);
297    IntervalSet::from_interval(i)
298  }
299}
300
301impl<Bound> Whole for IntervalSet<Bound> where
302 Bound: Width + Num
303{
304  fn whole() -> IntervalSet<Bound> {
305    let mut res = IntervalSet::empty();
306    res.push(Interval::whole());
307    res
308  }
309}
310
311impl<Bound> Bounded for IntervalSet<Bound> where
312 Bound: Width + Num + PartialOrd
313{
314  fn lower(&self) -> Bound {
315    debug_assert!(!self.is_empty(), "Cannot access lower bound on empty interval.");
316    self.front().lower()
317  }
318
319  fn upper(&self) -> Bound {
320    debug_assert!(!self.is_empty(), "Cannot access upper bound on empty interval.");
321    self.back().upper()
322  }
323}
324
325impl <Bound: Width+Num> Singleton for IntervalSet<Bound>
326{
327  fn singleton(x: Bound) -> IntervalSet<Bound> {
328    IntervalSet::new(x.clone(), x)
329  }
330}
331
332impl<Bound: Width+Num> Empty for IntervalSet<Bound>
333{
334  fn empty() -> IntervalSet<Bound> {
335    IntervalSet {
336      intervals: vec![],
337      size: <<Bound as Width>::Output>::zero()
338    }
339  }
340}
341
342/// `IsSingleton` and `IsEmpty` are defined automatically in `gcollections`.
343impl<Bound: Width+Num> Cardinality for IntervalSet<Bound>
344{
345  type Size = <Bound as Width>::Output;
346
347  fn size(&self) -> <Bound as Width>::Output {
348    self.size.clone()
349  }
350}
351
352impl<Bound: Width+Num> Contains for IntervalSet<Bound>
353{
354  fn contains(&self, value: &Bound) -> bool {
355    if let Some((left, right)) = self.find_interval(value) {
356      left == right
357    } else {
358      false
359    }
360  }
361}
362
363fn advance_one<I, F, Item>(a : &mut Peekable<I>, b: &mut Peekable<I>, choose: F) -> Item where
364 I: Iterator<Item=Item>,
365 F: Fn(&Item, &Item) -> bool,
366 Item: Bounded
367{
368  static NON_EMPTY_PRECONDITION: &str =
369    "`advance_one` expects both interval iterators to be non_empty.";
370  let who_advance = {
371    let i = a.peek().expect(NON_EMPTY_PRECONDITION);
372    let j = b.peek().expect(NON_EMPTY_PRECONDITION);
373    choose(i, j)
374  };
375  let to_advance = if who_advance { a } else { b };
376  to_advance.next().unwrap()
377}
378
379fn advance_lower<I, Item, B>(a : &mut Peekable<I>, b: &mut Peekable<I>) -> Item where
380 I: Iterator<Item=Item>,
381 Item: Bounded + Collection<Item=B>,
382 B: Ord
383{
384  advance_one(a, b, |i,j| i.lower() < j.lower())
385}
386
387// Advance the one with the lower upper bound.
388fn advance_lub<I, Item, B>(a : &mut Peekable<I>, b: &mut Peekable<I>) -> Item where
389 I: Iterator<Item=Item>,
390 Item: Bounded + Collection<Item=B>,
391 B: Ord
392{
393  advance_one(a, b, |i, j| i.upper() < j.upper())
394}
395
396fn from_lower_iterator<I, Bound>(a : &mut Peekable<I>, b: &mut Peekable<I>) -> IntervalSet<Bound> where
397 I: Iterator<Item=Interval<Bound>>,
398 Bound: Width+Num
399{
400  if a.peek().is_none() || b.peek().is_none() {
401    IntervalSet::empty()
402  } else {
403    let first = advance_lower(a, b);
404    IntervalSet::from_interval(first)
405  }
406}
407
408impl<Bound> Union<Bound> for IntervalSet<Bound> where
409  Bound: Width + Num + Clone
410{
411  type Output = IntervalSet<Bound>;
412
413  fn union(&self, rhs: &Bound) -> IntervalSet<Bound> {
414    self.union(&IntervalSet::singleton(rhs.clone()))
415  }
416}
417
418impl<Bound: Width+Num> Union for IntervalSet<Bound>
419{
420  type Output = IntervalSet<Bound>;
421
422  fn union(&self, rhs: &IntervalSet<Bound>) -> IntervalSet<Bound> {
423    let a = &mut self.intervals.iter().cloned().peekable();
424    let b = &mut rhs.intervals.iter().cloned().peekable();
425    let mut res = from_lower_iterator(a, b);
426    while a.peek().is_some() && b.peek().is_some() {
427      let lower = advance_lower(a, b);
428      res.join_or_push(lower);
429    }
430    res.extend_at_back(a);
431    res.extend_at_back(b);
432    res
433  }
434}
435
436// Returns `false` when one of the iterator is consumed.
437// Iterators are not consumed if the intervals are already overlapping.
438fn advance_to_first_overlapping<I, Item, B>(a : &mut Peekable<I>, b: &mut Peekable<I>) -> bool where
439 I: Iterator<Item=Item>,
440 Item: Bounded + Overlap + Collection<Item=B>,
441 B: Ord
442{
443  while a.peek().is_some() && b.peek().is_some() {
444    let overlapping = {
445      let i = a.peek().unwrap();
446      let j = b.peek().unwrap();
447      i.overlap(j)
448    };
449    if overlapping {
450      return true
451    } else {
452      advance_lower(a, b);
453    }
454  }
455  false
456}
457
458impl<Bound> Intersection<Bound> for IntervalSet<Bound> where
459  Bound: Width + Num + Clone
460{
461  type Output = IntervalSet<Bound>;
462
463  fn intersection(&self, rhs: &Bound) -> IntervalSet<Bound> {
464    self.intersection(&IntervalSet::singleton(rhs.clone()))
465  }
466}
467
468impl<Bound: Width+Num> Intersection for IntervalSet<Bound>
469{
470  type Output = IntervalSet<Bound>;
471
472  fn intersection(&self, rhs: &IntervalSet<Bound>) -> IntervalSet<Bound> {
473    let a = &mut self.intervals.iter().cloned().peekable();
474    let b = &mut rhs.intervals.iter().cloned().peekable();
475    let mut res = IntervalSet::empty();
476    while advance_to_first_overlapping(a, b) {
477      {
478        let i = a.peek().unwrap();
479        let j = b.peek().unwrap();
480        res.push(i.intersection(j));
481      }
482      advance_lub(a, b); // advance the one with the lowest upper bound.
483    }
484    res
485  }
486}
487
488fn push_left_complement<Bound: Width+Num>(x: &Interval<Bound>, res: &mut IntervalSet<Bound>) {
489  let min = <Bound as Width>::min_value();
490  if x.lower() != min {
491    res.push(Interval::new(min, x.lower() - Bound::one()));
492  }
493}
494
495fn push_right_complement<Bound: Width+Num>(x: &Interval<Bound>, res: &mut IntervalSet<Bound>) {
496  let max = <Bound as Width>::max_value();
497  if x.upper() != max {
498    res.push(Interval::new(x.upper() + Bound::one(), max));
499  }
500}
501
502impl<Bound: Width+Num> Complement for IntervalSet<Bound>
503{
504  fn complement(&self) -> IntervalSet<Bound> {
505    let mut res = IntervalSet::empty();
506    if self.is_empty() {
507      res.push(Interval::whole());
508    }
509    else {
510      let one = Bound::one();
511      push_left_complement(self.front(), &mut res);
512      for i in 1..self.intervals.len() {
513        let current = &self.intervals[i];
514        let previous = &self.intervals[i-1];
515        res.push(Interval::new(
516          previous.upper() + one.clone(),
517          current.lower() - one.clone()));
518      }
519      push_right_complement(self.back(), &mut res);
520    }
521    res
522  }
523}
524
525impl<Bound> Difference<Bound> for IntervalSet<Bound> where
526  Bound: Width + Num + Clone
527{
528  type Output = IntervalSet<Bound>;
529
530  fn difference(&self, rhs: &Bound) -> IntervalSet<Bound> {
531    self.difference(&IntervalSet::singleton(rhs.clone()))
532  }
533}
534
535impl<Bound: Width+Num> Difference for IntervalSet<Bound> {
536  type Output = IntervalSet<Bound>;
537
538  fn difference(&self, rhs: &IntervalSet<Bound>) -> IntervalSet<Bound> {
539    self.intersection(&rhs.complement())
540  }
541}
542
543impl<Bound> SymmetricDifference<Bound> for IntervalSet<Bound> where
544  Bound: Width + Num + Clone
545{
546  type Output = IntervalSet<Bound>;
547
548  fn symmetric_difference(&self, rhs: &Bound) -> IntervalSet<Bound> {
549    self.symmetric_difference(&IntervalSet::singleton(rhs.clone()))
550  }
551}
552
553impl<Bound: Width+Num> SymmetricDifference for IntervalSet<Bound> {
554  type Output = IntervalSet<Bound>;
555
556  fn symmetric_difference(&self, rhs: &IntervalSet<Bound>) -> IntervalSet<Bound> {
557    let union = self.union(rhs);
558    let intersection = self.intersection(rhs);
559    union.difference(&intersection)
560  }
561}
562
563impl<Bound: Width+Num> Overlap for IntervalSet<Bound> {
564  fn overlap(&self, rhs: &IntervalSet<Bound>) -> bool {
565    let a = &mut self.intervals.iter().cloned().peekable();
566    let b = &mut rhs.intervals.iter().cloned().peekable();
567    advance_to_first_overlapping(a, b)
568  }
569}
570
571impl<Bound: Width+Num> Overlap<Bound> for IntervalSet<Bound> {
572  fn overlap(&self, value: &Bound) -> bool {
573    if let Some((l, u)) = self.find_interval(value) {
574      l == u
575    }
576    else {
577      false
578    }
579  }
580}
581
582impl<Bound: Width+Num> Overlap<Optional<Bound>> for IntervalSet<Bound> {
583  fn overlap(&self, value: &Optional<Bound>) -> bool {
584    value.as_ref().map_or(false, |b| self.overlap(b))
585  }
586}
587
588macro_rules! primitive_interval_set_overlap
589{
590  ( $( $source:ty ),* ) =>
591  {$(
592    impl Overlap<IntervalSet<$source>> for $source {
593      fn overlap(&self, other: &IntervalSet<$source>) -> bool {
594        other.overlap(self)
595      }
596    }
597  )*}
598}
599
600primitive_interval_set_overlap!(i8,u8,i16,u16,i32,u32,i64,u64,isize,usize);
601
602impl<Bound: Width+Num> Disjoint for IntervalSet<Bound> {
603  fn is_disjoint(&self, rhs: &IntervalSet<Bound>) -> bool {
604    !self.overlap(rhs)
605  }
606}
607
608impl<Bound: Width+Num> ShrinkLeft for IntervalSet<Bound> where
609  <Bound as Width>::Output: Clone
610{
611  fn shrink_left(&self, lb: Bound) -> IntervalSet<Bound> {
612    if let Some((left, _)) = self.find_interval(&lb) {
613      let mut res = IntervalSet::empty();
614      if self.intervals[left].upper() >= lb {
615        res.push(Interval::new(lb, self.intervals[left].upper()));
616      }
617      for i in (left+1)..self.intervals.len() {
618        res.push(self.intervals[i].clone());
619      }
620      res
621    }
622    else if self.is_empty() || lb > self.back().upper() {
623      IntervalSet::empty()
624    } else {
625      self.clone()
626    }
627  }
628}
629
630impl<Bound: Width+Num> ShrinkRight for IntervalSet<Bound> where
631  <Bound as Width>::Output: Clone
632{
633  fn shrink_right(&self, ub: Bound) -> IntervalSet<Bound> {
634    if let Some((_, right)) = self.find_interval(&ub) {
635      let mut res = IntervalSet::empty();
636      for i in 0..right {
637        res.push(self.intervals[i].clone());
638      }
639      if self.intervals[right].lower() <= ub {
640        res.push(Interval::new(self.intervals[right].lower(), ub));
641      }
642      res
643    }
644    else if self.is_empty() || ub < self.front().lower() {
645      IntervalSet::empty()
646    } else {
647      self.clone()
648    }
649  }
650}
651
652impl<Bound: Width+Num> Subset for IntervalSet<Bound>
653{
654  fn is_subset(&self, other: &IntervalSet<Bound>) -> bool {
655    if self.is_empty() { true }
656    else if self.size() > other.size() || !self.span().is_subset(&other.span()) { false }
657    else {
658      let mut left = 0;
659      let right = other.intervals.len() - 1;
660      for interval in &self.intervals {
661        let (l, r) = other.find_interval_between(&interval.lower(), left, right);
662        if l == r && interval.is_subset(&other.intervals[l]) {
663          left = l;
664        } else {
665          return false;
666        }
667      }
668      true
669    }
670  }
671}
672
673impl<Bound: Width+Num> ProperSubset for IntervalSet<Bound>
674{
675  fn is_proper_subset(&self, other: &IntervalSet<Bound>) -> bool {
676    self.is_subset(other) && self.size() != other.size()
677  }
678}
679
680forward_all_binop!(impl<Bound: +Num+Width> Add for IntervalSet<Bound>, add);
681
682impl<'a, 'b, Bound: Num+Width> Add<&'b IntervalSet<Bound>> for &'a IntervalSet<Bound> {
683  type Output = IntervalSet<Bound>;
684
685  fn add(self, other: &IntervalSet<Bound>) -> IntervalSet<Bound> {
686    self.for_all_pairs(other, |i, j| i + j)
687  }
688}
689
690forward_all_binop!(impl<Bound: +Num+Width+Clone> Add for IntervalSet<Bound>, add, Bound);
691
692impl<'a, 'b, Bound: Num+Width+Clone> Add<&'b Bound> for &'a IntervalSet<Bound> {
693  type Output = IntervalSet<Bound>;
694
695  fn add(self, other: &Bound) -> IntervalSet<Bound> {
696    self.stable_map(|x| x + other.clone())
697  }
698}
699
700forward_all_binop!(impl<Bound: +Num+Width> Sub for IntervalSet<Bound>, sub);
701
702impl<'a, 'b, Bound: Num+Width> Sub<&'b IntervalSet<Bound>> for &'a IntervalSet<Bound> {
703  type Output = IntervalSet<Bound>;
704
705  fn sub(self, other: &IntervalSet<Bound>) -> IntervalSet<Bound> {
706    self.for_all_pairs(other, |i, j| i - j)
707  }
708}
709
710forward_all_binop!(impl<Bound: +Num+Width+Clone> Sub for IntervalSet<Bound>, sub, Bound);
711
712impl<'a, 'b, Bound: Num+Width+Clone> Sub<&'b Bound> for &'a IntervalSet<Bound> {
713  type Output = IntervalSet<Bound>;
714
715  fn sub(self, other: &Bound) -> IntervalSet<Bound> {
716    self.stable_map(|x| x - other.clone())
717  }
718}
719
720forward_all_binop!(impl<Bound: +Num+Width> Mul for IntervalSet<Bound>, mul);
721
722impl<'a, 'b, Bound: Num+Width> Mul<&'b IntervalSet<Bound>> for &'a IntervalSet<Bound> {
723  type Output = IntervalSet<Bound>;
724
725  // Caution: This is an over-approximation. For the same reason as `Interval::mul`.
726  fn mul(self, other: &IntervalSet<Bound>) -> IntervalSet<Bound> {
727    self.for_all_pairs(other, |i, j| i * j)
728  }
729}
730
731forward_all_binop!(impl<Bound: +Num+Width+Clone> Mul for IntervalSet<Bound>, mul, Bound);
732
733impl<'a, 'b, Bound: Num+Width+Clone> Mul<&'b Bound> for &'a IntervalSet<Bound> {
734  type Output = IntervalSet<Bound>;
735
736  // Caution: This is an over-approximation. For the same reason as `Interval::mul`.
737  fn mul(self, other: &Bound) -> IntervalSet<Bound> {
738    if self.is_empty() {
739      IntervalSet::empty()
740    } else if other == &Bound::zero() {
741      IntervalSet::singleton(Bound::zero())
742    } else if other == &Bound::one() {
743      self.clone()
744    } else {
745      self.map(|i| i * other.clone())
746    }
747  }
748}
749
750pub trait ToIntervalSet<Bound> where
751 Bound: Width
752{
753  fn to_interval_set(self) -> IntervalSet<Bound>;
754}
755
756impl<Bound: Width+Num> ToIntervalSet<Bound> for (Bound, Bound)
757{
758  fn to_interval_set(self) -> IntervalSet<Bound> {
759    vec![self].to_interval_set()
760  }
761}
762
763impl<Bound> ToIntervalSet<Bound> for Vec<(Bound, Bound)> where
764 Bound: Width + Num
765{
766  fn to_interval_set(self) -> IntervalSet<Bound> {
767    let mut intervals = IntervalSet::empty();
768    let mut to_add: Vec<_> = self.into_iter().map(|i| i.to_interval()).collect();
769    to_add.sort_unstable_by_key(|i| i.lower());
770    intervals.extend_at_back(to_add);
771    intervals
772  }
773}
774
775impl<Bound: Display+Width+Num> Display for IntervalSet<Bound> where
776 <Bound as Width>::Output: Display
777{
778  fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
779    if self.intervals.len() == 1 {
780      self.intervals[0].fmt(formatter)
781    }
782    else {
783      formatter.write_str("{")?;
784      for interval in &self.intervals  {
785        formatter.write_fmt(format_args!("{}", interval))?;
786      }
787      formatter.write_str("}")
788    }
789  }
790}
791
792impl<Bound> Join for IntervalSet<Bound> where
793 Bound: Width + Num
794{
795  fn join(self, other: IntervalSet<Bound>) -> IntervalSet<Bound> {
796    self.intersection(&other)
797  }
798}
799
800impl<Bound> Meet for IntervalSet<Bound> where
801 Bound: Width + Num
802{
803  fn meet(self, other: IntervalSet<Bound>) -> IntervalSet<Bound> {
804    self.union(&other)
805  }
806}
807
808impl<Bound> Entailment for IntervalSet<Bound> where
809 Bound: Width + Num
810{
811  fn entail(&self, other: &IntervalSet<Bound>) -> SKleene {
812    if self.is_subset(other) {
813      SKleene::True
814    }
815    else if other.is_subset(self) {
816      SKleene::False
817    }
818    else {
819      SKleene::Unknown
820    }
821  }
822}
823
824impl<Bound> Top for IntervalSet<Bound> where
825 Bound: Width + Num
826{
827  fn top() -> IntervalSet<Bound> {
828    IntervalSet::empty()
829  }
830}
831
832impl<Bound> Bot for IntervalSet<Bound> where
833 Bound: Width + Num
834{
835  fn bot() -> IntervalSet<Bound> {
836    IntervalSet::whole()
837  }
838}
839
840#[allow(non_upper_case_globals)]
841#[cfg(test)]
842mod tests {
843  use super::*;
844
845  const extend_example: [(i32, i32); 2] = [
846    (11, 33),
847    (-55, -44),
848  ];
849
850  fn test_inside_outside(is: IntervalSet<i32>, inside: Vec<i32>, outside: Vec<i32>) {
851    for i in &inside {
852      assert!(is.contains(i),
853        "{} is not contained inside {}, but it should.", i, is);
854    }
855    for i in &outside {
856      assert!(!is.contains(i),
857        "{} is contained inside {}, but it should not.", i, is);
858    }
859  }
860
861  // precondition: `intervals` must be a valid intern representation of the interval set.
862  fn make_interval_set(intervals: Vec<(i32, i32)>) -> IntervalSet<i32> {
863    intervals.to_interval_set()
864  }
865
866  fn test_result(test_id: String, result: &IntervalSet<i32>, expected: &IntervalSet<i32>) {
867    assert!(result.intervals == expected.intervals,
868      "{} | {} is different from the expected value: {}.", test_id, result, expected);
869  }
870
871  fn test_binary_op_sym<F>(test_id: String, a: Vec<(i32,i32)>, b: Vec<(i32,i32)>, op: F, expected: Vec<(i32,i32)>) where
872    F: Fn(&IntervalSet<i32>, &IntervalSet<i32>) -> IntervalSet<i32>
873  {
874    test_binary_op(test_id.clone(), a.clone(), b.clone(), |i,j| op(i,j), expected.clone());
875    test_binary_op(test_id, b, a, op, expected);
876  }
877
878  fn test_binary_op<F>(test_id: String, a: Vec<(i32,i32)>, b: Vec<(i32,i32)>, op: F, expected: Vec<(i32,i32)>) where
879    F: Fn(&IntervalSet<i32>, &IntervalSet<i32>) -> IntervalSet<i32>
880  {
881    println!("Info: {}.", test_id);
882    let a = make_interval_set(a);
883    let b = make_interval_set(b);
884    let expected = make_interval_set(expected);
885    test_result(test_id, &op(&a, &b), &expected);
886  }
887
888
889  fn test_binary_value_op<F>(test_id: String, a: Vec<(i32,i32)>, b: i32, op: F, expected: Vec<(i32,i32)>) where
890    F: Fn(&IntervalSet<i32>, i32) -> IntervalSet<i32>
891  {
892    println!("Info: {}.", test_id);
893    let a = make_interval_set(a);
894    let expected = make_interval_set(expected);
895    test_result(test_id, &op(&a, b), &expected);
896  }
897
898  fn test_binary_bool_op_sym<F>(test_id: String, a: Vec<(i32,i32)>, b: Vec<(i32,i32)>, op: F, expected: bool) where
899    F: Fn(&IntervalSet<i32>, &IntervalSet<i32>) -> bool
900  {
901    test_binary_bool_op(test_id.clone(), a.clone(), b.clone(), |i,j| op(i,j), expected);
902    test_binary_bool_op(test_id, b, a, op, expected);
903  }
904
905  fn test_binary_bool_op<F>(test_id: String, a: Vec<(i32,i32)>, b: Vec<(i32,i32)>, op: F, expected: bool) where
906    F: Fn(&IntervalSet<i32>, &IntervalSet<i32>) -> bool
907  {
908    println!("Info: {}.", test_id);
909    let a = make_interval_set(a);
910    let b = make_interval_set(b);
911    assert_eq!(op(&a, &b), expected);
912  }
913
914  fn test_binary_value_bool_op<V, F>(test_id: String, a: Vec<(i32,i32)>, b: V, op: F, expected: bool) where
915    F: Fn(&IntervalSet<i32>, &V) -> bool
916  {
917    println!("Info: {}.", test_id);
918    let a = make_interval_set(a);
919    assert_eq!(op(&a, &b), expected);
920  }
921
922  fn test_op<F>(test_id: String, a: Vec<(i32,i32)>, op: F, expected: Vec<(i32,i32)>) where
923    F: Fn(&IntervalSet<i32>) -> IntervalSet<i32>
924  {
925    println!("Info: {}.", test_id);
926    let a = make_interval_set(a);
927    let expected = make_interval_set(expected);
928    let result = op(&a);
929    test_result(test_id, &result, &expected);
930  }
931
932  #[test]
933  fn test_contains() {
934    let cases = vec![
935      (vec![], vec![], vec![-2,-1,0,1,2]),
936      (vec![(1,2)], vec![1,2], vec![-1,0,3,4]),
937      (vec![(1,2),(7,9)], vec![1,2,7,8,9], vec![-1,0,3,4,5,6,10,11]),
938      (vec![(1,2),(4,5),(7,9)], vec![1,2,4,5,7,8,9], vec![-1,0,3,6,10,11])
939    ];
940
941    for (is, inside, outside) in cases {
942      let is = make_interval_set(is);
943      test_inside_outside(is, inside, outside);
944    }
945  }
946
947  #[test]
948  fn test_complement() {
949    let min = <i32 as Width>::min_value();
950    let max = <i32 as Width>::max_value();
951
952    let cases = vec![
953      (1, vec![], vec![(min, max)]),
954      (2, vec![(min, max)], vec![]),
955      (3, vec![(0,0)], vec![(min,-1),(1,max)]),
956      (4, vec![(-5,5)], vec![(min,-6),(6,max)]),
957      (5, vec![(-5,-1),(1,5)], vec![(min,-6),(0,0),(6, max)]),
958      (6, vec![(min,-1),(1,5)], vec![(0,0),(6, max)]),
959      (7, vec![(-5,-1),(1,max)], vec![(min,-6),(0,0)]),
960      (8, vec![(min,-1),(1,max)], vec![(0,0)]),
961      (9, vec![(-5,-3),(0,1),(3,5)], vec![(min,-6),(-2,-1),(2,2),(6, max)])
962    ];
963
964    for (id, a, expected) in cases {
965      test_op(format!("test #{} of complement", id), a.clone(), |x| x.complement(), expected);
966      test_op(format!("test #{} of complement(complement)", id), a.clone(), |x| x.complement().complement(), a);
967    }
968  }
969
970  #[test]
971  fn test_union() {
972    // Note: the first number is the test id, so it should be easy to identify which test has failed.
973    // The two first vectors are the operands and the expected result is last.
974    let sym_cases = vec![
975      // identity tests
976      (1, vec![], vec![], vec![]),
977      (2, vec![], vec![(1,2)], vec![(1,2)]),
978      (3, vec![], vec![(1,2),(7,9)], vec![(1,2),(7,9)]),
979      (4, vec![(1,2),(7,9)], vec![(1,2)], vec![(1,2),(7,9)]),
980      (5, vec![(1,2),(7,9)], vec![(1,2),(7,9)], vec![(1,2),(7,9)]),
981      // front tests
982      (6, vec![(-3,-1)], vec![(1,2),(7,9)], vec![(-3,-1),(1,2),(7,9)]),
983      (7, vec![(-3,0)], vec![(1,2),(7,9)], vec![(-3,2),(7,9)]),
984      (8, vec![(-3,1)], vec![(1,2),(7,9)], vec![(-3,2),(7,9)]),
985      // middle tests
986      (9, vec![(2,7)], vec![(1,2),(7,9)], vec![(1,9)]),
987      (10, vec![(3,7)], vec![(1,2),(7,9)], vec![(1,9)]),
988      (11, vec![(4,5)], vec![(1,2),(7,9)], vec![(1,2),(4,5),(7,9)]),
989      (12, vec![(2,8)], vec![(1,2),(7,9)], vec![(1,9)]),
990      (13, vec![(2,6)], vec![(1,2),(7,9)], vec![(1,9)]),
991      (14, vec![(3,6)], vec![(1,2),(7,9)], vec![(1,9)]),
992      // back tests
993      (15, vec![(8,9)], vec![(1,2),(7,9)], vec![(1,2),(7,9)]),
994      (16, vec![(8,10)], vec![(1,2),(7,9)], vec![(1,2),(7,10)]),
995      (17, vec![(9,10)], vec![(1,2),(7,9)], vec![(1,2),(7,10)]),
996      (18, vec![(6,10)], vec![(1,2),(7,9)], vec![(1,2),(6,10)]),
997      (19, vec![(10,11)], vec![(1,2),(7,9)], vec![(1,2),(7,11)]),
998      (20, vec![(11,12)], vec![(1,2),(7,9)], vec![(1,2),(7,9),(11,12)]),
999      // mixed tests
1000      (21, vec![(-3,-1),(4,5),(11,12)], vec![(1,2),(7,9)], vec![(-3,-1),(1,2),(4,5),(7,9),(11,12)]),
1001      (22, vec![(-3,0),(3,6),(10,11)], vec![(1,2),(7,9)], vec![(-3,11)]),
1002      (23, vec![(-3,1),(3,7),(9,11)], vec![(1,2),(7,9)], vec![(-3,11)]),
1003      (24, vec![(-3,5),(7,11)], vec![(1,2),(7,9)], vec![(-3,5),(7,11)]),
1004      (25, vec![(-3,5),(7,8),(12,12)], vec![(1,2),(7,9)], vec![(-3,5),(7,9),(12,12)]),
1005      // englobing tests
1006      (26, vec![(-1,11)], vec![(1,2),(7,9)], vec![(-1,11)]),
1007    ];
1008
1009    for (id, a, b, expected) in sym_cases {
1010      test_binary_op_sym(format!("test #{} of union", id), a, b, |x,y| x.union(y), expected);
1011    }
1012  }
1013
1014  #[test]
1015  fn test_intersection() {
1016    // Note: the first number is the test id, so it should be easy to identify which test has failed.
1017    // The two first vectors are the operands and the expected result is last.
1018    let sym_cases = vec![
1019      // identity tests
1020      (1, vec![], vec![], vec![]),
1021      (2, vec![], vec![(1,2)], vec![]),
1022      (3, vec![], vec![(1,2),(7,9)], vec![]),
1023      (4, vec![(1,2),(7,9)], vec![(1,2)], vec![(1,2)]),
1024      (5, vec![(1,2),(7,9)], vec![(1,2),(7,9)], vec![(1,2),(7,9)]),
1025      // front tests
1026      (6, vec![(-3,-1)], vec![(1,2),(7,9)], vec![]),
1027      (7, vec![(-3,0)], vec![(1,2),(7,9)], vec![]),
1028      (8, vec![(-3,1)], vec![(1,2),(7,9)], vec![(1,1)]),
1029      // middle tests
1030      (9, vec![(2,7)], vec![(1,2),(7,9)], vec![(2,2),(7,7)]),
1031      (10, vec![(3,7)], vec![(1,2),(7,9)], vec![(7,7)]),
1032      (11, vec![(4,5)], vec![(1,2),(7,9)], vec![]),
1033      (12, vec![(2,8)], vec![(1,2),(7,9)], vec![(2,2),(7,8)]),
1034      (13, vec![(2,6)], vec![(1,2),(7,9)], vec![(2,2)]),
1035      (14, vec![(3,6)], vec![(1,2),(7,9)], vec![]),
1036      // back tests
1037      (15, vec![(8,9)], vec![(1,2),(7,9)], vec![(8,9)]),
1038      (16, vec![(8,10)], vec![(1,2),(7,9)], vec![(8,9)]),
1039      (17, vec![(9,10)], vec![(1,2),(7,9)], vec![(9,9)]),
1040      (18, vec![(6,10)], vec![(1,2),(7,9)], vec![(7,9)]),
1041      (19, vec![(10,11)], vec![(1,2),(7,9)], vec![]),
1042      (20, vec![(11,12)], vec![(1,2),(7,9)], vec![]),
1043      // mixed tests
1044      (21, vec![(-3,-1),(4,5),(11,12)], vec![(1,2),(7,9)], vec![]),
1045      (22, vec![(-3,0),(3,6),(10,11)], vec![(1,2),(7,9)], vec![]),
1046      (23, vec![(-3,1),(3,7),(9,11)], vec![(1,2),(7,9)], vec![(1,1),(7,7),(9,9)]),
1047      (24, vec![(-3,5),(7,11)], vec![(1,2),(7,9)], vec![(1,2),(7,9)]),
1048      (25, vec![(-3,5),(7,8),(12,12)], vec![(1,2),(7,9)], vec![(1,2),(7,8)]),
1049      // englobing tests
1050      (26, vec![(-1,11)], vec![(1,2),(7,9)], vec![(1,2),(7,9)]),
1051    ];
1052
1053    for (id, a, b, expected) in sym_cases {
1054      test_binary_op_sym(format!("test #{} of intersection", id), a, b, |x,y| x.intersection(y), expected);
1055    }
1056  }
1057
1058  #[test]
1059  fn test_to_interval_set() {
1060    // This example should not panic, and should yield the correct result.
1061    let intervals = vec![(3, 8), (2, 5)].to_interval_set();
1062    assert_eq!(intervals.interval_count(), 1);
1063    assert_eq!(intervals.lower(), 2);
1064    assert_eq!(intervals.upper(), 8);
1065  }
1066
1067  #[test]
1068  #[should_panic(expected = "This operation is only for pushing interval to the back of the array, possibly overlapping with the last element.")]
1069  fn test_extend_back() {
1070    // Calling extend_at_back with unordered input should panic.
1071    let mut set = IntervalSet::empty();
1072    let intervals = extend_example.map(|i| i.to_interval());
1073    set.extend_at_back(intervals);
1074    assert_eq!(set.interval_count(), 2);
1075  }
1076
1077  #[test]
1078  fn test_extend_empty() {
1079    // Calling extend with unordered input should not panic.
1080    let mut set = IntervalSet::empty();
1081    let intervals = extend_example.map(|i| i.to_interval());
1082    set.extend(intervals);
1083    assert_eq!(set.interval_count(), 2);
1084  }
1085
1086  #[test]
1087  fn test_extend_non_empty() {
1088    // Extending an IntervalSet with intervals that belong at the start or
1089    // the middle of the set should not panic.
1090    let mut intervals = vec![(10, 15), (20, 30)].to_interval_set();
1091    let at_start = vec![(0, 5).to_interval()];
1092    intervals.extend(at_start);
1093    let in_middle = vec![(17, 18).to_interval()];
1094    intervals.extend(in_middle);
1095
1096    assert_eq!(intervals.interval_count(), 4);
1097    assert_eq!(intervals.lower(), 0);
1098    assert_eq!(intervals.upper(), 30);
1099  }
1100
1101  #[test]
1102  fn test_difference() {
1103    // Note: the first number is the test id, so it should be easy to identify which test has failed.
1104    // The two first vectors are the operands and the two last are expected results (the first
1105    // for a.difference(b) and the second for b.difference(a)).
1106    let cases = vec![
1107      // identity tests
1108      (1, vec![], vec![], vec![], vec![]),
1109      (2, vec![], vec![(1,2)], vec![], vec![(1,2)]),
1110      (3, vec![], vec![(1,2),(7,9)], vec![], vec![(1,2),(7,9)]),
1111      (4, vec![(1,2),(7,9)], vec![(1,2)], vec![(7,9)], vec![]),
1112      (5, vec![(1,2),(7,9)], vec![(1,2),(7,9)], vec![], vec![]),
1113      // front tests
1114      (6, vec![(-3,-1)], vec![(1,2),(7,9)], vec![(-3,-1)], vec![(1,2),(7,9)]),
1115      (7, vec![(-3,0)], vec![(1,2),(7,9)], vec![(-3,0)], vec![(1,2),(7,9)]),
1116      (8, vec![(-3,1)], vec![(1,2),(7,9)], vec![(-3,0)], vec![(2,2),(7,9)]),
1117      // middle tests
1118      (9, vec![(2,7)], vec![(1,2),(7,9)], vec![(3,6)], vec![(1,1),(8,9)]),
1119      (10, vec![(3,7)], vec![(1,2),(7,9)], vec![(3,6)], vec![(1,2),(8,9)]),
1120      (11, vec![(4,5)], vec![(1,2),(7,9)], vec![(4,5)], vec![(1,2),(7,9)]),
1121      (12, vec![(2,8)], vec![(1,2),(7,9)], vec![(3,6)], vec![(1,1),(9,9)]),
1122      (13, vec![(2,6)], vec![(1,2),(7,9)], vec![(3,6)], vec![(1,1),(7,9)]),
1123      (14, vec![(3,6)], vec![(1,2),(7,9)], vec![(3,6)], vec![(1,2),(7,9)]),
1124      // back tests
1125      (15, vec![(8,9)], vec![(1,2),(7,9)], vec![], vec![(1,2),(7,7)]),
1126      (16, vec![(8,10)], vec![(1,2),(7,9)], vec![(10,10)], vec![(1,2),(7,7)]),
1127      (17, vec![(9,10)], vec![(1,2),(7,9)], vec![(10,10)], vec![(1,2),(7,8)]),
1128      (18, vec![(6,10)], vec![(1,2),(7,9)], vec![(6,6),(10,10)], vec![(1,2)]),
1129      (19, vec![(10,11)], vec![(1,2),(7,9)], vec![(10,11)], vec![(1,2),(7,9)]),
1130      (20, vec![(11,12)], vec![(1,2),(7,9)], vec![(11,12)], vec![(1,2),(7,9)]),
1131      // mixed tests
1132      (21, vec![(-3,-1),(4,5),(11,12)], vec![(1,2),(7,9)], vec![(-3,-1),(4,5),(11,12)], vec![(1,2),(7,9)]),
1133      (22, vec![(-3,0),(3,6),(10,11)], vec![(1,2),(7,9)], vec![(-3,0),(3,6),(10,11)], vec![(1,2),(7,9)]),
1134      (23, vec![(-3,1),(3,7),(9,11)], vec![(1,2),(7,9)], vec![(-3,0),(3,6),(10,11)], vec![(2,2),(8,8)]),
1135      (24, vec![(-3,5),(7,11)], vec![(1,2),(7,9)], vec![(-3,0),(3,5),(10,11)], vec![]),
1136      (25, vec![(-3,5),(7,8),(12,12)], vec![(1,2),(7,9)], vec![(-3,0),(3,5),(12,12)], vec![(9,9)]),
1137      // englobing tests
1138      (26, vec![(-1,11)], vec![(1,2),(7,9)], vec![(-1,0),(3,6),(10,11)], vec![]),
1139    ];
1140
1141    for (id, a, b, expected, expected_sym) in cases {
1142      test_binary_op(format!("test #{} of difference", id), a.clone(), b.clone(), |x,y| x.difference(y), expected);
1143      test_binary_op(format!("test #{} of difference", id), b, a, |x,y| x.difference(y), expected_sym);
1144    }
1145  }
1146
1147  #[test]
1148  fn test_symmetric_difference() {
1149    // Note: the first number is the test id, so it should be easy to identify which test has failed.
1150    // The two first vectors are the operands and the expected result is last.
1151    let sym_cases = vec![
1152      // identity tests
1153      (1, vec![], vec![], vec![]),
1154      (2, vec![], vec![(1,2)], vec![(1,2)]),
1155      (3, vec![], vec![(1,2),(7,9)], vec![(1,2),(7,9)]),
1156      (4, vec![(1,2),(7,9)], vec![(1,2)], vec![(7,9)]),
1157      (5, vec![(1,2),(7,9)], vec![(1,2),(7,9)], vec![]),
1158      // front tests
1159      (6, vec![(-3,-1)], vec![(1,2),(7,9)], vec![(-3,-1),(1,2),(7,9)]),
1160      (7, vec![(-3,0)], vec![(1,2),(7,9)], vec![(-3,2),(7,9)]),
1161      (8, vec![(-3,1)], vec![(1,2),(7,9)], vec![(-3,0),(2,2),(7,9)]),
1162      // middle tests
1163      (9, vec![(2,7)], vec![(1,2),(7,9)], vec![(1,1),(3,6),(8,9)]),
1164      (10, vec![(3,7)], vec![(1,2),(7,9)], vec![(1,6),(8,9)]),
1165      (11, vec![(4,5)], vec![(1,2),(7,9)], vec![(1,2),(4,5),(7,9)]),
1166      (12, vec![(2,8)], vec![(1,2),(7,9)], vec![(1,1),(3,6),(9,9)]),
1167      (13, vec![(2,6)], vec![(1,2),(7,9)], vec![(1,1),(3,9)]),
1168      (14, vec![(3,6)], vec![(1,2),(7,9)], vec![(1,9)]),
1169      // back tests
1170      (15, vec![(8,9)], vec![(1,2),(7,9)], vec![(1,2),(7,7)]),
1171      (16, vec![(8,10)], vec![(1,2),(7,9)], vec![(1,2),(7,7),(10,10)]),
1172      (17, vec![(9,10)], vec![(1,2),(7,9)], vec![(1,2),(7,8),(10,10)]),
1173      (18, vec![(6,10)], vec![(1,2),(7,9)], vec![(1,2),(6,6),(10,10)]),
1174      (19, vec![(10,11)], vec![(1,2),(7,9)], vec![(1,2),(7,11)]),
1175      (20, vec![(11,12)], vec![(1,2),(7,9)], vec![(1,2),(7,9),(11,12)]),
1176      // mixed tests
1177      (21, vec![(-3,-1),(4,5),(11,12)], vec![(1,2),(7,9)], vec![(-3,-1),(1,2),(4,5),(7,9),(11,12)]),
1178      (22, vec![(-3,0),(3,6),(10,11)], vec![(1,2),(7,9)], vec![(-3,11)]),
1179      (23, vec![(-3,1),(3,7),(9,11)], vec![(1,2),(7,9)], vec![(-3,0),(2,6),(8,8),(10,11)]),
1180      (24, vec![(-3,5),(7,11)], vec![(1,2),(7,9)], vec![(-3,0),(3,5),(10,11)]),
1181      (25, vec![(-3,5),(7,8),(12,12)], vec![(1,2),(7,9)], vec![(-3,0),(3,5),(9,9),(12,12)]),
1182      // englobing tests
1183      (26, vec![(-1,11)], vec![(1,2),(7,9)], vec![(-1,0),(3,6),(10,11)]),
1184    ];
1185
1186    for (id, a, b, expected) in sym_cases {
1187      test_binary_op_sym(format!("test #{} of symmetric difference", id),
1188        a, b, |x,y| x.symmetric_difference(y), expected);
1189    }
1190  }
1191
1192  #[test]
1193  fn test_overlap_and_is_disjoint() {
1194    // Note: the first number is the test id, so it should be easy to identify which test has failed.
1195    // The two first vectors are the operands and the expected result is last.
1196    let sym_cases = vec![
1197      // identity tests
1198      (1, vec![], vec![], false),
1199      (2, vec![], vec![(1,2)], false),
1200      (3, vec![], vec![(1,2),(7,9)], false),
1201      (4, vec![(1,2),(7,9)], vec![(1,2)], true),
1202      (5, vec![(1,2),(7,9)], vec![(1,2),(7,9)], true),
1203      // front tests
1204      (6, vec![(-3,-1)], vec![(1,2),(7,9)], false),
1205      (7, vec![(-3,0)], vec![(1,2),(7,9)], false),
1206      (8, vec![(-3,1)], vec![(1,2),(7,9)], true),
1207      // middle tests
1208      (9, vec![(2,7)], vec![(1,2),(7,9)], true),
1209      (10, vec![(3,7)], vec![(1,2),(7,9)], true),
1210      (11, vec![(4,5)], vec![(1,2),(7,9)], false),
1211      (12, vec![(2,8)], vec![(1,2),(7,9)], true),
1212      (13, vec![(2,6)], vec![(1,2),(7,9)], true),
1213      (14, vec![(3,6)], vec![(1,2),(7,9)], false),
1214      // back tests
1215      (15, vec![(8,9)], vec![(1,2),(7,9)], true),
1216      (16, vec![(8,10)], vec![(1,2),(7,9)], true),
1217      (17, vec![(9,10)], vec![(1,2),(7,9)], true),
1218      (18, vec![(6,10)], vec![(1,2),(7,9)], true),
1219      (19, vec![(10,11)], vec![(1,2),(7,9)], false),
1220      (20, vec![(11,12)], vec![(1,2),(7,9)], false),
1221      // mixed tests
1222      (21, vec![(-3,-1),(4,5),(11,12)], vec![(1,2),(7,9)], false),
1223      (22, vec![(-3,0),(3,6),(10,11)], vec![(1,2),(7,9)], false),
1224      (23, vec![(-3,1),(3,7),(9,11)], vec![(1,2),(7,9)], true),
1225      (24, vec![(-3,5),(7,11)], vec![(1,2),(7,9)], true),
1226      (25, vec![(-3,5),(7,8),(12,12)], vec![(1,2),(7,9)], true),
1227      // englobing tests
1228      (26, vec![(-1,11)], vec![(1,2),(7,9)], true),
1229    ];
1230
1231    for (id, a, b, expected) in sym_cases {
1232      test_binary_bool_op_sym(format!("test #{} of overlap", id),
1233        a.clone(), b.clone(), |x,y| x.overlap(y), expected);
1234      test_binary_bool_op_sym(format!("test #{} of is_disjoint", id),
1235        a, b, |x,y| x.is_disjoint(y), !expected);
1236    }
1237  }
1238
1239  fn overlap_cases() -> Vec<(u32, Vec<(i32,i32)>, i32, bool)> {
1240    vec![
1241      (1, vec![], 0, false),
1242      (2, vec![(1,2)], 0, false),
1243      (3, vec![(1,2)], 1, true),
1244      (4, vec![(1,2)], 2, true),
1245      (5, vec![(1,2)], 3, false),
1246      (6, vec![(1,3),(5,7)], 2, true),
1247      (7, vec![(1,3),(5,7)], 6, true),
1248      (8, vec![(1,3),(5,7)], 4, false),
1249      (9, vec![(1,3),(5,7)], 0, false),
1250      (10, vec![(1,3),(5,7)], 8, false)
1251    ]
1252  }
1253
1254  #[test]
1255  fn test_overlap_bound() {
1256    let cases = overlap_cases();
1257
1258    for (id, a, b, expected) in cases {
1259      test_binary_value_bool_op(format!("test #{} of overlap_bound", id),
1260        a.clone(), b, |x,y| x.overlap(y), expected);
1261      test_binary_value_bool_op(format!("test #{} of overlap_bound", id),
1262        a, b, |x,y| y.overlap(x), expected);
1263    }
1264  }
1265
1266  #[test]
1267  fn test_overlap_option() {
1268    let mut cases: Vec<(u32, Vec<(i32,i32)>, Optional<i32>, bool)> = overlap_cases().into_iter()
1269      .map(|(id,a,b,e)| (id,a,Optional::singleton(b),e))
1270      .collect();
1271    cases.extend(
1272      vec![
1273        (11, vec![], Optional::empty(), false),
1274        (12, vec![(1,2)], Optional::empty(), false),
1275        (13, vec![(1,3),(5,7)], Optional::empty(), false),
1276      ].into_iter()
1277    );
1278
1279    for (id, a, b, expected) in cases {
1280      test_binary_value_bool_op(format!("test #{} of overlap_option", id),
1281        a.clone(), b, |x,y| x.overlap(y), expected);
1282    }
1283  }
1284
1285  #[test]
1286  fn test_shrink() {
1287    let min = <i32 as Width>::min_value();
1288    let max = <i32 as Width>::max_value();
1289
1290    // Second and third args are the test value.
1291    // The fourth is the result of a shrink_left and the fifth of a shrink_right.
1292    let cases = vec![
1293      (1, vec![], 0, vec![], vec![]),
1294      (2, vec![(min, max)], 0, vec![(0, max)], vec![(min,0)]),
1295      (3, vec![(0,0)], 0, vec![(0,0)], vec![(0,0)]),
1296      (4, vec![(0,0)], -1, vec![(0,0)], vec![]),
1297      (5, vec![(0,0)], 1, vec![], vec![(0,0)]),
1298      (6, vec![(-5,5)], 0, vec![(0,5)], vec![(-5,0)]),
1299      (7, vec![(-5,5)], -5, vec![(-5,5)], vec![(-5,-5)]),
1300      (8, vec![(-5,5)], 5, vec![(5,5)], vec![(-5,5)]),
1301      (9, vec![(-5,-1),(1,5)], 0, vec![(1,5)], vec![(-5,-1)]),
1302      (10, vec![(-5,-1),(1,5)], 1, vec![(1,5)], vec![(-5,-1),(1,1)]),
1303      (11, vec![(-5,-1),(1,5)], -1, vec![(-1,-1),(1,5)], vec![(-5,-1)]),
1304      (12, vec![(min,-1),(1,5)], min, vec![(min,-1),(1,5)], vec![(min,min)]),
1305      (13, vec![(min,-1),(1,5)], max, vec![], vec![(min,-1),(1,5)]),
1306      (14, vec![(-5,-1),(1,max)], max, vec![(max, max)], vec![(-5,-1),(1,max)]),
1307      (15, vec![(min,-1),(1,max)], 0, vec![(1, max)], vec![(min, -1)]),
1308      (16, vec![(-5,-3),(0,1),(3,5)], 1, vec![(1,1),(3,5)], vec![(-5,-3),(0,1)])
1309    ];
1310
1311    for (id, a, v, expected_left, expected_right) in cases {
1312      test_binary_value_op(format!("test #{} of shrink_left", id),
1313        a.clone(), v, |x, v| x.shrink_left(v), expected_left);
1314      test_binary_value_op(format!("test #{} of shrink_right", id),
1315        a, v, |x, v| x.shrink_right(v), expected_right);
1316    }
1317  }
1318
1319  #[test]
1320  fn test_subset() {
1321    // Note: the first number is the test id, so it should be easy to identify which test has failed.
1322    // The two first vectors are the operands and the four last are expected results (resp.
1323    // `a.is_subset(b)`, `b.is_subset(a)`, `a.is_proper_subset(b)` and `b.is_proper_subset(a)`.
1324    let cases = vec![
1325      // identity tests
1326      (1, vec![], vec![], true, true, false, false),
1327      (2, vec![], vec![(1,2)], true, false, true, false),
1328      (3, vec![], vec![(1,2),(7,9)], true, false, true, false),
1329      (4, vec![(1,2),(7,9)], vec![(1,2)], false, true, false, true),
1330      (5, vec![(1,2),(7,9)], vec![(1,2),(7,9)], true, true, false, false),
1331      // middle tests
1332      (6, vec![(2,7)], vec![(1,2),(7,9)], false, false, false, false),
1333      (7, vec![(3,7)], vec![(1,2),(7,9)], false, false, false, false),
1334      (8, vec![(4,5)], vec![(1,2),(7,9)], false, false, false, false),
1335      (9, vec![(2,8)], vec![(1,2),(7,9)], false, false, false, false),
1336      // mixed tests
1337      (10, vec![(-3,-1),(4,5),(11,12)], vec![(-2,-1),(7,9)], false, false, false, false),
1338      (11, vec![(-3,0),(3,6),(10,11)], vec![(-2,-1),(4,4),(10,10)], false, true, false, true),
1339      (12, vec![(-3,0),(3,6),(10,11)], vec![(-3,0),(3,6),(10,11)], true, true, false, false),
1340      // englobing tests
1341      (13, vec![(-1,11)], vec![(1,2),(7,9)], false, true, false, true),
1342    ];
1343
1344    for (id, a, b, expected, expected_sym, expected_proper, expected_proper_sym) in cases {
1345      test_binary_bool_op(format!("test #{} of subset", id), a.clone(), b.clone(), |x,y| x.is_subset(y), expected);
1346      test_binary_bool_op(format!("test #{} of subset", id), b.clone(), a.clone(), |x,y| x.is_subset(y), expected_sym);
1347      test_binary_bool_op(format!("test #{} of proper subset", id), a.clone(), b.clone(), |x,y| x.is_proper_subset(y), expected_proper);
1348      test_binary_bool_op(format!("test #{} of proper subset", id), b.clone(), a.clone(), |x,y| x.is_proper_subset(y), expected_proper_sym);
1349    }
1350  }
1351
1352  #[test]
1353  fn test_arithmetics() {
1354    // Second and third args are the test values.
1355    // 4, 5, 6 and 7 are the results of `a + b`, `a - b`, `b - a` and `a * b`
1356    let cases = vec![
1357      (1, vec![], vec![], vec![], vec![], vec![], vec![]),
1358      (2, vec![], vec![(1,1),(3,5)], vec![], vec![], vec![], vec![]),
1359      (3, vec![(1,1),(3,5)], vec![(0,0)], vec![(1,1),(3,5)], vec![(1,1),(3,5)], vec![(-5,-3),(-1,-1)], vec![(0,0)]),
1360      (4, vec![(1,1),(3,5)], vec![(1,1)], vec![(2,2),(4,6)], vec![(0,0),(2,4)], vec![(-4,-2),(0,0)], vec![(1,1),(3,5)]),
1361      (5, vec![(1,1),(3,5)], vec![(0,1),(4,5)],
1362        vec![(1,10)],
1363        vec![(-4,5)],
1364        vec![(-5,4)],
1365        vec![(0,5),(12,25)]),
1366    ];
1367
1368    for (id, a, b, e_add, e_sub, e_sub_sym, e_mul) in cases {
1369      test_binary_op_sym(format!("test #{} of `a+b`", id),
1370        a.clone(), b.clone(), |x,y| x + y, e_add);
1371      test_binary_op(format!("test #{} of `a-b`", id),
1372        a.clone(), b.clone(), |x,y| x - y, e_sub);
1373      test_binary_op(format!("test #{} of `b-a`", id),
1374        b.clone(), a.clone(), |x,y| x - y, e_sub_sym);
1375      test_binary_op_sym(format!("test #{} of `a*b`", id),
1376        a.clone(), b.clone(), |x,y| x * y, e_mul);
1377    }
1378  }
1379
1380  #[test]
1381  fn test_arithmetics_bound() {
1382    let i1_35 = vec![(1,1),(3,5)];
1383    // Second and third args are the test value.
1384    // 4, 5 and 6 are the results of `a + b`, `a - b` and `a * b`
1385    let cases = vec![
1386      (1, vec![], 0, vec![], vec![], vec![]),
1387      (2, vec![(0,0)], 0, vec![(0,0)], vec![(0,0)], vec![(0,0)]),
1388      (3, i1_35.clone(), 0, i1_35.clone(), i1_35.clone(), vec![(0,0)]),
1389      (4, vec![], 1, vec![], vec![], vec![]),
1390      (5, vec![(0,0)], 1, vec![(1,1)], vec![(-1,-1)], vec![(0,0)]),
1391      (6, i1_35.clone(), 1, vec![(2,2),(4,6)], vec![(0,0),(2,4)], i1_35.clone()),
1392      (7, vec![], 3, vec![], vec![], vec![]),
1393      (8, vec![(0,0)], 3, vec![(3,3)], vec![(-3,-3)], vec![(0,0)]),
1394      (9, i1_35.clone(), 3, vec![(4,4),(6,8)], vec![(-2,-2),(0,2)], vec![(3,3),(9,15)])
1395    ];
1396
1397    for (id, a, b, e_add, e_sub, e_mul) in cases {
1398      test_binary_value_op(format!("test #{} of `a+b`", id),
1399        a.clone(), b.clone(), |x,y| x + y, e_add);
1400      test_binary_value_op(format!("test #{} of `a-b`", id),
1401        a.clone(), b.clone(), |x,y| x - y, e_sub);
1402      test_binary_value_op(format!("test #{} of `a*b`", id),
1403        a.clone(), b.clone(), |x,y| x * y, e_mul);
1404    }
1405  }
1406
1407  #[test]
1408  fn test_lattice() {
1409    use gcollections::ops::lattice::test::*;
1410    use trilean::SKleene::*;
1411    let whole = IntervalSet::<i32>::whole();
1412    let empty = IntervalSet::<i32>::empty();
1413    let a = vec![(0,5), (10,15)].to_interval_set();
1414    let b = vec![(5,10)].to_interval_set();
1415    let c = vec![(6,9)].to_interval_set();
1416    let d = vec![(4,6), (8,10)].to_interval_set();
1417    let e = vec![(5,5), (10,10)].to_interval_set();
1418    let f = vec![(6,6), (8,9)].to_interval_set();
1419    let g = vec![(0,15)].to_interval_set();
1420    let h = vec![(4,10)].to_interval_set();
1421    let tester = LatticeTester::new(
1422      0,
1423      /* data_a */  vec![empty.clone(), empty.clone(), whole.clone(), a.clone(), b.clone(), c.clone()],
1424      /* data_b */  vec![whole.clone(), a.clone(),     a.clone(),     b.clone(), c.clone(), d.clone()],
1425      /* a |= b*/   vec![True,          True,          False,         Unknown,   False,     Unknown],
1426      /* a |_| b */ vec![empty.clone(), empty.clone(), a.clone(),     e.clone(), c.clone(), f.clone()],
1427      /* a |-| b */ vec![whole.clone(), a.clone(),     whole.clone(), g.clone(), b.clone(), h.clone()]
1428    );
1429    tester.test_all();
1430  }
1431
1432  #[test]
1433  fn test_iterator() {
1434    let empty = IntervalSet::<i32>::empty();
1435    let mut a = vec![(0,5), (10,15)].to_interval_set();
1436    let mut iter = a.clone().into_iter();
1437    assert_eq!(iter.next(), Some(Interval::new(0,5)), "test 1 of test_iterator");
1438    assert_eq!(iter.next(), Some(Interval::new(10,15)), "test 2 of test_iterator");
1439    assert_eq!(iter.next(), None, "test 3 of test_iterator");
1440    for _x in a.clone() {}
1441    for _x in &a {}
1442    for _x in &mut a {}
1443    for _x in empty {
1444      assert!(false, "test 4 of test_iterator: empty interval must not yield an element.");
1445    }
1446  }
1447}