#![cfg_attr(
any(feature = "fat", feature = "exfat"),
doc = "\n # The encoding two families inherited\n\n [`DosTimestamp`] is the exception, \
and it is here for the reason a conversion normally is not: FAT and exFAT do not each define \
a date format, they carry the same one. The same two packed words, the same 1980 epoch, the \
same two-second granularity, the same companion field of hundredths. What differs is where \
each format puts those words in a directory entry and what it stores beside them, and that \
part stays in each family's own on-disk layer.\n"
)]
use core::fmt;
const SECS_PER_DAY: i64 = 86_400;
const DAYS_PER_ERA: i64 = 146_097;
const DAYS_EPOCH_TO_SHIFTED: i64 = 719_468;
#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
pub struct Timestamp {
pub secs: i64,
pub nanos: u32,
}
impl Timestamp {
pub const NANOS_PER_SEC: u32 = 1_000_000_000;
#[cfg(any(feature = "ext", feature = "btrfs", feature = "apfs"))]
pub(crate) const fn has_proper_fraction(self) -> bool {
self.nanos < Self::NANOS_PER_SEC
}
#[must_use]
pub const fn from_secs(secs: i64) -> Self {
Self { secs, nanos: 0 }
}
#[must_use]
pub const fn civil(self) -> Civil {
Civil::at_secs(self.secs)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct Civil {
pub year: i64,
pub month: u32,
pub day: u32,
pub hour: u32,
pub minute: u32,
pub second: u32,
}
impl Civil {
#[must_use]
pub const fn at_secs(secs: i64) -> Self {
let days = secs.div_euclid(SECS_PER_DAY);
let rem = secs.rem_euclid(SECS_PER_DAY);
let shifted = days + DAYS_EPOCH_TO_SHIFTED;
let era = shifted.div_euclid(DAYS_PER_ERA);
let day_of_era = shifted.rem_euclid(DAYS_PER_ERA);
let year_of_era =
(day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let shifted_month = (5 * day_of_year + 2) / 153;
let day = (day_of_year - (153 * shifted_month + 2) / 5 + 1) as u32;
let month = (if shifted_month < 10 {
shifted_month + 3
} else {
shifted_month - 9
}) as u32;
let year = year_of_era + era * 400 + (month <= 2) as i64;
Self {
year,
month,
day,
hour: (rem / 3600) as u32,
minute: (rem / 60 % 60) as u32,
second: (rem % 60) as u32,
}
}
#[must_use]
pub const fn to_secs(self) -> i64 {
let year = self.year - (self.month <= 2) as i64;
let era = year.div_euclid(400);
let year_of_era = year.rem_euclid(400);
let shifted_month = if self.month > 2 {
self.month - 3
} else {
self.month + 9
};
let day_of_year = (153 * shifted_month as i64 + 2) / 5 + self.day as i64 - 1;
let day_of_era = 365 * year_of_era + year_of_era / 4 - year_of_era / 100 + day_of_year;
let days = era * DAYS_PER_ERA + day_of_era - DAYS_EPOCH_TO_SHIFTED;
days * SECS_PER_DAY + self.hour as i64 * 3600 + self.minute as i64 * 60 + self.second as i64
}
}
impl fmt::Display for Civil {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self {
year,
month,
day,
hour,
minute,
second,
} = *self;
write!(
f,
"{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z"
)
}
}
#[cfg(any(feature = "fat", feature = "exfat"))]
const SECONDS_PER_UNIT: u32 = 2;
#[cfg(any(feature = "fat", feature = "exfat"))]
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub struct DosTimestamp {
pub date: u16,
pub time: u16,
pub tenth: u8,
}
#[cfg(any(feature = "fat", feature = "exfat"))]
impl DosTimestamp {
pub const SECS_MIN: i64 = 315_532_800;
pub const SECS_MAX: i64 = 4_354_819_198;
pub const MAX_TENTH: u8 = 199;
#[must_use]
pub fn encode(time: Timestamp) -> Option<Self> {
if !Self::represents(time) {
return None;
}
let c = Timestamp::from_secs(time.secs).civil();
let year = (c.year - 1980) as u16;
let date = (year << 9) | ((c.month as u16) << 5) | c.day as u16;
let time_word = ((c.hour as u16) << 11) | ((c.minute as u16) << 5) | (c.second / 2) as u16;
let hundredths = (c.second % 2) * 100 + (time.nanos / 10_000_000).min(99);
Some(Self {
date,
time: time_word,
tenth: hundredths.min(Self::MAX_TENTH as u32) as u8,
})
}
const fn civil(self) -> Civil {
Civil {
year: 1980 + (self.date >> 9) as i64,
month: ((self.date >> 5) & 0xF) as u32,
day: (self.date & 0x1F) as u32,
hour: (self.time >> 11) as u32,
minute: ((self.time >> 5) & 0x3F) as u32,
second: (self.time & 0x1F) as u32 * SECONDS_PER_UNIT,
}
}
#[must_use]
pub const fn decode(self) -> Timestamp {
Timestamp {
secs: self.civil().to_secs() + self.tenth as i64 / 100,
nanos: (self.tenth as u32 % 100) * 10_000_000,
}
}
#[must_use]
pub const fn is_well_formed(self) -> bool {
if self.tenth > Self::MAX_TENTH {
return false;
}
let stated = self.civil();
let reached = Civil::at_secs(stated.to_secs());
stated.year == reached.year
&& stated.month == reached.month
&& stated.day == reached.day
&& stated.hour == reached.hour
&& stated.minute == reached.minute
&& stated.second == reached.second
}
#[must_use]
pub const fn represents(time: Timestamp) -> bool {
time.secs >= Self::SECS_MIN && time.secs <= Self::SECS_MAX
}
}
#[cfg(test)]
mod tests {
use super::{Civil, Timestamp};
#[test]
fn an_instant_is_its_seconds_and_fraction() {
assert_eq!(
Timestamp::from_secs(1_700_000_000),
Timestamp {
secs: 1_700_000_000,
nanos: 0
}
);
assert_eq!(Timestamp::from_secs(-1).secs, -1);
assert_eq!(Timestamp::default(), Timestamp::from_secs(0));
}
#[test]
fn a_civil_reading_renders_as_utc_without_a_calendar_to_consult() {
let at = |secs| Timestamp::from_secs(secs).civil().to_string();
assert_eq!(at(0), "1970-01-01T00:00:00Z");
assert_eq!(at(1_700_000_000), "2023-11-14T22:13:20Z");
assert_eq!(at(951_782_400), "2000-02-29T00:00:00Z");
assert_eq!(at(-1), "1969-12-31T23:59:59Z");
assert_eq!(at(-2_147_483_648), "1901-12-13T20:45:52Z");
assert_eq!(at(15_032_385_535), "2446-05-10T22:38:55Z");
assert_eq!(at(315_532_800), "1980-01-01T00:00:00Z");
assert_eq!(at(4_354_819_198), "2107-12-31T23:59:58Z");
}
#[test]
fn the_conversion_agrees_with_itself_in_both_directions() {
for day in -200_000..200_000i64 {
let c = Civil::at_secs(day * 86_400);
assert_eq!(
c.to_secs() / 86_400,
day,
"day {day} converts to {c} and back to something else"
);
assert!((1..=12).contains(&c.month), "day {day}: month {}", c.month);
assert!((1..=31).contains(&c.day), "day {day}: day {}", c.day);
}
}
#[test]
fn a_date_no_calendar_has_yields_the_instant_the_arithmetic_reaches() {
let odd = Civil {
year: 2015,
month: 2,
day: 31,
hour: 0,
minute: 0,
second: 0,
};
let march = Civil {
year: 2015,
month: 3,
day: 3,
hour: 0,
minute: 0,
second: 0,
};
assert_eq!(odd.to_secs(), march.to_secs());
}
}
#[cfg(all(test, any(feature = "fat", feature = "exfat")))]
mod dos_tests {
use super::*;
struct Known {
what: &'static str,
secs: i64,
nanos: u32,
calendar: (u16, u16, u16, u16, u16, u16),
tenth: u8,
}
fn packed(calendar: (u16, u16, u16, u16, u16, u16)) -> (u16, u16) {
let (year, month, day, hour, minute, second) = calendar;
let date = ((year - 1980) << 9) | (month << 5) | day;
let time = (hour << 11) | (minute << 5) | (second / 2);
(date, time)
}
const KNOWN: &[Known] = &[
Known {
what: "the first instant the encoding represents",
secs: DosTimestamp::SECS_MIN,
nanos: 0,
calendar: (1980, 1, 1, 0, 0, 0),
tenth: 0,
},
Known {
what: "the last instant the encoding represents",
secs: DosTimestamp::SECS_MAX,
nanos: 0,
calendar: (2107, 12, 31, 23, 59, 58),
tenth: 0,
},
Known {
what: "the baseline formatter's invariant instant",
secs: 1_426_325_213,
nanos: 0,
calendar: (2015, 3, 14, 9, 26, 53),
tenth: 100,
},
Known {
what: "a leap day",
secs: 951_827_696,
nanos: 0,
calendar: (2000, 2, 29, 12, 34, 56),
tenth: 0,
},
Known {
what: "a fraction inside an even second",
secs: 1_426_325_212,
nanos: 370_000_000,
calendar: (2015, 3, 14, 9, 26, 52),
tenth: 37,
},
];
#[test]
fn every_known_instant_encodes_to_the_words_a_calendar_gives() {
for k in KNOWN {
let (date, time) = packed(k.calendar);
let encoded = DosTimestamp::encode(Timestamp {
secs: k.secs,
nanos: k.nanos,
})
.unwrap_or_else(|| panic!("{}: refused an instant in range", k.what));
assert_eq!(encoded.date, date, "{}: date word", k.what);
assert_eq!(encoded.time, time, "{}: time word", k.what);
assert_eq!(encoded.tenth, k.tenth, "{}: hundredths", k.what);
}
}
#[test]
fn decoding_recovers_the_instant_the_fields_can_hold() {
for k in KNOWN {
let (date, time) = packed(k.calendar);
let decoded = DosTimestamp {
date,
time,
tenth: k.tenth,
}
.decode();
let expected_nanos = (k.nanos / 10_000_000) * 10_000_000;
assert_eq!(decoded.secs, k.secs, "{}: seconds", k.what);
assert_eq!(decoded.nanos, expected_nanos, "{}: fraction", k.what);
}
}
#[test]
fn an_instant_outside_the_range_is_refused_rather_than_wrapped() {
let encode = |secs| DosTimestamp::encode(Timestamp::from_secs(secs));
assert!(encode(DosTimestamp::SECS_MIN - 1).is_none());
assert!(encode(DosTimestamp::SECS_MAX + 1).is_none());
assert!(encode(0).is_none());
assert!(encode(-1).is_none());
assert!(encode(DosTimestamp::SECS_MIN).is_some());
assert!(encode(DosTimestamp::SECS_MAX).is_some());
assert!(DosTimestamp::represents(Timestamp::from_secs(
DosTimestamp::SECS_MIN
)));
assert!(!DosTimestamp::represents(Timestamp::from_secs(
DosTimestamp::SECS_MIN - 1
)));
}
#[test]
fn the_round_trip_holds_across_the_whole_representable_range() {
const STRIDE: i64 = 100_003;
let mut secs = DosTimestamp::SECS_MIN;
let mut checked = 0u32;
while secs <= DosTimestamp::SECS_MAX {
let encoded = DosTimestamp::encode(Timestamp::from_secs(secs)).expect("in range");
assert_eq!(
encoded.decode().secs,
secs,
"the instant did not survive the round trip"
);
checked += 1;
secs += STRIDE;
}
assert!(
checked > 40_000,
"the sweep only checked {checked} instants"
);
}
#[test]
fn the_conversion_is_utc_and_carries_no_zone() {
let midnight =
DosTimestamp::encode(Timestamp::from_secs(DosTimestamp::SECS_MIN)).expect("in range");
assert_eq!(midnight.time, 0);
assert_eq!(midnight.date & 0x1F, 1, "the day must be the first");
assert_eq!((midnight.date >> 5) & 0xF, 1, "the month must be January");
}
#[test]
fn a_date_no_calendar_has_is_reported_rather_than_refused() {
let odd = DosTimestamp {
date: (35 << 9) | (2 << 5) | 31,
time: 0,
tenth: 0,
}
.decode();
assert_eq!(
odd.secs,
DosTimestamp {
date: (35 << 9) | (3 << 5) | 3,
time: 0,
tenth: 0,
}
.decode()
.secs
);
}
#[test]
fn a_field_outside_the_range_the_encoding_defines_is_what_the_judge_answers_for() {
let date = |month: u16, day: u16| (35 << 9) | (month << 5) | day;
for (stamp, what) in [
(
DosTimestamp {
date: date(0, 0),
time: 0,
tenth: 0,
},
"month 0 and day 0, which is what a field of zero bytes spells",
),
(
DosTimestamp {
date: date(2, 31),
time: 0,
tenth: 0,
},
"day 31 of February",
),
(
DosTimestamp {
date: date(13, 1),
time: 0,
tenth: 0,
},
"a thirteenth month",
),
(
DosTimestamp {
date: date(3, 14),
time: 24 << 11,
tenth: 0,
},
"a twenty-fifth hour",
),
(
DosTimestamp {
date: date(3, 14),
time: 60 << 5,
tenth: 0,
},
"a sixtieth minute",
),
(
DosTimestamp {
date: date(3, 14),
time: 30,
tenth: 0,
},
"a seconds field counting past fifty-eight",
),
(
DosTimestamp {
date: date(3, 14),
time: 0,
tenth: 200,
},
"a hundredths byte past what the field means",
),
] {
assert!(!stamp.is_well_formed(), "{what} is a field out of range");
}
let leap_day = |year: u16| DosTimestamp {
date: ((year - 1980) << 9) | (2 << 5) | 29,
time: 0,
tenth: 0,
};
assert!(leap_day(2000).is_well_formed(), "2000 is a leap year");
assert!(!leap_day(2015).is_well_formed(), "2015 is not");
assert!(!leap_day(2100).is_well_formed(), "nor is 2100");
for secs in [
DosTimestamp::SECS_MIN,
DosTimestamp::SECS_MAX,
951_827_696,
1_426_325_213,
] {
let stamp = DosTimestamp::encode(Timestamp::from_secs(secs)).expect("in range");
assert!(
stamp.is_well_formed(),
"{secs} encodes to a field it judges"
);
}
assert_eq!(DosTimestamp::MAX_TENTH, 199);
assert!(
DosTimestamp {
date: date(3, 14),
time: 0,
tenth: DosTimestamp::MAX_TENTH,
}
.is_well_formed()
);
}
}