Skip to main content

scan_core/
time.rs

1use std::ops::{Bound, RangeBounds};
2
3use get_size2::GetSize;
4
5/// The type that represents time.
6pub type Time = u32;
7
8/// A time constraint given by lower bound and upper bounds.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10pub struct TimeRange {
11    lower_bound: Bound<Time>,
12    upper_bound: Bound<Time>,
13}
14
15impl GetSize for TimeRange {}
16
17impl RangeBounds<Time> for TimeRange {
18    fn start_bound(&self) -> Bound<&Time> {
19        self.lower_bound.as_ref()
20    }
21
22    fn end_bound(&self) -> Bound<&Time> {
23        self.upper_bound.as_ref()
24    }
25}
26
27impl TimeRange {
28    /// Creates new [`TimeRange`] from any range.
29    pub fn new<R: RangeBounds<Time>>(range: R) -> Self {
30        TimeRange {
31            lower_bound: range.start_bound().cloned(),
32            upper_bound: range.end_bound().cloned(),
33        }
34    }
35
36    /// Shift time range in the future for the given delta.
37    pub fn shift(&self, delta: Time) -> Self {
38        let lower_bound = match self.lower_bound {
39            Bound::Included(l) => Bound::Included(l.saturating_add(delta)),
40            Bound::Excluded(l) => Bound::Excluded(l.saturating_add(delta)),
41            Bound::Unbounded => Bound::Unbounded,
42        };
43        let upper_bound = match self.upper_bound {
44            Bound::Included(r) => Bound::Included(r.saturating_add(delta)),
45            Bound::Excluded(r) => Bound::Excluded(r.saturating_add(delta)),
46            Bound::Unbounded => Bound::Unbounded,
47        };
48        TimeRange {
49            lower_bound,
50            upper_bound,
51        }
52    }
53}