1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
//! Type and functions for comparing inclusive ranges

use ::{std};

use num_traits::PrimInt;

///////////////////////////////////////////////////////////////////////////////
//  enums                                                                    //
///////////////////////////////////////////////////////////////////////////////

/// Result of comparing a pair of ranges `(A,B)`
#[derive(Debug,Eq,PartialEq)]
pub enum RangeCompare {
  Disjoint  (RangeDisjoint),
  Intersect (RangeIntersect)
}

/// Ways in which a pair of ranges `(A,B)` can be disjoint
#[derive(Debug,Eq,PartialEq)]
pub enum RangeDisjoint {
  /// `A = B = {}`
  EmptyBoth,
  /// `A = {}`
  EmptyLhs,
  /// `B = {}`
  EmptyRhs,
  /// `[ A ]  [ B ]`
  LessThanProper,
  /// `[ A ][ B ]`
  LessThanAdjacent,
  /// `[ B ]  [ A ]`
  GreaterThanProper,
  /// `[ B ][ A ]`
  GreaterThanAdjacent
}

/// Ways in which a pair of ranges `(A,B)` can intersect
#[derive(Debug,Eq,PartialEq)]
pub enum RangeIntersect {
  /// `[ A=B ]`
  EqualTo,
  /// `[ A [ ] B ]`
  OverlapsLeft,
  /// `[ B [ ] A ]`
  OverlapsRight,
  /// `[ B ] A ]`
  ContainsFirst,
  /// `[ A [ B ] ]`
  ContainsProper,
  /// `[ A [ B ]`
  ContainsLast,
  /// `[ A ] B ]`
  ContainedByFirst,
  /// `[ [ A ] B ]`
  ContainedByProper,
  /// `[ B [ A ]`
  ContainedByLast
}

///////////////////////////////////////////////////////////////////////////////
//  functions                                                                //
///////////////////////////////////////////////////////////////////////////////

/// Compare two inclusive ranges.
///
/// ```
/// # #![feature(inclusive_range_syntax)]
/// # use range_set::*;
/// assert_eq!(
///   range_compare (&(0..=5), &(0..=5)),
///   RangeCompare::Intersect (RangeIntersect::EqualTo));
/// assert_eq!(
///   range_compare (&(1..=0), &(1..=0)),
///   RangeCompare::Disjoint (RangeDisjoint::EmptyBoth));
/// ```
pub fn range_compare <T : PrimInt> (
  left : &std::ops::RangeInclusive <T>, right : &std::ops::RangeInclusive <T>
) -> RangeCompare {
  if let Some (disjoint) = RangeDisjoint::compare (left, right) {
    disjoint.into()
  } else if let Some (intersect) = RangeIntersect::compare (left, right) {
    intersect.into()
  } else {
    unreachable!()
  }
}

/// Compute the intersection of two inclusive ranges. Returns an empty range
/// if they are disjoint.
///
/// ```
/// # #![feature(inclusive_range_syntax)]
/// # use range_set::*;
/// assert_eq!(
///   intersection (&(0..=3), &(2..=5)),
///   2..=3);
/// assert!(is_empty (&intersection (&(0..=2), &(3..=5))));
/// ```
pub fn intersection <T : PrimInt> (
  left : &std::ops::RangeInclusive <T>, right : &std::ops::RangeInclusive <T>
) -> std::ops::RangeInclusive <T> {
  if let None = RangeDisjoint::compare (left, right) {
    std::cmp::max (left.start, right.start)..=std::cmp::min (left.end, right.end)
  } else {
    T::one()..=T::zero()
  }
}

/// TODO: replace with standard library is_empty method when PR #48087 is merged
///
/// ```
/// # #![feature(inclusive_range_syntax)]
/// # use range_set::*;
/// assert!(is_empty (&(1..=0)));
/// ```
#[inline]
pub fn is_empty <T : PrimInt>
  (range : &std::ops::RangeInclusive <T>) -> bool
{
  range.end < range.start
}

///////////////////////////////////////////////////////////////////////////////
//  impls                                                                    //
///////////////////////////////////////////////////////////////////////////////

impl From <RangeDisjoint> for RangeCompare {
  fn from (disjoint : RangeDisjoint) -> Self {
    RangeCompare::Disjoint (disjoint)
  }
}

impl From <RangeIntersect> for RangeCompare {
  fn from (intersect : RangeIntersect) -> Self {
    RangeCompare::Intersect (intersect)
  }
}

impl RangeDisjoint {
  /// Tests two inclusive ranges for disjointness, returning `None` if they
  /// intersect.
  ///
  /// ```
  /// # #![feature(inclusive_range_syntax)]
  /// # use range_set::*;
  /// assert_eq!(RangeDisjoint::compare (&(0..=5), &(0..=5)), None);
  /// assert_eq!(
  ///   RangeDisjoint::compare (&(1..=0), &(1..=0)),
  ///   Some (RangeDisjoint::EmptyBoth));
  /// assert_eq!(
  ///   RangeDisjoint::compare (&(1..=0), &(0..=5)),
  ///   Some (RangeDisjoint::EmptyLhs));
  /// assert_eq!(
  ///   RangeDisjoint::compare (&(0..=5), &(1..=0)),
  ///   Some (RangeDisjoint::EmptyRhs));
  /// assert_eq!(
  ///   RangeDisjoint::compare (&(0..=2), &(4..=5)),
  ///   Some (RangeDisjoint::LessThanProper));
  /// assert_eq!(
  ///   RangeDisjoint::compare (&(0..=2), &(3..=5)),
  ///   Some (RangeDisjoint::LessThanAdjacent));
  /// assert_eq!(
  ///   RangeDisjoint::compare (&(4..=5), &(0..=2)),
  ///   Some (RangeDisjoint::GreaterThanProper));
  /// assert_eq!(
  ///   RangeDisjoint::compare (&(3..=5), &(0..=2)),
  ///   Some (RangeDisjoint::GreaterThanAdjacent));
  /// ```
  pub fn compare <T : PrimInt> (
    left : &std::ops::RangeInclusive <T>, right : &std::ops::RangeInclusive <T>
  ) -> Option <Self> {
    match (is_empty (left), is_empty (right)) {
      (true, true)   => Some (RangeDisjoint::EmptyBoth),
      (true, false)  => Some (RangeDisjoint::EmptyLhs),
      (false, true)  => Some (RangeDisjoint::EmptyRhs),
      (false, false) => if right.start <= left.end && left.start <= right.end
        || left.start <= right.end && right.start <= left.end
      {
        None  // intersection
      } else {
        Some (
          if left.end < right.start {
            match right.start - left.end {
              x if x == T::one() => RangeDisjoint::LessThanAdjacent,
              _                  => RangeDisjoint::LessThanProper
            }
          } else {
            debug_assert!(right.end < left.start);
            match left.start - right.end {
              x if x == T::one() => RangeDisjoint::GreaterThanAdjacent,
              _                  => RangeDisjoint::GreaterThanProper
            }
          }
        )
      }
    }
  }
}

impl RangeIntersect {
  /// Test two inclusive ranges for intersection, returning `None` if the
  /// ranges are disjoint.
  ///
  /// ```
  /// # #![feature(inclusive_range_syntax)]
  /// # use range_set::*;
  /// assert_eq!(RangeIntersect::compare (&(0..=1), &(4..=5)), None);
  /// assert_eq!(
  ///   RangeIntersect::compare (&(0..=5), &(0..=5)),
  ///   Some (RangeIntersect::EqualTo));
  /// assert_eq!(
  ///   RangeIntersect::compare (&(0..=5), &(1..=4)),
  ///   Some (RangeIntersect::ContainsProper));
  /// assert_eq!(
  ///   RangeIntersect::compare (&(1..=4), &(0..=5)),
  ///   Some (RangeIntersect::ContainedByProper));
  /// assert_eq!(
  ///   RangeIntersect::compare (&(0..=5), &(0..=3)),
  ///   Some (RangeIntersect::ContainsFirst));
  /// assert_eq!(
  ///   RangeIntersect::compare (&(0..=5), &(4..=5)),
  ///   Some (RangeIntersect::ContainsLast));
  /// assert_eq!(
  ///   RangeIntersect::compare (&(0..=2), &(0..=5)),
  ///   Some (RangeIntersect::ContainedByFirst));
  /// assert_eq!(
  ///   RangeIntersect::compare (&(4..=5), &(0..=5)),
  ///   Some (RangeIntersect::ContainedByLast));
  /// assert_eq!(
  ///   RangeIntersect::compare (&(0..=3), &(3..=5)),
  ///   Some (RangeIntersect::OverlapsLeft));
  /// assert_eq!(
  ///   RangeIntersect::compare (&(3..=5), &(0..=3)),
  ///   Some (RangeIntersect::OverlapsRight));
  /// ```
  pub fn compare <T : PrimInt> (
    left : &std::ops::RangeInclusive <T>, right : &std::ops::RangeInclusive <T>
  ) -> Option <Self> {
    match (is_empty (left), is_empty (right)) {
      (true, true) | (true, false) | (false, true) => None,
      (false, false) => if left.end < right.start || right.end < left.start {
        None  // disjoint
      } else {
        Some (if left == right {
          RangeIntersect::EqualTo
        } else {
          match left.start.cmp (&right.start) {
            std::cmp::Ordering::Less => match left.end.cmp (&right.end) {
              std::cmp::Ordering::Less    => RangeIntersect::OverlapsLeft,
              std::cmp::Ordering::Equal   => RangeIntersect::ContainsLast,
              std::cmp::Ordering::Greater => RangeIntersect::ContainsProper
            }
            std::cmp::Ordering::Equal => match left.end.cmp (&right.end) {
              std::cmp::Ordering::Less    => RangeIntersect::ContainedByFirst,
              std::cmp::Ordering::Equal   => unreachable!(),
              std::cmp::Ordering::Greater => RangeIntersect::ContainsFirst
            }
            std::cmp::Ordering::Greater => match left.end.cmp (&right.end) {
              std::cmp::Ordering::Less    => RangeIntersect::ContainedByProper,
              std::cmp::Ordering::Equal   => RangeIntersect::ContainedByLast,
              std::cmp::Ordering::Greater => RangeIntersect::OverlapsRight
            }
          }
        })
      }
    }
  }
}