endstat/src/utils.rs

50 lines
1.1 KiB
Rust
Raw Permalink Normal View History

2019-04-30 19:49:22 -07:00
use serde::{Serialize, Serializer};
use std::{
fmt::{Display, Formatter, Result as FmtResult},
ops::Sub,
time::{SystemTime, UNIX_EPOCH},
};
2019-05-01 09:58:10 -07:00
#[derive(PartialEq, PartialOrd, Copy, Clone, Debug)]
2019-04-30 19:49:22 -07:00
pub struct EpochTimestamp(SystemTime);
impl EpochTimestamp {
pub fn now() -> Self {
EpochTimestamp(SystemTime::now())
}
}
impl Sub for EpochTimestamp {
type Output = u64;
fn sub(self, other: EpochTimestamp) -> u64 {
self.0.duration_since(other.0).unwrap_or_default().as_secs()
}
}
impl Display for EpochTimestamp {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(
f,
"{}",
self.0
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
)
}
}
impl Serialize for EpochTimestamp {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
s.serialize_u64(
self.0
.duration_since(SystemTime::from(UNIX_EPOCH))
.unwrap_or_default()
.as_secs(),
)
}
}