rust_rcs_core/util/
ranges.rs

1// Copyright 2023 宋昊文
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use 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}