Cotton code
136 lines · 5.7 KB · RustRaw
//! Calendar arithmetic for Money's monthly grid: a date's absolute month//! index and its "YYYY-MM" label, and whole-day steps counted on//! `zoned_clock`'s civil calendar — the one every tool counts days on.//!//! Every function is pure and refuses a malformed date rather than landing//! money in the wrong month: a bad shape is [`DatesError::NotAnIsoDate`], a//! month or day out of range [`DatesError::Unparseable`].use crate::transforms::zoned_clock::{civil_from_days, days_from_civil};/// Why a date could not be read.////// The two `Unparseable*` variants are ONE `RangeError` on the TypeScript side/// and two here because the messages differ and both are reachable: a shape/// that passes the regex but is not a real ISO instant, and an instant so far/// out that `toISOString` itself refuses.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pub enum DatesError {    /// `TypeError` — the shape check, the same one every function here starts    /// with so a malformed date fails the same way wherever it enters.    #[error("expected an ISO date (YYYY-MM-DD), got \"{0}\"")]    NotAnIsoDate(String),    /// `RangeError` from `Date.parse` — the shape was right and the day was    /// not, e.g. month 13 or day 32. (Day 30 of February is NOT this: the    /// ECMAScript grammar admits any day 01–31 and `MakeDay` rolls it over, so    /// `add_days("2026-02-30", 1)` answers `2026-03-03`.)    #[error("unparseable ISO date \"{0}\"")]    Unparseable(String),    /// The arithmetic left the years 0000–9999, where no ISO date is.    #[error("Invalid time value")]    InvalidTimeValue,}impl DatesError {    /// Which JavaScript error constructor the TypeScript throws. The tests    /// assert `toThrow(TypeError)` against `toThrow(RangeError)`, so the    /// distinction is behaviour, not decoration.    pub const fn kind(&self) -> &'static str {        match self {            DatesError::NotAnIsoDate(_) => "TypeError",            DatesError::Unparseable(_) | DatesError::InvalidTimeValue => "RangeError",        }    }}/// `/^(\d{4})-(\d{2})-(\d{2})$/` — shape only, exactly as the TypeScript's/// regex: it says nothing about whether the month or day is real.fn iso_parts(iso: &str) -> Option<(i64, i64, i64)> {    let bytes = iso.as_bytes();    if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {        return None;    }    let digits = |from: usize, count: usize| -> Option<i64> {        let slice = bytes.get(from..from + count)?;        if !slice.iter().all(u8::is_ascii_digit) {            return None;        }        let mut value = 0i64;        for byte in slice {            value = value * 10 + i64::from(byte - b'0');        }        Some(value)    };    Some((digits(0, 4)?, digits(5, 2)?, digits(8, 2)?))}/// Absolute month index (year × 12 + month − 1) from an ISO date.////// The SHAPE is all that is checked, which is the TypeScript's behaviour and/// worth knowing: `month_index("2026-13-01")` is 24324, one past December 2026,/// because the regex has no opinion about month 13. Every caller that needs a/// REAL date validates with `period::assert_iso_date` instead.pub fn month_index(iso: &str) -> Result<i64, DatesError> {    let (year, month, _) =        iso_parts(iso).ok_or_else(|| DatesError::NotAnIsoDate(iso.to_string()))?;    Ok(year * 12 + (month - 1))}/// The "YYYY-MM" label for an absolute month index.////// `Math.floor(index / 12)` for the year and JavaScript's TRUNCATED `%` for the/// month, which is why a negative index produces the strange-looking labels the/// vectors pin (`month_label(-1)` is `"00-1-00"`: the year is −1, rendered/// `"-1"` and then left-padded with zeros to four characters). Nothing in the/// engine reaches a negative index; the arithmetic is ported as it stands so the/// two implementations cannot differ if one ever does.pub fn month_label(index: i64) -> String {    let year = index.div_euclid(12);    let month = (index % 12) + 1;    format!("{}-{}", pad_start(year, 4), pad_start(month, 2))}/// `String(n).padStart(width, "0")` — a MINIMUM width, never a truncation, and/// the minus sign counts as one of the characters it pads around.fn pad_start(value: i64, width: usize) -> String {    let text = value.to_string();    if text.len() >= width {        return text;    }    let mut out = "0".repeat(width - text.len());    out.push_str(&text);    out}/// `iso` + `days`, as a calendar date, on `zoned_clock`'s calendar (the one/// every tool counts days on). A day 29–31 past its month's end rolls over/// (`2026-02-30` is 2 March); a month or day outside 1–12 / 1–31 is refused,/// and so is an answer outside the years 0000–9999.pub fn add_days(iso: &str, days: i64) -> Result<String, DatesError> {    let shifted = day_of(iso)?.checked_add(days).ok_or(DatesError::InvalidTimeValue)?;    let (year, month, day) = civil_from_days(shifted);    if !(0..=9999).contains(&year) {        return Err(DatesError::InvalidTimeValue);    }    Ok(format!("{year:04}-{month:02}-{day:02}"))}/// Calendar-day distance used by transfer matching.pub fn days_between_dates(from_iso: &str, to_iso: &str) -> Result<i64, DatesError> {    Ok(day_of(to_iso)? - day_of(from_iso)?)}/// The day number of an ISO date, the shape checked first.fn day_of(iso: &str) -> Result<i64, DatesError> {    let (year, month, day) = iso_parts(iso).ok_or_else(|| DatesError::NotAnIsoDate(iso.to_string()))?;    if !(1..=12).contains(&month) || !(1..=31).contains(&day) {        return Err(DatesError::Unparseable(iso.to_string()));    }    // The month's first day, then the day count: a 30 February rolls into March.    Ok(days_from_civil(year, month, 1) + day - 1)}#[cfg(test)]#[path = "dates_tests.rs"]mod tests;