gtars_core/models/
interval.rs

1// https://github.com/sstadick/rust-lapper/blob/7e3904daed85181f1faa39b15f51935f13945976/src/lib.rs#L92
2use num_traits::{identities::zero, PrimInt, Unsigned};
3use std::cmp::Ordering::{self};
4
5/// Represent a range from [start, end)
6/// Inclusive start, exclusive of end
7#[derive(Eq, Debug, Clone)]
8pub struct Interval<I, T>
9where
10    I: PrimInt + Unsigned + Send + Sync,
11    T: Eq + Clone + Send + Sync,
12{
13    pub start: I,
14    pub end: I,
15    pub val: T,
16}
17
18impl<I, T> Ord for Interval<I, T>
19where
20    I: PrimInt + Unsigned + Send + Sync,
21    T: Eq + Clone + Send + Sync,
22{
23    #[inline]
24    fn cmp(&self, other: &Interval<I, T>) -> Ordering {
25        match self.start.cmp(&other.start) {
26            Ordering::Less => Ordering::Less,
27            Ordering::Greater => Ordering::Greater,
28            Ordering::Equal => self.end.cmp(&other.end),
29        }
30    }
31}
32
33impl<I, T> Interval<I, T>
34where
35    I: PrimInt + Unsigned + Send + Sync,
36    T: Eq + Clone + Send + Sync,
37{
38    /// Compute the intsect between two intervals
39    #[inline]
40    pub fn intersect(&self, other: &Interval<I, T>) -> I {
41        std::cmp::min(self.end, other.end)
42            .checked_sub(std::cmp::max(&self.start, &other.start))
43            .unwrap_or_else(zero::<I>)
44    }
45
46    /// Check if two intervals overlap
47    #[inline]
48    pub fn overlap(&self, start: I, end: I) -> bool {
49        self.start < end && self.end > start
50    }
51}
52
53impl<I, T> PartialOrd for Interval<I, T>
54where
55    I: PrimInt + Unsigned + Send + Sync,
56    T: Eq + Clone + Send + Sync,
57{
58    #[inline]
59    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
60        Some(self.cmp(other))
61    }
62}
63
64impl<I, T> PartialEq for Interval<I, T>
65where
66    I: PrimInt + Unsigned + Send + Sync,
67    T: Eq + Clone + Send + Sync,
68{
69    #[inline]
70    fn eq(&self, other: &Interval<I, T>) -> bool {
71        self.start == other.start && self.end == other.end
72    }
73}