use std::{
fmt::Display,
time::{Duration, SystemTime, SystemTimeError},
};
#[derive(Clone, Debug)]
pub struct TimestampedEmit<T> {
pub value: T,
pub timestamp: u128,
error: Option<&'static str>,
sys_time_error: Option<SystemTimeError>,
}
impl<T> TimestampedEmit<T> {
pub fn error_duration(&self) -> Option<Duration> {
if let Some(ste) = &self.sys_time_error {
return Some(ste.duration());
}
None
}
pub fn error_str(&self) -> Option<&'static str> {
self.error
}
pub fn is_error(&self) -> bool {
if self.error.is_none() {
return false;
}
true
}
pub(super) fn new(value: T) -> TimestampedEmit<T> {
let mut error = None;
let mut sys_time_error = None;
let timestamp = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_else(|ste| {
error = Some("Error: Attempted to calculate a time before the Unix epoch. Your system clock might be misconfigured.");
sys_time_error = Some(ste);
Duration::new(0, 0)
})
.as_millis();
TimestampedEmit {
value,
timestamp,
error,
sys_time_error,
}
}
}
impl<T: Display> Display for TimestampedEmit<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "value: {}\ntimestamp: {}", self.value, self.timestamp)
}
}