Skip to main content

ferroui_reactive/
time_interval.rs

1//! `TimeInterval<T>` and `Timestamped<T>` (`TimeInterval.cs`, `Timestamped.cs`).
2
3use std::fmt;
4use std::time::{Duration, SystemTime};
5
6/// A value with the time since the previous value (`TimeInterval<T>`).
7#[derive(Clone, Debug, PartialEq, Eq, Hash)]
8pub struct TimeInterval<T> {
9    /// The value (`Value`).
10    pub value: T,
11    /// The time since the previous value (`Interval`).
12    pub interval: Duration,
13}
14
15impl<T> TimeInterval<T> {
16    pub fn new(value: T, interval: Duration) -> Self {
17        Self { value, interval }
18    }
19}
20
21impl<T: fmt::Display> fmt::Display for TimeInterval<T> {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        write!(f, "{}@{:?}", self.value, self.interval)
24    }
25}
26
27/// A value with the time it was produced (`Timestamped<T>`).
28#[derive(Clone, Debug, PartialEq, Eq, Hash)]
29pub struct Timestamped<T> {
30    /// The value (`Value`).
31    pub value: T,
32    /// The time of the value (`Timestamp`).
33    pub timestamp: SystemTime,
34}
35
36impl<T> Timestamped<T> {
37    pub fn new(value: T, timestamp: SystemTime) -> Self {
38        Self { value, timestamp }
39    }
40}
41
42impl<T: fmt::Display> fmt::Display for Timestamped<T> {
43    /// `value@timestamp` (`ToString`), the time as the duration since the epoch of the system time.
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        let since_epoch = self.timestamp.duration_since(SystemTime::UNIX_EPOCH).unwrap_or_default();
46        write!(f, "{}@{:?}", self.value, since_epoch)
47    }
48}