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)]
5pub struct Interval {
6    pub valid_from: String,
7    pub valid_to: String,
8}
9
10impl Interval {
11    pub fn new(valid_from: impl Into<String>, valid_to: impl Into<String>) -> Self {
12        Self {
13            valid_from: valid_from.into(),
14            valid_to: valid_to.into(),
15        }
16    }
17
18    /// Check if interval represents an open interval (`OPEN_SENTINEL`).
19    pub fn is_open(&self) -> bool {
20        self.valid_to == OPEN_SENTINEL
21    }
22
23    /// Check if timestamp falls within half-open interval [valid_from, valid_to).
24    pub fn contains(&self, ts: &str) -> bool {
25        self.valid_from.as_str() <= ts && ts < self.valid_to.as_str()
26    }
27
28    /// Check if two half-open intervals overlap: max(start1, start2) < min(end1, end2).
29    pub fn overlaps(&self, other: &Interval) -> bool {
30        let max_start = std::cmp::max(self.valid_from.as_str(), other.valid_from.as_str());
31        let min_end = std::cmp::min(self.valid_to.as_str(), other.valid_to.as_str());
32        max_start < min_end
33    }
34}