use std::time::{Duration, SystemTime, UNIX_EPOCH};
use crate::errors::InternalError;
const NANOS_PER_SEC: u128 = 1_000_000_000;
pub fn system_time_to_nanos(time: SystemTime) -> crate::Result<i128> {
if time > UNIX_EPOCH {
Ok(time
.duration_since(UNIX_EPOCH)
.map_err(|err| InternalError::Other {
reason: err.to_string(),
})?
.as_nanos() as i128)
} else {
let duration = UNIX_EPOCH
.duration_since(time)
.map_err(|err| InternalError::Other {
reason: err.to_string(),
})?;
Ok(-(duration.as_nanos() as i128))
}
}
pub fn system_time_from_nanos(nanos: i128) -> SystemTime {
let unsigned_nanos = nanos.unsigned_abs();
let secs = u64::try_from(unsigned_nanos / NANOS_PER_SEC)
.expect("Overflow decoding bytes to timestamp.");
let subsec_nanos = (unsigned_nanos % NANOS_PER_SEC) as u32;
if nanos < 0 {
UNIX_EPOCH - Duration::new(secs, subsec_nanos)
} else {
UNIX_EPOCH + Duration::new(secs, subsec_nanos)
}
}