rust_rcs_core/util/
ranges.rs1use std::ops::Range;
16
17pub trait RangeOperations<Rhs: ?Sized = Self>
18where
19 Self: Sized,
20{
21 fn intersects(&self, rhs: &Rhs) -> bool;
22 fn covering(&self, rhs: &Rhs) -> bool;
23 fn covered_by(&self, rhs: &Rhs) -> bool;
24 fn union(&self, rhs: &Rhs) -> Option<Self>;
25}
26
27impl<Idx> RangeOperations for Range<Idx>
28where
29 Idx: PartialOrd + Copy,
30{
31 fn intersects(&self, rhs: &Range<Idx>) -> bool {
32 (self.start < rhs.start && self.end > rhs.start)
33 || (rhs.start < self.start && rhs.end > self.start)
34 }
35
36 fn covering(&self, rhs: &Range<Idx>) -> bool {
37 self.start <= rhs.start && self.end >= rhs.end
38 }
39
40 fn covered_by(&self, rhs: &Range<Idx>) -> bool {
41 self.start >= rhs.start && self.end <= rhs.end
42 }
43
44 fn union(&self, rhs: &Range<Idx>) -> Option<Range<Idx>> {
45 if self.start <= rhs.start && self.end >= rhs.start {
46 if self.end > rhs.end {
47 Some(Range {
48 start: self.start,
49 end: self.end,
50 })
51 } else {
52 Some(Range {
53 start: self.start,
54 end: rhs.end,
55 })
56 }
57 } else if rhs.start <= self.start && rhs.end >= self.start {
58 if rhs.end > self.end {
59 Some(Range {
60 start: rhs.start,
61 end: rhs.end,
62 })
63 } else {
64 Some(Range {
65 start: rhs.start,
66 end: self.end,
67 })
68 }
69 } else {
70 None
71 }
72 }
73}