pub trait FormatTime {
fn format_time(&self, w: &mut impl std::fmt::Write) -> std::fmt::Result;
}
impl FormatTime for () {
fn format_time(&self, _w: &mut impl std::fmt::Write) -> std::fmt::Result {
Ok(())
}
}
#[cfg(feature = "time")]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Default)]
pub struct UtcDateTime;
#[cfg(feature = "time")]
impl FormatTime for UtcDateTime {
fn format_time(&self, w: &mut impl std::fmt::Write) -> std::fmt::Result {
let time = time::OffsetDateTime::now_utc();
write!(w, "{} {}", time.date(), time.time())
}
}
#[cfg(feature = "time")]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Default)]
pub struct LocalDateTime;
#[cfg(feature = "time")]
impl FormatTime for LocalDateTime {
fn format_time(&self, w: &mut impl std::fmt::Write) -> std::fmt::Result {
let time = time::OffsetDateTime::now_local().expect("time offset cannot be determined");
write!(w, "{}", time)
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct Uptime {
epoch: std::time::Instant,
}
impl Default for Uptime {
fn default() -> Self {
Uptime {
epoch: std::time::Instant::now(),
}
}
}
impl From<std::time::Instant> for Uptime {
fn from(epoch: std::time::Instant) -> Self {
Uptime { epoch }
}
}
impl FormatTime for Uptime {
fn format_time(&self, w: &mut impl std::fmt::Write) -> std::fmt::Result {
let e = self.epoch.elapsed();
write!(w, "{:4}.{:06}s", e.as_secs(), e.subsec_micros())
}
}
impl<'a, F> FormatTime for &'a F
where
F: FormatTime,
{
fn format_time(&self, w: &mut impl std::fmt::Write) -> std::fmt::Result {
(*self).format_time(w)
}
}