use crate::error::{HlcError, HlcResult};
pub const EPOCH: i64 = 1_704_067_200_000;
#[derive(Debug)]
pub struct CustomEpochTimestamp(u64);
impl CustomEpochTimestamp {
pub fn from_millis(ms: u64) -> Self {
Self(ms)
}
pub fn millis(&self) -> u64 {
self.0
}
pub fn from_unix_timestamp(unix_timestamp: i64) -> HlcResult<Self> {
if unix_timestamp < EPOCH {
return Err(HlcError::TimestampBelowMin(unix_timestamp, EPOCH));
}
Ok(Self::from_millis((unix_timestamp - EPOCH) as u64))
}
pub fn to_unix_timestamp(ms: u64) -> i64 {
ms as i64 + EPOCH
}
}
#[cfg(test)]
mod tests {
use chrono::{TimeZone, Utc};
use super::*;
#[test]
fn custom_epoch_is_correct() {
let expected_epoch = Utc
.with_ymd_and_hms(2024, 1, 1, 0, 0, 0)
.unwrap()
.timestamp_millis();
assert_eq!(EPOCH, expected_epoch);
}
#[test]
fn conversion_to_and_from_unix_timestamp() {
let unix_ts = 1704067200123; let custom_ts = CustomEpochTimestamp::from_unix_timestamp(unix_ts).unwrap();
assert_eq!(custom_ts.millis(), 123);
let back_to_unix = CustomEpochTimestamp::to_unix_timestamp(custom_ts.millis());
assert_eq!(back_to_unix, unix_ts);
}
}