interval.rs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. use std::cmp::{max, min};
  2. #[derive(Clone, Copy, PartialEq, Eq)]
  3. pub struct Interval {
  4. pub start: i64,
  5. pub end: i64,
  6. }
  7. impl Interval {
  8. /// Construct a new `Interval` representing the range [start..end).
  9. /// It is an invariant that `start <= end`.
  10. pub fn new(start: i64, end: i64) -> Interval {
  11. debug_assert!(start <= end);
  12. Interval { start, end }
  13. }
  14. pub fn start(&self) -> i64 { self.start }
  15. pub fn end(&self) -> i64 { self.end }
  16. pub fn is_before(&self, val: i64) -> bool { self.end <= val }
  17. pub fn contains(&self, val: i64) -> bool { self.start <= val && val < self.end }
  18. pub fn contains_range(&self, start: i64, end: i64) -> bool { !self.intersect(Interval::new(start, end)).is_empty() }
  19. pub fn is_after(&self, val: i64) -> bool { self.start > val }
  20. pub fn is_empty(&self) -> bool { self.end <= self.start }
  21. pub fn intersect(&self, other: Interval) -> Interval {
  22. let start = max(self.start, other.start);
  23. let end = min(self.end, other.end);
  24. Interval {
  25. start,
  26. end: max(start, end),
  27. }
  28. }
  29. // the first half of self - other
  30. pub fn prefix(&self, other: Interval) -> Interval {
  31. Interval {
  32. start: min(self.start, other.start),
  33. end: min(self.end, other.start),
  34. }
  35. }
  36. // the second half of self - other
  37. pub fn suffix(&self, other: Interval) -> Interval {
  38. Interval {
  39. start: max(self.start, other.end),
  40. end: max(self.end, other.end),
  41. }
  42. }
  43. pub fn size(&self) -> i64 { self.end - self.start }
  44. }