Cotton code
230 lines · 8.2 KB · RustRaw
//! A moment split the way a person thinks of it: any datetime column read as a//! calendar day plus an optional clock time, and joined back. The port of//! `packages/core/src/engine/todoDue.ts`, named by the type it reads.//!//! A moment column stores ONE value, an ISO instant. The contract the app has//! always kept is that a moment at LOCAL MIDNIGHT is date-only — "a day is//! enough" — and any other clock reading is a stated hour. The phone applies//! that contract in the device's own zone; this module is the SAME contract//! for a process whose clock is not the person's, which is why the zone is an//! argument. Given that zone the two agree by construction.//!//! What the split buys: a caller can move the DAY and keep the hour, set the//! hour and keep the day, or drop the hour and keep the day. It names no//! table and no column — a todo's `due_at` is one caller.use crate::js::{json_stringify, parse_date_ms, to_iso_string};use crate::zoned_clock::{    date_utc, instant_from_zoned, zoned_parts, ZoneError, ZonedParts,};/// A moment as the person reads it.#[derive(Debug, Clone, PartialEq, Eq)]pub struct MomentSplit {    /// The calendar day, `YYYY-MM-DD`, in the zone it was read in.    pub date: String,    /// The clock time, `HH:mm` (24h), or `None` for a date-only moment.    pub time: Option<String>,}/// Why a moment could not be read or written. The sentences are the/// TypeScript's, verbatim.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pub enum MomentSplitError {    #[error("cotton: {0} is not an instant")]    NotAnInstant(String),    #[error("cotton: {0} is not a calendar day")]    NotACalendarDay(String),    #[error("cotton: {0} is not a clock time")]    NotAClockTime(String),    #[error("cotton: a time needs a day — this todo has no due date")]    TimeNeedsADay,    #[error(transparent)]    Zone(#[from] ZoneError),}/// A real calendar day, not just four-two-two digits.pub fn is_calendar_day(value: &str) -> bool {    parse_calendar_day(value).is_some()}/// `/^\d{4}-\d{2}-\d{2}$/` plus the round-trip through the calendar that/// rejects 30 February.fn parse_calendar_day(value: &str) -> Option<(i64, i64, i64)> {    let bytes = value.as_bytes();    if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {        return None;    }    if !bytes        .iter()        .enumerate()        .all(|(index, b)| index == 4 || index == 7 || b.is_ascii_digit())    {        return None;    }    let year: i64 = value[0..4].parse().ok()?;    let month: i64 = value[5..7].parse().ok()?;    let day: i64 = value[8..10].parse().ok()?;    // `Date.UTC` NORMALISES out-of-range components, so the TypeScript checks    // that the day it gets back is the day it asked for — which is what turns    // "2026-02-30" (a legal shape) into a refusal.    let probe = date_utc(year, month - 1, day, 0, 0, 0, 0);    let (probe_year, probe_month, probe_day) =        crate::zoned_clock::civil_from_days(probe.div_euclid(86_400_000));    if probe_year != year || probe_month != month || probe_day != day {        return None;    }    Some((year, month, day))}/// A clock time this module will store — `HH:mm`, 24-hour,/// `/^([01]\d|2[0-3]):[0-5]\d$/`.pub fn is_clock_time(value: &str) -> bool {    parse_clock_time(value).is_some()}fn parse_clock_time(value: &str) -> Option<(i64, i64)> {    let bytes = value.as_bytes();    if bytes.len() != 5 || bytes[2] != b':' {        return None;    }    if !bytes        .iter()        .enumerate()        .all(|(index, b)| index == 2 || b.is_ascii_digit())    {        return None;    }    let hour: i64 = value[0..2].parse().ok()?;    let minute: i64 = value[3..5].parse().ok()?;    if hour > 23 || minute > 59 {        return None;    }    Some((hour, minute))}/// Read an instant as a day plus an optional clock time, in `timezone`.////// Midnight reads as NO time — the contract. Refuses an instant that does not/// parse: a caller holding a row with a broken instant should hear it, not/// receive a day it did not ask for.pub fn split_moment(at: &str, timezone: &str) -> Result<MomentSplit, MomentSplitError> {    let instant =        parse_date_ms(at).ok_or_else(|| MomentSplitError::NotAnInstant(json_quote(at)))?;    let parts = zoned_parts(instant, timezone)?;    Ok(MomentSplit {        // NOT zero-padded: the TypeScript writes `${parts.year}` for the year        // and pads only the month and the day.        date: format!("{}-{:02}-{:02}", parts.year, parts.month, parts.day),        time: if parts.hour == 0 && parts.minute == 0 {            None        } else {            Some(format!("{:02}:{:02}", parts.hour, parts.minute))        },    })}/// True when the instant carries a stated hour in `timezone`.pub fn states_clock_time(at: &str, timezone: &str) -> Result<bool, MomentSplitError> {    Ok(split_moment(at, timezone)?.time.is_some())}/// The instant a day (and optional clock time) names in `timezone`, as the ISO/// string the file stores. A `None` time is local midnight — a date-only moment/// by the contract.pub fn join_moment(moment: &MomentSplit, timezone: &str) -> Result<String, MomentSplitError> {    let Some((year, month, day)) = parse_calendar_day(&moment.date) else {        return Err(MomentSplitError::NotACalendarDay(json_quote(&moment.date)));    };    let (hour, minute) = match moment.time.as_deref() {        None => (0, 0),        Some(time) => {            parse_clock_time(time).ok_or_else(|| MomentSplitError::NotAClockTime(json_quote(time)))?        }    };    let ms = instant_from_zoned(        ZonedParts {            year,            month,            day,            hour,            minute,            second: 0,        },        0,        timezone,    )?;    to_iso_string(ms).ok_or_else(|| MomentSplitError::NotAnInstant(ms.to_string()))}/// One half of a change to a moment.////// The TypeScript distinguishes `undefined` ("leave it alone") from `null`/// ("clear it"); Rust needs an explicit three-state, so this is it rather than/// an `Option<Option<T>>` that reads as nothing at a call site.#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]pub enum PartChange<T> {    /// `undefined` — leave this half alone.    #[default]    Unchanged,    /// `null` — clear this half.    Cleared,    /// A new value.    Set(T),}/// The next instant after a change to one or both halves.////// [`PartChange::Unchanged`] leaves a half alone; `Cleared` on `time` drops the/// clock (the day stays); `Cleared` on `date` clears the whole moment — a time/// without a day is not a moment. Answers `None` for "no moment". The one/// refusal: a time on a moment that has no day, which is a question with no/// answer — the caller turns it into a sentence for whoever asked.pub fn next_moment(    current: Option<&str>,    date: PartChange<&str>,    time: PartChange<&str>,    timezone: &str,) -> Result<Option<String>, MomentSplitError> {    if date == PartChange::Cleared {        return Ok(None);    }    let base = match current {        Some(current) => Some(split_moment(current, timezone)?),        None => None,    };    let resolved_date: Option<String> = match date {        PartChange::Set(date) => Some(date.to_string()),        // `change.date ?? base?.date ?? null` — `Unchanged` is `undefined`, so        // it falls through to the base.        PartChange::Unchanged => base.as_ref().map(|b| b.date.clone()),        PartChange::Cleared => unreachable!("handled above"),    };    let Some(resolved_date) = resolved_date else {        return match time {            PartChange::Unchanged | PartChange::Cleared => Ok(None),            PartChange::Set(_) => Err(MomentSplitError::TimeNeedsADay),        };    };    let resolved_time: Option<String> = match time {        PartChange::Unchanged => base.and_then(|b| b.time),        PartChange::Cleared => None,        PartChange::Set(time) => Some(time.to_string()),    };    Ok(Some(join_moment(        &MomentSplit {            date: resolved_date,            time: resolved_time,        },        timezone,    )?))}fn json_quote(value: &str) -> String {    json_stringify(&serde_json::Value::String(value.to_string()))}#[cfg(test)]#[path = "moment_split_tests.rs"]mod tests;