Skip to main content

sark_http/field/
date.rs

1use core::{
2    cell::Cell,
3    mem::{align_of, needs_drop, size_of},
4    ops,
5};
6
7use dope_runtime::civil::{Error as CivilError, Source as _, System};
8use o3::base::time;
9
10const DAYS: [[u8; 3]; 7] = [
11    *b"Thu", *b"Fri", *b"Sat", *b"Sun", *b"Mon", *b"Tue", *b"Wed",
12];
13const MONTHS: [[u8; 3]; 12] = [
14    *b"Jan", *b"Feb", *b"Mar", *b"Apr", *b"May", *b"Jun", *b"Jul", *b"Aug", *b"Sep", *b"Oct",
15    *b"Nov", *b"Dec",
16];
17const DIGITS: [[u8; 2]; 100] = digits();
18
19/// An IMF-fixdate field value with its wire length encoded in the type.
20#[derive(Clone, Copy, PartialEq, Eq)]
21#[repr(transparent)]
22pub struct Stamp([u8; 29]);
23
24impl Stamp {
25    pub const LEN: usize = 29;
26
27    /// Formats a Unix timestamp when its civil year fits IMF-fixdate.
28    pub const fn from_unix(unix: time::Unix<time::Seconds>) -> Option<Self> {
29        let seconds = unix.ticks();
30        let days = seconds / 86_400;
31        let day = days as i64;
32        let (year, month, date) = civil(day);
33        if year > 9_999 {
34            return None;
35        }
36
37        let daytime = seconds % 86_400;
38        let hour = (daytime / 3_600) as usize;
39        let minute = (daytime % 3_600 / 60) as usize;
40        let second = (daytime % 60) as usize;
41        let mut bytes = *b"Thu, 01 Jan 1970 00:00:00 GMT";
42        write(&mut bytes, 0, &DAYS[(days % 7) as usize]);
43        pair(&mut bytes, 5, date as usize);
44        // SAFETY: civil's nonnegative era-day calculation yields months 1 through 12.
45        let month = unsafe { &*MONTHS.as_ptr().add(month as usize - 1) };
46        write(&mut bytes, 8, month);
47        pair(&mut bytes, 12, year as usize / 100);
48        pair(&mut bytes, 14, year as usize % 100);
49        pair(&mut bytes, 17, hour);
50        pair(&mut bytes, 20, minute);
51        pair(&mut bytes, 23, second);
52        Some(Self(bytes))
53    }
54
55    pub const fn as_bytes(&self) -> &[u8; Self::LEN] {
56        &self.0
57    }
58}
59
60impl ops::Deref for Stamp {
61    type Target = [u8; Self::LEN];
62
63    fn deref(&self) -> &Self::Target {
64        &self.0
65    }
66}
67
68/// Driver-local civil clock for automatic HTTP/1 Date fields.
69pub struct Clock {
70    stamp: Cell<Stamp>,
71}
72
73impl Clock {
74    pub fn new() -> Result<Self, Error> {
75        Ok(Self {
76            stamp: Cell::new(Self::read()?),
77        })
78    }
79
80    pub fn load(&self) -> Stamp {
81        self.stamp.get()
82    }
83
84    /// Advances the cached stamp when civil time is representable. A failed
85    /// sample leaves the last valid HTTP date intact.
86    pub fn refresh(&self) {
87        if let Ok(stamp) = Self::read() {
88            self.stamp.set(stamp);
89        }
90    }
91
92    fn read() -> Result<Stamp, Error> {
93        let now = System::NEW.read()?;
94        Stamp::from_unix(now.floor_secs()).ok_or(Error::Range)
95    }
96}
97
98#[derive(Clone, Copy, Debug, PartialEq, Eq)]
99pub enum Error {
100    Civil(CivilError),
101    Range,
102}
103
104impl From<CivilError> for Error {
105    fn from(error: CivilError) -> Self {
106        Self::Civil(error)
107    }
108}
109
110const fn civil(day: i64) -> (i64, u8, u8) {
111    let shifted = day + 719_468;
112    let era = shifted / 146_097;
113    let era_day = shifted - era * 146_097;
114    let era_year = (era_day - era_day / 1_460 + era_day / 36_524 - era_day / 146_096) / 365;
115    let mut year = era_year + era * 400;
116    let year_day = era_day - (365 * era_year + era_year / 4 - era_year / 100);
117    let index = (5 * year_day + 2) / 153;
118    let date = year_day - (153 * index + 2) / 5 + 1;
119    let month = if index < 10 { index + 3 } else { index - 9 };
120    if month <= 2 {
121        year += 1;
122    }
123    (year, month as u8, date as u8)
124}
125
126const fn pair(bytes: &mut [u8; Stamp::LEN], at: usize, value: usize) {
127    // SAFETY: civil dates, daytime remainders, and the admitted four-digit year
128    // supply only values below 100. Each call selects a fixed two-byte output slot.
129    let pair = unsafe { &*DIGITS.as_ptr().add(value) };
130    write(bytes, at, pair);
131}
132
133const fn write<const N: usize>(bytes: &mut [u8; Stamp::LEN], at: usize, value: &[u8; N]) {
134    // SAFETY: this module's fixed two- and three-byte slots all end at or before
135    // byte 25 of the exclusively borrowed 29-byte output. Arrays of u8 align to 1.
136    unsafe { bytes.as_mut_ptr().add(at).cast::<[u8; N]>().write(*value) };
137}
138
139const fn digits() -> [[u8; 2]; 100] {
140    let mut table = [[0; 2]; 100];
141    let mut value = 0;
142    while value < 100 {
143        table[value] = [b'0' + (value / 10) as u8, b'0' + (value % 10) as u8];
144        value += 1;
145    }
146    table
147}
148
149const _: () = {
150    assert!(size_of::<Stamp>() == Stamp::LEN);
151    assert!(align_of::<Stamp>() == 1);
152    assert!(!needs_drop::<Stamp>());
153};