Skip to main content

macrame/temporal/
interval.rs

1use crate::util::timestamp::OPEN_SENTINEL;
2
3/// Half-open valid time interval [valid_from, valid_to).
4#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
5#[non_exhaustive]
6pub struct Interval {
7    pub valid_from: String,
8    pub valid_to: String,
9}
10
11impl Interval {
12    pub fn new(valid_from: impl Into<String>, valid_to: impl Into<String>) -> Self {
13        Self {
14            valid_from: valid_from.into(),
15            valid_to: valid_to.into(),
16        }
17    }
18
19    /// Check if interval represents an open interval (`OPEN_SENTINEL`).
20    pub fn is_open(&self) -> bool {
21        self.valid_to == OPEN_SENTINEL
22    }
23
24    /// Check if timestamp falls within half-open interval [valid_from, valid_to).
25    pub fn contains(&self, ts: &str) -> bool {
26        self.valid_from.as_str() <= ts && ts < self.valid_to.as_str()
27    }
28
29    /// Check if two half-open intervals overlap: max(start1, start2) < min(end1, end2).
30    pub fn overlaps(&self, other: &Interval) -> bool {
31        let max_start = std::cmp::max(self.valid_from.as_str(), other.valid_from.as_str());
32        let min_end = std::cmp::min(self.valid_to.as_str(), other.valid_to.as_str());
33        max_start < min_end
34    }
35}