use crate::time::DosTimestamp;
pub const UTC_OFFSET_VALID: u8 = 0x80;
pub const UTC_OFFSET: u8 = UTC_OFFSET_VALID;
const MINUTES_PER_UNIT: i32 = 15;
const OFFSET_UNITS: u8 = 0x7F;
#[must_use]
pub const fn pack_timestamp(stamp: DosTimestamp) -> u32 {
((stamp.date as u32) << 16) | stamp.time as u32
}
#[must_use]
pub const fn unpack_timestamp(field: u32, tenth: u8) -> DosTimestamp {
DosTimestamp {
date: (field >> 16) as u16,
time: field as u16,
tenth,
}
}
#[must_use]
pub const fn utc_offset_minutes(byte: u8) -> Option<i32> {
if byte & UTC_OFFSET_VALID == 0 {
return None;
}
let units = ((byte & OFFSET_UNITS) << 1) as i8 >> 1;
Some(units as i32 * MINUTES_PER_UNIT)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::time::Timestamp;
#[test]
fn the_two_words_pack_into_one_field_with_the_date_above_the_time() {
let stamp = DosTimestamp::encode(Timestamp::from_secs(1_426_325_212)).expect("in range");
let field = pack_timestamp(stamp);
assert_eq!((field >> 16) as u16, stamp.date);
assert_eq!(field as u16, stamp.time);
assert_ne!(stamp.date, stamp.time, "the halves must be distinguishable");
assert_eq!(unpack_timestamp(field, stamp.tenth), stamp);
assert_eq!(
unpack_timestamp(field, 0).tenth,
0,
"a field with no hundredths byte is granular to two seconds"
);
}
#[test]
fn the_offset_byte_says_utc_by_recording_a_zero_offset_rather_than_by_being_zero() {
assert_eq!(utc_offset_minutes(UTC_OFFSET), Some(0));
assert_eq!(utc_offset_minutes(0), None);
}
#[test]
fn an_offset_is_a_signed_count_of_quarter_hours() {
for (byte, minutes, what) in [
(UTC_OFFSET_VALID, 0, "UTC"),
(UTC_OFFSET_VALID | 0x04, 60, "one hour east"),
(UTC_OFFSET_VALID | 0x7C, -60, "one hour west"),
(UTC_OFFSET_VALID | 0x16, 330, "India, at half past five"),
(
UTC_OFFSET_VALID | 0x2F,
705,
"Chatham Island, at a quarter to twelve",
),
(
UTC_OFFSET_VALID | 0x40,
-960,
"the furthest west the field reaches",
),
(
UTC_OFFSET_VALID | 0x3F,
945,
"the furthest east the field reaches",
),
] {
assert_eq!(utc_offset_minutes(byte), Some(minutes), "{what}");
}
assert_eq!(utc_offset_minutes(0x7F), None);
}
}