use std::fmt;
pub struct MicroTime {
microday: f64,
}
impl MicroTime {
pub fn from_f64(microday: f64) -> Self {
MicroTime { microday: microday }
}
pub fn from_seconds(seconds: f64) -> Self {
MicroTime {
microday: seconds / 0.0864,
}
}
pub fn from_str(micros: &str) -> Option<MicroTime> {
let micros_unit = micros.get(micros.len() - 3..micros.len())?;
if micros_unit != "μd" {
return None;
};
let microday = micros.get(0..micros.len() - 3)?.parse::<f64>().ok()?;
Some(MicroTime { microday })
}
pub fn to_seconds(&self) -> f64 {
self.microday() * 0.0864
}
pub fn microday(&self) -> f64 {
self.microday
}
}
impl fmt::Display for MicroTime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, r#"{:.3}μd"#, self.microday)
}
}
#[cfg(test)]
mod test {
#[test]
pub fn t12_seconds_to_micros() {
let micros = super::MicroTime::from_seconds(9.58);
assert_eq!(micros.microday(), 110.87962962962962);
}
#[test]
pub fn t13_micros_from_str_opt() {
let micros = super::MicroTime::from_str("110.8μd").unwrap();
assert_eq!(micros.microday(), 110.8);
}
#[test]
pub fn t14_micros_to_seconds() {
let micros = super::MicroTime::from_f64(110.0);
let seconds = micros.to_seconds();
assert_eq!(seconds, 9.504000000000001);
}
#[test]
pub fn t15_micros_to_str() {
let micros = super::MicroTime::from_f64(110.0);
assert_eq!(micros.to_string(), "110.000μd");
}
}