fusion-stack-laravel-rust 0.3.0

Fusion Stack for Laravel for Rust: versioned, documented JSON APIs with standard errors
Documentation
//! UTC dates for versions, deprecations and their headers, as Unix timestamps in seconds.

use std::time::{SystemTime, UNIX_EPOCH};

const WEEKDAYS: [&str; 7] = ["Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed"];
const MONTHS: [&str; 12] = [
    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];

/// Days since 1970-01-01 for a civil date (Howard Hinnant's algorithm).
const fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
    let year = if month <= 2 { year - 1 } else { year };
    let era = year.div_euclid(400);
    let yoe = year - era * 400;
    let doy = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146_097 + doe - 719_468
}

const fn civil_from_days(days: i64) -> (i64, i64, i64) {
    let z = days + 719_468;
    let era = z.div_euclid(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;
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
    (
        if month <= 2 {
            yoe + era * 400 + 1
        } else {
            yoe + era * 400
        },
        month,
        day,
    )
}

fn number(text: &str, digits: usize) -> Option<i64> {
    (text.len() == digits && text.bytes().all(|byte| byte.is_ascii_digit()))
        .then(|| text.parse().ok())
        .flatten()
}

/// Parses a strict `YYYY-MM-DD` date that exists, as days since the epoch.
pub(crate) fn parse_date(text: &str) -> Option<i64> {
    let mut parts = text.split('-');
    let (year, month, day) = (
        number(parts.next()?, 4)?,
        number(parts.next()?, 2)?,
        number(parts.next()?, 2)?,
    );
    if parts.next().is_some() || !(1..=12).contains(&month) || day < 1 {
        return None;
    }
    let days = days_from_civil(year, month, day);
    (civil_from_days(days) == (year, month, day)).then_some(days)
}

/// Parses `YYYY-MM-DD`, `YYYY-MM-DD HH:MM` or `YYYY-MM-DD HH:MM:SS` in UTC.
pub(crate) fn parse_moment(text: &str) -> Option<i64> {
    let (date, time) = match text.trim().split_once([' ', 'T']) {
        Some((date, time)) => (date, Some(time)),
        None => (text.trim(), None),
    };
    let mut seconds = parse_date(date)? * 86_400;
    if let Some(time) = time {
        let mut parts = time.split(':');
        let hours = number(parts.next()?, 2)?;
        let minutes = number(parts.next()?, 2)?;
        let secs = parts.next().map_or(Some(0), |part| number(part, 2))?;
        if parts.next().is_some() || hours > 23 || minutes > 59 || secs > 59 {
            return None;
        }
        seconds += hours * 3600 + minutes * 60 + secs;
    }
    Some(seconds)
}

fn split(timestamp: i64) -> ((i64, i64, i64), i64, i64, i64) {
    let days = timestamp.div_euclid(86_400);
    let rest = timestamp.rem_euclid(86_400);
    (
        civil_from_days(days),
        rest / 3600,
        rest % 3600 / 60,
        rest % 60,
    )
}

/// `2027-06-01`
pub(crate) fn date(timestamp: i64) -> String {
    let ((year, month, day), ..) = split(timestamp);
    format!("{year:04}-{month:02}-{day:02}")
}

/// `2027-05-04 15:00`
pub(crate) fn date_time(timestamp: i64) -> String {
    let (_, hours, minutes, _) = split(timestamp);
    format!("{} {hours:02}:{minutes:02}", date(timestamp))
}

/// `2027-05-04T15:00:00+00:00`, as PHP's `DATE_ATOM` writes it.
pub(crate) fn atom(timestamp: i64) -> String {
    let (_, hours, minutes, seconds) = split(timestamp);
    format!(
        "{}T{hours:02}:{minutes:02}:{seconds:02}+00:00",
        date(timestamp)
    )
}

/// `Tue, 01 Jun 2027 00:00:00 GMT`, an HTTP date.
pub(crate) fn http_date(timestamp: i64) -> String {
    let ((year, month, day), hours, minutes, seconds) = split(timestamp);
    let weekday =
        WEEKDAYS[usize::try_from(timestamp.div_euclid(86_400).rem_euclid(7)).unwrap_or(0)];
    let month = MONTHS[usize::try_from(month - 1).unwrap_or(0)];
    format!("{weekday}, {day:02} {month} {year:04} {hours:02}:{minutes:02}:{seconds:02} GMT")
}

/// The current time.
pub(crate) fn now() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |elapsed| {
            i64::try_from(elapsed.as_secs()).unwrap_or(i64::MAX)
        })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dates_round_trip_and_format_like_php() {
        let sunset = parse_moment("2027-06-01").unwrap();
        assert_eq!(http_date(sunset), "Tue, 01 Jun 2027 00:00:00 GMT");
        assert_eq!(parse_moment("2026-11-30").unwrap(), 1_795_996_800);
        let end = parse_moment("2027-05-04 15:00").unwrap();
        assert_eq!(date_time(end), "2027-05-04 15:00");
        assert_eq!(atom(end), "2027-05-04T15:00:00+00:00");
        assert_eq!(date(parse_moment("2024-02-29").unwrap()), "2024-02-29");
    }

    #[test]
    fn impossible_dates_are_rejected() {
        assert!(parse_date("2026-02-29").is_none());
        assert!(parse_date("2026-13-01").is_none());
        assert!(parse_date("26-01-01").is_none());
        assert!(parse_moment("2026-01-01 24:00").is_none());
    }
}