use core::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ClockStatus(pub u8);
impl ClockStatus {
pub const NOT_SPECIFIED: Self = Self(0xFF);
#[must_use]
pub const fn invalid(self) -> bool {
self.0 & 0x01 != 0
}
#[must_use]
pub const fn doubtful(self) -> bool {
self.0 & 0x02 != 0
}
#[must_use]
pub const fn different_clock_base(self) -> bool {
self.0 & 0x04 != 0
}
#[must_use]
pub const fn invalid_clock_status(self) -> bool {
self.0 & 0x08 != 0
}
#[must_use]
pub const fn daylight_saving_active(self) -> bool {
self.0 & 0x80 != 0
}
#[must_use]
pub const fn is_not_specified(self) -> bool {
self.0 == 0xFF
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DateTime {
pub year: u16,
pub month: u8,
pub day_of_month: u8,
pub day_of_week: u8,
pub hour: u8,
pub minute: u8,
pub second: u8,
pub hundredths: u8,
pub deviation: i16,
pub status: ClockStatus,
}
impl DateTime {
pub const WILDCARD: Self = Self {
year: 0xFFFF,
month: 0xFF,
day_of_month: 0xFF,
day_of_week: 0xFF,
hour: 0xFF,
minute: 0xFF,
second: 0xFF,
hundredths: 0xFF,
deviation: DEVIATION_NOT_SPECIFIED,
status: ClockStatus::NOT_SPECIFIED,
};
#[must_use]
pub const fn from_bytes(b: [u8; 12]) -> Self {
Self {
year: u16::from_be_bytes([b[0], b[1]]),
month: b[2],
day_of_month: b[3],
day_of_week: b[4],
hour: b[5],
minute: b[6],
second: b[7],
hundredths: b[8],
deviation: i16::from_be_bytes([b[9], b[10]]),
status: ClockStatus(b[11]),
}
}
#[must_use]
pub const fn to_bytes(self) -> [u8; 12] {
let y = self.year.to_be_bytes();
let d = self.deviation.to_be_bytes();
[
y[0],
y[1],
self.month,
self.day_of_month,
self.day_of_week,
self.hour,
self.minute,
self.second,
self.hundredths,
d[0],
d[1],
self.status.0,
]
}
#[must_use]
pub const fn has_wildcard(&self) -> bool {
self.year == 0xFFFF
|| self.month >= 0xFD
|| self.day_of_month >= 0xFD
|| self.hour == 0xFF
|| self.minute == 0xFF
|| self.second == 0xFF
}
#[must_use]
pub const fn utc_offset_minutes(&self) -> Option<i16> {
if self.deviation == DEVIATION_NOT_SPECIFIED { None } else { Some(-self.deviation) }
}
#[must_use]
pub fn to_unix_seconds(&self) -> Option<i64> {
if self.has_wildcard() {
return None;
}
let offset = self.utc_offset_minutes()?;
if self.month == 0 || self.month > 12 || self.day_of_month == 0 {
return None;
}
if self.day_of_month > days_in_month(self.year, self.month) {
return None;
}
if self.hour > 23 || self.minute > 59 || self.second > 59 {
return None;
}
let days = days_from_civil(self.year, self.month, self.day_of_month);
let secs = i64::from(days) * 86_400
+ i64::from(self.hour) * 3600
+ i64::from(self.minute) * 60
+ i64::from(self.second);
Some(secs - i64::from(offset) * 60)
}
#[must_use]
pub const fn from_civil(
year: u16,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
utc_offset_minutes: i16,
) -> Option<Self> {
if year == 0xFFFF
|| month == 0
|| day == 0
|| day > days_in_month(year, month)
|| hour > 23
|| minute > 59
|| second > 59
|| utc_offset_minutes == i16::MIN
{
return None;
}
Some(Self {
year,
month,
day_of_month: day,
day_of_week: day_of_week(year, month, day),
hour,
minute,
second,
hundredths: 0,
deviation: -utc_offset_minutes,
status: ClockStatus(0),
})
}
#[must_use]
pub const fn from_unix_seconds(secs: i64) -> Option<Self> {
if secs < Self::MIN_UNIX_SECONDS || secs > Self::MAX_UNIX_SECONDS {
return None;
}
let days = secs.div_euclid(86_400);
let rem = secs.rem_euclid(86_400);
let (year, month, day) = civil_from_days(days as i32);
let year = year as u16;
Some(Self {
year,
month,
day_of_month: day,
day_of_week: day_of_week(year, month, day),
hour: (rem / 3600) as u8,
minute: (rem / 60 % 60) as u8,
second: (rem % 60) as u8,
hundredths: 0,
deviation: 0,
status: ClockStatus(0),
})
}
pub const MIN_UNIX_SECONDS: i64 = -62_167_219_200;
pub const MAX_UNIX_SECONDS: i64 = 2_005_917_609_599;
}
pub const DEVIATION_NOT_SPECIFIED: i16 = -0x8000;
impl fmt::Display for DateTime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let n = wildcard_or;
if self.year == 0xFFFF {
f.write_str("****")?;
} else {
write!(f, "{:04}", self.year)?;
}
f.write_str("-")?;
n(self.month, 2, f)?;
f.write_str("-")?;
n(self.day_of_month, 2, f)?;
f.write_str("T")?;
n(self.hour, 2, f)?;
f.write_str(":")?;
n(self.minute, 2, f)?;
f.write_str(":")?;
n(self.second, 2, f)?;
match self.utc_offset_minutes() {
None => Ok(()),
Some(0) => f.write_str("Z"),
Some(m) => {
let sign = if m < 0 { '-' } else { '+' };
let a = m.unsigned_abs();
write!(f, "{sign}{:02}:{:02}", a / 60, a % 60)
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Date {
pub year: u16,
pub month: u8,
pub day_of_month: u8,
pub day_of_week: u8,
}
impl Date {
#[must_use]
pub const fn from_bytes(b: [u8; 5]) -> Self {
Self { year: u16::from_be_bytes([b[0], b[1]]), month: b[2], day_of_month: b[3], day_of_week: b[4] }
}
#[must_use]
pub const fn to_bytes(self) -> [u8; 5] {
let y = self.year.to_be_bytes();
[y[0], y[1], self.month, self.day_of_month, self.day_of_week]
}
}
impl fmt::Display for Date {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.year == 0xFFFF {
f.write_str("****")?;
} else {
write!(f, "{:04}", self.year)?;
}
f.write_str("-")?;
wildcard_or(self.month, 2, f)?;
f.write_str("-")?;
wildcard_or(self.day_of_month, 2, f)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Time {
pub hour: u8,
pub minute: u8,
pub second: u8,
pub hundredths: u8,
}
impl Time {
#[must_use]
pub const fn from_bytes(b: [u8; 4]) -> Self {
Self { hour: b[0], minute: b[1], second: b[2], hundredths: b[3] }
}
#[must_use]
pub const fn to_bytes(self) -> [u8; 4] {
[self.hour, self.minute, self.second, self.hundredths]
}
}
impl fmt::Display for Time {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
wildcard_or(self.hour, 2, f)?;
f.write_str(":")?;
wildcard_or(self.minute, 2, f)?;
f.write_str(":")?;
wildcard_or(self.second, 2, f)
}
}
fn wildcard_or(v: u8, width: usize, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if v >= 0xFD {
for _ in 0..width {
f.write_str("*")?;
}
Ok(())
} else {
write!(f, "{v:0width$}")
}
}
const fn days_in_month(year: u16, month: u8) -> u8 {
match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 => {
let y = year as u32;
if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) { 29 } else { 28 }
}
_ => 0,
}
}
const fn days_from_civil(year: u16, m: u8, d: u8) -> i32 {
let m = m as i32;
let d = d as i32;
let y = year as i32 - if m <= 2 { 1 } else { 0 };
let era = if y >= 0 { y } else { y - 399 } / 400;
let yoe = y - era * 400;
let mp = (m + 9) % 12;
let doy = (153 * mp + 2) / 5 + d - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe - 719_468
}
const fn civil_from_days(days: i32) -> (i32, u8, u8) {
let z = days + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = (doy - (153 * mp + 2) / 5 + 1) as u8;
let month = if mp < 10 { mp + 3 } else { mp - 9 } as u8;
let year = yoe + era * 400 + if month <= 2 { 1 } else { 0 };
(year, month, day)
}
const fn day_of_week(y: u16, m: u8, d: u8) -> u8 {
((days_from_civil(y, m, d) + 3).rem_euclid(7) + 1) as u8
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn wire_form_round_trips_including_wildcards() {
let raw = [0x07, 0xE9, 0x0C, 0x1F, 0xFF, 0x17, 0x3B, 0x3B, 0xFF, 0x00, 0x3C, 0x00];
let dt = DateTime::from_bytes(raw);
assert_eq!(dt.year, 2025);
assert_eq!(dt.month, 12);
assert_eq!(dt.day_of_month, 31);
assert_eq!(dt.hour, 23);
assert_eq!(dt.deviation, 60);
assert_eq!(dt.to_bytes(), raw);
}
#[test]
fn unix_seconds_become_a_concrete_utc_clock() {
type Civil = (u16, u8, u8, u8, u8, u8, u8);
let cases: [(i64, Civil); 5] = [
(0, (1970, 1, 1, 4, 0, 0, 0)),
(-1, (1969, 12, 31, 3, 23, 59, 59)),
(1_709_164_800, (2024, 2, 29, 4, 0, 0, 0)),
(DateTime::MIN_UNIX_SECONDS, (0, 1, 1, 6, 0, 0, 0)),
(DateTime::MAX_UNIX_SECONDS, (65534, 12, 31, 1, 23, 59, 59)),
];
for (secs, (y, mo, d, wd, h, mi, s)) in cases {
let dt = DateTime::from_unix_seconds(secs).unwrap();
assert_eq!(
(dt.year, dt.month, dt.day_of_month, dt.day_of_week, dt.hour, dt.minute, dt.second),
(y, mo, d, wd, h, mi, s),
"{secs}"
);
assert_eq!((dt.hundredths, dt.deviation, dt.status), (0, 0, ClockStatus(0)));
assert!(!dt.has_wildcard());
assert_eq!(dt.to_unix_seconds(), Some(secs));
}
assert_eq!(DateTime::from_unix_seconds(DateTime::MIN_UNIX_SECONDS - 1), None);
assert_eq!(
DateTime::from_unix_seconds(DateTime::MAX_UNIX_SECONDS + 1),
None,
"year 65535 is the wildcard"
);
assert_eq!(DateTime::from_unix_seconds(i64::MIN), None);
assert_eq!(DateTime::from_unix_seconds(i64::MAX), None);
}
#[test]
fn from_unix_seconds_agrees_with_from_civil_every_day_for_a_cycle() {
let mut secs = DateTime::from_civil(1800, 1, 1, 13, 14, 15, 0).unwrap().to_unix_seconds().unwrap();
for _ in 0..146_097 {
let dt = DateTime::from_unix_seconds(secs).unwrap();
let civil =
DateTime::from_civil(dt.year, dt.month, dt.day_of_month, dt.hour, dt.minute, dt.second, 0);
assert_eq!(civil, Some(dt));
assert_eq!(dt.to_unix_seconds(), Some(secs));
secs += 86_400;
}
}
#[test]
fn from_civil_refuses_what_names_no_instant() {
let ok = |y, mo, d, h, mi, s, off| DateTime::from_civil(y, mo, d, h, mi, s, off).is_some();
assert!(ok(2024, 2, 29, 23, 59, 59, 0));
assert!(!ok(2025, 2, 29, 0, 0, 0, 0), "2025 is not a leap year");
assert!(!ok(2025, 2, 31, 0, 0, 0, 0));
assert!(!ok(2025, 13, 1, 0, 0, 0, 0));
assert!(!ok(2025, 0, 1, 0, 0, 0, 0));
assert!(!ok(2025, 1, 0, 0, 0, 0, 0));
assert!(!ok(2025, 1, 1, 24, 0, 0, 0));
assert!(!ok(2025, 1, 1, 0, 60, 0, 0));
assert!(!ok(2016, 12, 31, 23, 59, 60, 0), "a leap second has no Unix value");
assert!(!ok(0xFFFF, 1, 1, 0, 0, 0, 0), "the wildcard year");
assert!(!ok(2025, 1, 1, 0, 0, 0, i16::MIN), "its deviation is the not-specified marker");
assert!(ok(2025, 1, 1, 0, 0, 0, i16::MAX));
}
#[test]
fn deviation_is_minutes_behind_utc() {
let dt = DateTime::from_civil(2025, 1, 15, 12, 0, 0, 60).unwrap();
assert_eq!(dt.deviation, -60);
assert_eq!(dt.utc_offset_minutes(), Some(60));
assert_eq!(dt.to_unix_seconds(), Some(1_736_938_800));
}
#[test]
fn an_absent_deviation_is_not_utc() {
let mut dt = DateTime::from_civil(2025, 1, 15, 12, 0, 0, 0).unwrap();
dt.deviation = DEVIATION_NOT_SPECIFIED;
assert_eq!(dt.utc_offset_minutes(), None);
assert_eq!(dt.to_unix_seconds(), None, "must refuse rather than assume UTC");
}
#[test]
fn a_wildcard_is_not_a_timestamp() {
assert!(DateTime::WILDCARD.has_wildcard());
assert_eq!(DateTime::WILDCARD.to_unix_seconds(), None);
let mut last_day = DateTime::from_civil(2025, 6, 1, 6, 0, 0, 120).unwrap();
last_day.day_of_month = 0xFE; assert!(last_day.has_wildcard());
assert_eq!(last_day.to_unix_seconds(), None);
}
#[test]
fn epoch_and_a_leap_day() {
let epoch = DateTime::from_civil(1970, 1, 1, 0, 0, 0, 0).unwrap();
assert_eq!(epoch.to_unix_seconds(), Some(0));
assert_eq!(epoch.day_of_week, 4, "1970-01-01 was a Thursday");
let leap = DateTime::from_civil(2024, 2, 29, 0, 0, 0, 0).unwrap();
assert_eq!(leap.to_unix_seconds(), Some(1_709_164_800));
assert_eq!(leap.day_of_week, 4, "2024-02-29 was a Thursday");
}
#[test]
fn out_of_range_fields_are_refused() {
let mut dt = DateTime::from_civil(2025, 1, 1, 0, 0, 0, 0).unwrap();
dt.month = 13;
assert_eq!(dt.to_unix_seconds(), None);
let mut dt = DateTime::from_civil(2025, 1, 1, 0, 0, 0, 0).unwrap();
dt.hour = 24;
assert_eq!(dt.to_unix_seconds(), None);
}
#[test]
fn a_day_that_does_not_exist_in_its_month_is_refused() {
let mut dt = DateTime::from_civil(2025, 2, 28, 12, 0, 0, 0).unwrap();
assert!(dt.to_unix_seconds().is_some());
dt.day_of_month = 29;
assert_eq!(dt.to_unix_seconds(), None, "2025 is not a leap year");
let mut leap = DateTime::from_civil(2024, 2, 28, 12, 0, 0, 0).unwrap();
leap.day_of_month = 29;
assert!(leap.to_unix_seconds().is_some(), "2024 is");
let mut april = DateTime::from_civil(2025, 4, 30, 12, 0, 0, 0).unwrap();
assert!(april.to_unix_seconds().is_some());
april.day_of_month = 31;
assert_eq!(april.to_unix_seconds(), None, "April has thirty days");
let mut y1900 = DateTime::from_civil(1900, 2, 28, 0, 0, 0, 0).unwrap();
y1900.day_of_month = 29;
assert_eq!(y1900.to_unix_seconds(), None);
let mut y2000 = DateTime::from_civil(2000, 2, 28, 0, 0, 0, 0).unwrap();
y2000.day_of_month = 29;
assert!(y2000.to_unix_seconds().is_some());
}
#[test]
fn a_leap_second_has_no_unix_timestamp() {
let mut dt = DateTime::from_civil(2016, 12, 31, 23, 59, 59, 0).unwrap();
assert!(dt.to_unix_seconds().is_some());
dt.second = 60;
assert_eq!(dt.to_unix_seconds(), None, "23:59:60 is not a Unix second");
}
#[test]
fn every_type_prints_a_wildcard_the_same_way() {
assert_eq!(
alloc::format!("{}", Time { hour: 0xFF, minute: 30, second: 0xFF, hundredths: 0xFF }),
"**:30:**"
);
assert_eq!(
alloc::format!("{}", Date { year: 0xFFFF, month: 0xFF, day_of_month: 0xFE, day_of_week: 0xFF }),
"****-**-**",
"the last day of any month is a pattern, not the 254th"
);
assert_eq!(alloc::format!("{}", DateTime::WILDCARD), "****-**-**T**:**:**");
}
#[test]
fn clock_status_bits() {
let s = ClockStatus(0x81);
assert!(s.invalid());
assert!(s.daylight_saving_active());
assert!(!s.doubtful());
assert!(ClockStatus::NOT_SPECIFIED.is_not_specified());
}
}