use core::fmt;
use std::error::Error;
use std::time::{Duration, SystemTime};
use crate::header::{HeaderError, HeaderValue};
pub const TIMESTAMP_WIDTH: usize = 32;
pub const MIN_YEAR: i64 = 1;
pub const MAX_YEAR: i64 = 9_999;
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct SignifyTimestamp {
text: String,
created: u64,
}
impl SignifyTimestamp {
pub fn at(moment: SystemTime) -> Result<Self, TimestampError> {
let since_epoch = moment
.duration_since(SystemTime::UNIX_EPOCH)
.map_err(|_| TimestampError::BeforeEpoch)?;
Self::from_unix(since_epoch)
}
pub fn from_unix(since_epoch: Duration) -> Result<Self, TimestampError> {
Self::render(since_epoch, since_epoch.subsec_millis().saturating_mul(1_000))
}
pub fn from_unix_micros(since_epoch: Duration) -> Result<Self, TimestampError> {
Self::render(since_epoch, since_epoch.subsec_micros())
}
fn render(since_epoch: Duration, microseconds: u32) -> Result<Self, TimestampError> {
let created = since_epoch.as_secs();
let seconds = i64::try_from(created).map_err(|_| TimestampError::OutOfRange { year: i64::MAX })?;
let days = seconds.div_euclid(86_400);
let seconds_of_day = seconds.rem_euclid(86_400);
let (year, month, day) = civil_from_days(days).ok_or(TimestampError::OutOfRange { year: i64::MAX })?;
if !(MIN_YEAR..=MAX_YEAR).contains(&year) {
return Err(TimestampError::OutOfRange { year });
}
let hour = seconds_of_day / 3_600;
let minute = (seconds_of_day % 3_600) / 60;
let second = seconds_of_day % 60;
let text = format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{microseconds:06}+00:00");
Ok(Self { text, created })
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.text
}
#[must_use]
pub const fn created(&self) -> u64 {
self.created
}
pub fn to_header_value(&self) -> Result<HeaderValue, HeaderError> {
HeaderValue::new(&self.text)
}
}
impl fmt::Display for SignifyTimestamp {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.text)
}
}
fn civil_from_days(days: i64) -> Option<(i64, i64, i64)> {
let shifted = days.checked_add(719_468)?;
let era = shifted.div_euclid(146_097);
let day_of_era = shifted.rem_euclid(146_097);
let year_of_era = (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let year = year_of_era.checked_add(era.checked_mul(400)?)?;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let month_position = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * month_position + 2) / 5 + 1;
let month = month_position + if month_position < 10 { 3 } else { -9 };
Some((if month <= 2 { year.checked_add(1)? } else { year }, month, day))
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum TimestampError {
BeforeEpoch,
OutOfRange {
year: i64,
},
}
impl fmt::Display for TimestampError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::BeforeEpoch => formatter.write_str("a Signify timestamp may not precede the Unix epoch"),
Self::OutOfRange { year } => write!(
formatter,
"the year {year} is outside the range {MIN_YEAR} to {MAX_YEAR} the format can hold"
),
}
}
}
impl Error for TimestampError {}
#[cfg(test)]
mod tests {
use super::*;
use std::error::Error;
fn at(milliseconds: u64) -> Result<SignifyTimestamp, TimestampError> {
SignifyTimestamp::from_unix(Duration::from_millis(milliseconds))
}
#[test]
fn the_format_is_exact() -> Result<(), Box<dyn Error>> {
for (milliseconds, expected) in [
(1_700_000_000_123_u64, "2023-11-14T22:13:20.123000+00:00"),
(0, "1970-01-01T00:00:00.000000+00:00"),
(1_456_747_200_000, "2016-02-29T12:00:00.000000+00:00"),
(1_704_067_199_999, "2023-12-31T23:59:59.999000+00:00"),
(951_782_400_000, "2000-02-29T00:00:00.000000+00:00"),
] {
let stamp = at(milliseconds)?;
assert_eq!(stamp.as_str(), expected, "{milliseconds}");
assert_eq!(stamp.to_string(), expected);
assert_eq!(stamp.as_str().len(), TIMESTAMP_WIDTH);
}
Ok(())
}
#[test]
fn the_value_always_ends_in_three_zeros() -> Result<(), Box<dyn Error>> {
for milliseconds in [0_u64, 1, 999, 1_000, 1_700_000_000_001] {
let stamp = at(milliseconds)?;
assert!(stamp.as_str().ends_with("000+00:00"), "{}", stamp.as_str());
}
let coarse = SignifyTimestamp::from_unix(Duration::from_nanos(1_700_000_000_123_999_999))?;
assert_eq!(coarse.as_str(), "2023-11-14T22:13:20.123000+00:00");
Ok(())
}
#[test]
fn created_is_the_whole_second_of_the_same_reading() -> Result<(), Box<dyn Error>> {
let stamp = at(1_700_000_000_999)?;
assert_eq!(stamp.created(), 1_700_000_000);
assert_eq!(stamp.as_str(), "2023-11-14T22:13:20.999000+00:00");
assert_eq!(at(1_700_000_000_000)?.created(), stamp.created());
Ok(())
}
#[test]
fn a_moment_before_the_epoch_is_refused() {
let before = SystemTime::UNIX_EPOCH - Duration::from_secs(1);
assert_eq!(SignifyTimestamp::at(before), Err(TimestampError::BeforeEpoch));
assert!(SignifyTimestamp::at(SystemTime::UNIX_EPOCH).is_ok());
}
#[test]
fn a_year_the_format_cannot_hold_is_refused() {
const TOO_LATE_SECONDS: u64 = 253_402_300_800;
let too_late = Duration::from_secs(TOO_LATE_SECONDS);
assert!(matches!(
SignifyTimestamp::from_unix(too_late),
Err(TimestampError::OutOfRange { .. })
));
let latest = SignifyTimestamp::from_unix(Duration::from_secs(TOO_LATE_SECONDS - 1));
assert_eq!(
latest.map(|stamp| stamp.as_str().to_owned()).ok(),
Some("9999-12-31T23:59:59.000000+00:00".to_owned()),
);
assert!(matches!(
SignifyTimestamp::from_unix(Duration::MAX),
Err(TimestampError::OutOfRange { .. })
));
}
#[test]
fn the_value_is_always_a_usable_header_value() -> Result<(), Box<dyn Error>> {
for milliseconds in [0_u64, 1_700_000_000_123, 253_402_300_799_000] {
let stamp = at(milliseconds)?;
assert_eq!(stamp.to_header_value()?.as_str(), stamp.as_str());
}
Ok(())
}
#[test]
fn civil_days_round_trip_against_known_dates() {
for (days, expected) in [
(0_i64, (1970_i64, 1_i64, 1_i64)),
(-1, (1969, 12, 31)),
(11_017, (2000, 3, 1)),
(19_675, (2023, 11, 14)),
(-25_567, (1900, 1, 1)),
] {
assert_eq!(civil_from_days(days), Some(expected), "{days}");
}
}
#[test]
fn errors_carry_readable_text() {
for error in [TimestampError::BeforeEpoch, TimestampError::OutOfRange { year: 12_345 }] {
assert_ne!(error.to_string(), "");
assert!(error.source().is_none());
}
}
}