Skip to main content

ixa/
calendar.rs

1//! Calendar dates for parameters. Model times are `f64` days from day 0;
2//! given a start date, a document may write a day as a `YYYY-MM-DD` date,
3//! a `YYYY-Www` week, or days with units such as `2w`. The `#[calendar]`
4//! attribute marks those fields:
5//!
6//! ```
7//! use ixa::calendar;
8//! use ixa::calendar::Date;
9//! use serde::{Deserialize, Serialize};
10//!
11//! #[calendar]
12//! #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
13//! pub struct Policy {
14//!     #[calendar]
15//!     pub start: f64,
16//!     #[calendar]
17//!     pub end: Option<f64>,
18//!     #[calendar(duration)]
19//!     pub delay: f64,
20//! }
21//!
22//! #[calendar(weeks = "epi")]
23//! #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
24//! pub struct Parameters {
25//!     #[calendar(reference)]
26//!     pub start_date: Option<Date>,
27//!     #[calendar]
28//!     pub policies: Vec<Policy>,
29//!     #[calendar(inclusive)]
30//!     pub max_time: f64,
31//! }
32//!
33//! let p: Parameters = serde_json::from_str(r#"{
34//!     "start_date": "2026-05-14",
35//!     "policies": [{"start": "2026-06-01", "end": "2026-W27", "delay": "2w"}],
36//!     "max_time": "2026-08-05"
37//! }"#).unwrap();
38//! assert_eq!(p.policies[0].start, 18.0);
39//! assert_eq!(p.policies[0].end, Some(52.0));
40//! assert_eq!(p.policies[0].delay, 14.0);
41//! assert_eq!(p.max_time, 84.0);
42//!
43//! assert!(serde_json::to_string(&p).unwrap().contains(r#""start":18.0"#));
44//! assert!(serde_json::to_string(&p.dated()).unwrap().contains(r#""start":"2026-06-01""#));
45//! ```
46//!
47//! `#[calendar]` generates a twin struct (`CalendarPolicy` for `Policy`)
48//! holding each marked field's [`Calendar::Wire`] ([`Day`] for an `f64`),
49//! and implements [`Calendar`] between the two. Field options:
50//! `#[calendar(reference)]` marks the root's start date (`Date` or
51//! `Option<Date>`); `inclusive` is for a day a date or week includes, such
52//! as the end of a run; `duration` is for a length of time, which takes
53//! units but no dates and is not moved by [`Calendar::shift_days`];
54//! `signed` lets a duration be negative; `week` makes `dated()` write a
55//! week where the day starts one. `#[calendar(weeks = "iso")]` or
56//! `weeks = "epi"` on a struct picks the [`WeekSystem`] for it and the
57//! structs inside it; a week in a document without one is an error.
58//!
59//! Every calendar struct deserializes through its twin and serializes days.
60//! The struct with the start date is the root and has `dated()`; a struct
61//! read without one takes numbers and units but no dates or weeks. A nested
62//! root falls back to the outer start date. Dates are for human-readable
63//! formats; a format that is not (by serde's `is_human_readable`) reads and
64//! writes the struct as written, days only, so it round trips through any
65//! serde format. Every field type must then be `Deserialize`, including types
66//! that implement [`Calendar`] by hand.
67//!
68//! The twin copies the struct's derives and serde attributes, so
69//! `#[calendar]` goes above `#[derive(..)]`. Limits: derive `Clone`,
70//! `Debug`, `PartialEq`, `Serialize` and `Deserialize`; no generics; no serde `try_from`, `from`, `into` or `remote`,
71//! and no `with`, `deserialize_with`, `serialize_with` or `default = ".."`
72//! on a marked field. A struct with its own wire shape implements
73//! [`Calendar`] by hand. To validate a document, wrap the root in a type
74//! whose `Deserialize` reads it and checks the result.
75//!
76//! In code, [`Date::start_of`] and [`Date::start_of_week`] turn a date or
77//! week string into days from a start date. [`ContextCalendarExt`] stores
78//! the start date and week system on the context so reports can write the
79//! current [`Date`], [`Week`] and [`Weekday`], which serialize as
80//! `YYYY-MM-DD`, `YYYY-Www` and `Mon`.
81//!
82//! Field options on a field that does not hold days are a compile error:
83//!
84//! ```compile_fail
85//! use ixa::calendar;
86//! use serde::{Deserialize, Serialize};
87//!
88//! #[calendar]
89//! #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
90//! struct Window { #[calendar] from: f64 }
91//!
92//! #[calendar]
93//! #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
94//! struct Outer { #[calendar(inclusive)] windows: Vec<Window> }
95//! ```
96
97use std::fmt;
98use std::str::FromStr;
99
100use serde::de::{self, MapAccess, Visitor};
101use serde::{Deserialize, Deserializer, Serialize, Serializer};
102use thiserror::Error;
103
104use crate::{define_data_plugin, Context, ContextBase};
105
106/// Days since 1970-01-01 of 0000-01-01 and 9999-12-31.
107const MIN_DAYS: i64 = -719_528;
108const MAX_DAYS: i64 = 2_932_896;
109
110/// A calendar date, written and read as `YYYY-MM-DD`.
111#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
112pub struct Date {
113    year: i32,
114    month: u32,
115    day: u32,
116}
117
118/// Days since 1970-01-01 of a proleptic Gregorian date, negative before it.
119fn civil_to_days(y: i64, m: i64, d: i64) -> i64 {
120    let y = if m <= 2 { y - 1 } else { y };
121    let era = if y >= 0 { y } else { y - 399 } / 400;
122    let yoe = y - era * 400;
123    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
124    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
125    era * 146_097 + doe - 719_468
126}
127
128impl Date {
129    /// A checked date, with a four-digit year.
130    ///
131    /// # Errors
132    /// When the year, month or day is out of range.
133    pub fn new(year: i32, month: u32, day: u32) -> Result<Self, CalendarError> {
134        if !(0..=9999).contains(&year) {
135            return Err(CalendarError::InvalidDate(format!(
136                "year {year} is not 0 to 9999"
137            )));
138        }
139        let days_in_month = match month {
140            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
141            4 | 6 | 9 | 11 => 30,
142            2 if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) => 29,
143            2 => 28,
144            _ => {
145                return Err(CalendarError::InvalidDate(format!(
146                    "month {month} is not 1 to 12"
147                )))
148            }
149        };
150        if day == 0 || day > days_in_month {
151            return Err(CalendarError::InvalidDate(format!(
152                "day {day} is not 1 to {days_in_month}"
153            )));
154        }
155        Ok(Self { year, month, day })
156    }
157
158    /// Days since 1970-01-01, negative before it.
159    fn days_since_epoch(self) -> i64 {
160        civil_to_days(
161            i64::from(self.year),
162            i64::from(self.month),
163            i64::from(self.day),
164        )
165    }
166
167    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
168    fn from_days_since_epoch(days: i64) -> Self {
169        let z = days + 719_468;
170        let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
171        let doe = z - era * 146_097;
172        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
173        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
174        let mp = (5 * doy + 2) / 153;
175        let day = doy - (153 * mp + 2) / 5 + 1;
176        let month = if mp < 10 { mp + 3 } else { mp - 9 };
177        let year = yoe + era * 400 + i64::from(month <= 2);
178        Self {
179            year: year as i32,
180            month: month as u32,
181            day: day as u32,
182        }
183    }
184
185    #[must_use]
186    pub fn year(self) -> i32 {
187        self.year
188    }
189
190    #[must_use]
191    pub fn month(self) -> u32 {
192        self.month
193    }
194
195    #[must_use]
196    pub fn day(self) -> u32 {
197        self.day
198    }
199
200    /// The date `days` after this one (before it if negative), or `None`
201    /// outside years 0 to 9999.
202    #[must_use]
203    pub fn checked_plus_days(self, days: i64) -> Option<Self> {
204        self.days_since_epoch()
205            .checked_add(days)
206            .filter(|d| (MIN_DAYS..=MAX_DAYS).contains(d))
207            .map(Self::from_days_since_epoch)
208    }
209
210    /// The date that `time` falls on, with this date as day 0, or `None`
211    /// outside years 0 to 9999.
212    #[must_use]
213    #[allow(clippy::cast_possible_truncation)]
214    pub fn date_at(self, time: f64) -> Option<Self> {
215        if !time.is_finite() {
216            return None;
217        }
218        self.checked_plus_days(time.floor() as i64)
219    }
220
221    /// Days from this date to `other`, negative if `other` is earlier.
222    #[must_use]
223    pub fn days_until(self, other: Date) -> i64 {
224        other.days_since_epoch() - self.days_since_epoch()
225    }
226
227    /// The start of the date in `s`, in days from this date, for dates
228    /// written in code: `start.start_of("2026-06-01")`.
229    ///
230    /// # Panics
231    /// When `s` is not a valid `YYYY-MM-DD` date.
232    #[must_use]
233    #[track_caller]
234    #[allow(clippy::cast_precision_loss)]
235    pub fn start_of(self, s: &str) -> f64 {
236        match s.parse::<Date>() {
237            Ok(date) => self.days_until(date) as f64,
238            Err(e) => panic!("{e}"),
239        }
240    }
241
242    /// The end of the date in `s`, [`Date::start_of`] plus one, for an
243    /// inclusive bound such as the end of a run.
244    ///
245    /// # Panics
246    /// When `s` is not a valid `YYYY-MM-DD` date.
247    #[must_use]
248    #[track_caller]
249    pub fn end_of(self, s: &str) -> f64 {
250        self.start_of(s) + 1.0
251    }
252
253    #[must_use]
254    pub fn weekday(self) -> Weekday {
255        Weekday::ALL[WeekSystem::Iso.offset(self.days_since_epoch()) as usize]
256    }
257
258    /// The week this date falls in; near New Year it may belong to the
259    /// year before or after. `None` for the first days of year 0, whose
260    /// week belongs to year -1.
261    #[must_use]
262    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
263    pub fn week(self, system: WeekSystem) -> Option<Week> {
264        let days = self.days_since_epoch();
265        let first = days - system.offset(days);
266        // A week belongs to the year of its fourth day.
267        let year = Self::from_days_since_epoch(first + 3).year;
268        let week = (first - system.week_one(i64::from(year))) / 7 + 1;
269        Week::new(year, week as u32).ok()
270    }
271
272    /// The start of the week in `s`, in days from this date, for weeks
273    /// written in code: `start.start_of_week("2026-W12", WeekSystem::Epi)`.
274    ///
275    /// # Panics
276    /// When `s` is not a valid `YYYY-Www` week in `system`.
277    #[must_use]
278    #[track_caller]
279    #[allow(clippy::cast_precision_loss)]
280    pub fn start_of_week(self, s: &str, system: WeekSystem) -> f64 {
281        match s.parse::<Week>().and_then(|week| week.first_day(system)) {
282            Ok(date) => self.days_until(date) as f64,
283            Err(e) => panic!("{e}"),
284        }
285    }
286
287    /// The end of the week in `s`, [`Date::start_of_week`] plus seven.
288    ///
289    /// # Panics
290    /// When `s` is not a valid `YYYY-Www` week in `system`.
291    #[must_use]
292    #[track_caller]
293    pub fn end_of_week(self, s: &str, system: WeekSystem) -> f64 {
294        self.start_of_week(s, system) + 7.0
295    }
296}
297
298impl FromStr for Date {
299    type Err = CalendarError;
300
301    fn from_str(s: &str) -> Result<Self, CalendarError> {
302        let invalid = || CalendarError::InvalidDate(format!("{s:?} is not a date (YYYY-MM-DD)"));
303        let mut parts = s.split('-');
304        let mut next = |len: usize| {
305            parts
306                .next()
307                .filter(|p| p.len() == len && p.bytes().all(|b| b.is_ascii_digit()))
308                .and_then(|p| p.parse::<u32>().ok())
309                .ok_or_else(invalid)
310        };
311        let (year, month, day) = (next(4)?, next(2)?, next(2)?);
312        if parts.next().is_some() {
313            return Err(invalid());
314        }
315        #[allow(clippy::cast_possible_wrap)]
316        Self::new(year as i32, month, day)
317            .map_err(|e| CalendarError::InvalidDate(format!("{s:?}: {e}")))
318    }
319}
320
321impl fmt::Display for Date {
322    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
323        write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
324    }
325}
326
327impl Serialize for Date {
328    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
329        serializer.collect_str(self)
330    }
331}
332
333/// The key of the map the `toml` crate hands over for a native TOML date.
334const TOML_DATETIME: &str = "$__toml_private_datetime";
335
336/// `YYYY-MM-DD`, or a native TOML date.
337struct DateVisitor;
338
339impl<'de> Visitor<'de> for DateVisitor {
340    type Value = Date;
341
342    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
343        f.write_str("a date, YYYY-MM-DD")
344    }
345
346    fn visit_str<E: de::Error>(self, s: &str) -> Result<Date, E> {
347        s.parse().map_err(E::custom)
348    }
349
350    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Date, A::Error> {
351        let mut text = None;
352        while let Some(key) = map.next_key::<String>()? {
353            if key != TOML_DATETIME {
354                return Err(de::Error::unknown_field(&key, &[TOML_DATETIME]));
355            }
356            text = Some(map.next_value::<String>()?);
357        }
358        let text = text.ok_or_else(|| de::Error::missing_field(TOML_DATETIME))?;
359        text.parse().map_err(de::Error::custom)
360    }
361}
362
363impl<'de> Deserialize<'de> for Date {
364    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
365        if deserializer.is_human_readable() {
366            deserializer.deserialize_any(DateVisitor)
367        } else {
368            deserializer.deserialize_str(DateVisitor)
369        }
370    }
371}
372
373/// A day of the week, written as `Mon` to `Sun`.
374#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
375pub enum Weekday {
376    Monday,
377    Tuesday,
378    Wednesday,
379    Thursday,
380    Friday,
381    Saturday,
382    Sunday,
383}
384
385impl Weekday {
386    const ALL: [Self; 7] = [
387        Self::Monday,
388        Self::Tuesday,
389        Self::Wednesday,
390        Self::Thursday,
391        Self::Friday,
392        Self::Saturday,
393        Self::Sunday,
394    ];
395
396    fn abbreviation(self) -> &'static str {
397        match self {
398            Self::Monday => "Mon",
399            Self::Tuesday => "Tue",
400            Self::Wednesday => "Wed",
401            Self::Thursday => "Thu",
402            Self::Friday => "Fri",
403            Self::Saturday => "Sat",
404            Self::Sunday => "Sun",
405        }
406    }
407}
408
409impl fmt::Display for Weekday {
410    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
411        f.write_str(self.abbreviation())
412    }
413}
414
415impl FromStr for Weekday {
416    type Err = CalendarError;
417
418    fn from_str(s: &str) -> Result<Self, CalendarError> {
419        Self::ALL
420            .into_iter()
421            .find(|day| day.abbreviation() == s)
422            .ok_or_else(|| {
423                CalendarError::InvalidWeekday(format!("{s:?} is not a weekday (Mon to Sun)"))
424            })
425    }
426}
427
428impl Serialize for Weekday {
429    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
430        serializer.collect_str(self)
431    }
432}
433
434impl<'de> Deserialize<'de> for Weekday {
435    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
436        let s = <std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
437        s.parse().map_err(de::Error::custom)
438    }
439}
440
441/// How weeks are numbered. Both number from the week holding January 4
442/// (the first with four days in the year), so a week near New Year may
443/// belong to the year before or after.
444#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
445pub enum WeekSystem {
446    /// ISO 8601: weeks start on Monday.
447    Iso,
448    /// CDC epidemiological (MMWR) weeks: weeks start on Sunday.
449    Epi,
450}
451
452impl WeekSystem {
453    /// Days since the start of the week of the day `days` since 1970-01-01.
454    fn offset(self, days: i64) -> i64 {
455        // 1970-01-01 was a Thursday.
456        match self {
457            Self::Iso => (days + 3).rem_euclid(7),
458            Self::Epi => (days + 4).rem_euclid(7),
459        }
460    }
461
462    /// Days since 1970-01-01 of the first day of week 1 of `year`.
463    fn week_one(self, year: i64) -> i64 {
464        let jan_4 = civil_to_days(year, 1, 4);
465        jan_4 - self.offset(jan_4)
466    }
467
468    /// 52 or 53.
469    #[must_use]
470    pub fn weeks_in(self, year: i32) -> u32 {
471        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
472        let weeks =
473            ((self.week_one(i64::from(year) + 1) - self.week_one(i64::from(year))) / 7) as u32;
474        weeks
475    }
476}
477
478impl fmt::Display for WeekSystem {
479    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
480        f.write_str(match self {
481            Self::Iso => "ISO",
482            Self::Epi => "epi",
483        })
484    }
485}
486
487/// A numbered week of a year, written and read as `YYYY-Www`. Which days
488/// it covers depends on the [`WeekSystem`].
489#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
490pub struct Week {
491    year: i32,
492    week: u32,
493}
494
495impl Week {
496    /// A week 1 to 53 of a four-digit year; whether the year has a week 53
497    /// is checked by [`Week::first_day`].
498    ///
499    /// # Errors
500    /// When the year or week is out of range.
501    pub fn new(year: i32, week: u32) -> Result<Self, CalendarError> {
502        if !(0..=9999).contains(&year) {
503            return Err(CalendarError::InvalidWeek(format!(
504                "year {year} is not 0 to 9999"
505            )));
506        }
507        if !(1..=53).contains(&week) {
508            return Err(CalendarError::InvalidWeek(format!(
509                "week {week} is not 1 to 53"
510            )));
511        }
512        Ok(Self { year, week })
513    }
514
515    #[must_use]
516    pub fn year(self) -> i32 {
517        self.year
518    }
519
520    #[must_use]
521    pub fn number(self) -> u32 {
522        self.week
523    }
524
525    /// The Monday (ISO) or Sunday (epi) the week starts on.
526    ///
527    /// # Errors
528    /// Week 53 of a year with 52 weeks, or a week outside years 0 to 9999.
529    pub fn first_day(self, system: WeekSystem) -> Result<Date, CalendarError> {
530        let weeks = system.weeks_in(self.year);
531        if self.week > weeks {
532            return Err(CalendarError::InvalidWeek(format!(
533                "{self}: {} has {weeks} {system} weeks",
534                self.year
535            )));
536        }
537        let days = system.week_one(i64::from(self.year)) + 7 * i64::from(self.week - 1);
538        if !(MIN_DAYS..=MAX_DAYS).contains(&days) {
539            return Err(CalendarError::InvalidWeek(format!(
540                "{self} starts outside years 0 to 9999"
541            )));
542        }
543        Ok(Date::from_days_since_epoch(days))
544    }
545}
546
547impl FromStr for Week {
548    type Err = CalendarError;
549
550    fn from_str(s: &str) -> Result<Self, CalendarError> {
551        let invalid = || CalendarError::InvalidWeek(format!("{s:?} is not a week (YYYY-Www)"));
552        let digits = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit());
553        let (year, week) = s.split_once("-W").ok_or_else(invalid)?;
554        if year.len() != 4 || week.len() != 2 || !digits(year) || !digits(week) {
555            return Err(invalid());
556        }
557        let (year, week) = (
558            year.parse().map_err(|_| invalid())?,
559            week.parse().map_err(|_| invalid())?,
560        );
561        Self::new(year, week).map_err(|e| CalendarError::InvalidWeek(format!("{s:?}: {e}")))
562    }
563}
564
565impl fmt::Display for Week {
566    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
567        write!(f, "{:04}-W{:02}", self.year, self.week)
568    }
569}
570
571impl Serialize for Week {
572    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
573        serializer.collect_str(self)
574    }
575}
576
577struct WeekVisitor;
578
579impl Visitor<'_> for WeekVisitor {
580    type Value = Week;
581
582    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
583        f.write_str("a week, YYYY-Www")
584    }
585
586    fn visit_str<E: de::Error>(self, s: &str) -> Result<Week, E> {
587        s.parse().map_err(E::custom)
588    }
589}
590
591impl<'de> Deserialize<'de> for Week {
592    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
593        deserializer.deserialize_str(WeekVisitor)
594    }
595}
596
597/// An error reading a date or converting one to days.
598#[derive(Error, Debug, Clone, PartialEq)]
599pub enum CalendarError {
600    #[error("{0}")]
601    InvalidDate(String),
602    #[error("{0}")]
603    InvalidWeek(String),
604    #[error("{0}")]
605    InvalidWeekday(String),
606    /// Days with units that do not parse.
607    #[error("{0}")]
608    InvalidDays(String),
609    /// A negative or NaN value in a `duration` field.
610    #[error("a duration cannot be {}", if .0.is_nan() { "NaN".to_string() } else { format!("negative: {}", .0) })]
611    InvalidDuration(f64),
612    /// A date or week with no start date to count from.
613    #[error("{0} is a {kind}, but there is no start date", kind = .0.kind())]
614    NoStartDate(Day),
615    #[error("{0} is a week, but no week system is set: add `weeks = \"iso\"` or `weeks = \"epi\"` to `#[calendar]`")]
616    NoWeekSystem(Week),
617    /// A date or week in a `duration` field.
618    #[error("a duration cannot be the {kind} {0}", kind = .0.kind())]
619    NotADuration(Day),
620    /// From a hand-written [`Calendar`] impl.
621    #[error("{0}")]
622    Custom(String),
623    /// An error in a field, such as `policies[0].start`.
624    #[error("{path}: {error}")]
625    At {
626        path: String,
627        error: Box<CalendarError>,
628    },
629}
630
631impl CalendarError {
632    /// The error inside field `segment` (or index `[i]`) of a struct.
633    #[must_use]
634    pub fn at(self, segment: &str) -> Self {
635        match self {
636            Self::At { path, error } => {
637                let dot = if path.starts_with('[') { "" } else { "." };
638                Self::At {
639                    path: format!("{segment}{dot}{path}"),
640                    error,
641                }
642            }
643            error => Self::At {
644                path: segment.to_owned(),
645                error: Box::new(error),
646            },
647        }
648    }
649}
650
651/// A day field as a document writes it. Days with units (`2w`, `3d`,
652/// `12h`) read as [`Day::DaysFromStart`].
653#[derive(Clone, Copy, Debug, PartialEq)]
654pub enum Day {
655    DaysFromStart(f64),
656    CalendarDate(Date),
657    CalendarWeek(Week),
658}
659
660impl Default for Day {
661    fn default() -> Self {
662        Self::DaysFromStart(0.0)
663    }
664}
665
666/// Days compare with days, dates with dates and weeks with weeks; other
667/// pairs are incomparable without a start date.
668impl PartialOrd for Day {
669    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
670        match (self, other) {
671            (Self::DaysFromStart(a), Self::DaysFromStart(b)) => a.partial_cmp(b),
672            (Self::CalendarDate(a), Self::CalendarDate(b)) => a.partial_cmp(b),
673            (Self::CalendarWeek(a), Self::CalendarWeek(b)) => a.partial_cmp(b),
674            _ => None,
675        }
676    }
677}
678
679impl fmt::Display for Day {
680    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
681        match self {
682            Self::DaysFromStart(days) => write!(f, "{days}"),
683            Self::CalendarDate(date) => write!(f, "{date}"),
684            Self::CalendarWeek(week) => write!(f, "{week}"),
685        }
686    }
687}
688
689impl Day {
690    fn kind(self) -> &'static str {
691        match self {
692            Self::DaysFromStart(_) => "number of days",
693            Self::CalendarDate(_) => "date",
694            Self::CalendarWeek(_) => "week",
695        }
696    }
697
698    /// Days from the start date, read as `field` says: an `inclusive` date
699    /// or week covers its whole span, and a `duration` takes no date or
700    /// week.
701    ///
702    /// # Errors
703    /// A date or week with no start date, a week with no week system or
704    /// that its year does not have, or a date, week or negative value
705    /// where a duration does not allow one.
706    pub fn resolve(self, cx: CalendarContext, field: FieldOptions) -> Result<f64, CalendarError> {
707        if field.duration {
708            return match self {
709                Self::DaysFromStart(days) if days.is_nan() || (!field.signed && days < 0.0) => {
710                    Err(CalendarError::InvalidDuration(days))
711                }
712                Self::DaysFromStart(days) => Ok(days),
713                _ => Err(CalendarError::NotADuration(self)),
714            };
715        }
716        let start = || cx.start.ok_or(CalendarError::NoStartDate(self));
717        #[allow(clippy::cast_precision_loss)]
718        match self {
719            Self::DaysFromStart(days) => Ok(days),
720            Self::CalendarDate(date) => {
721                Ok(start()?.days_until(date) as f64 + f64::from(field.inclusive))
722            }
723            Self::CalendarWeek(week) => {
724                let system = cx.weeks.ok_or(CalendarError::NoWeekSystem(week))?;
725                let start = start()?;
726                let first = week.first_day(system)?;
727                Ok(start.days_until(first) as f64 + if field.inclusive { 7.0 } else { 0.0 })
728            }
729        }
730    }
731
732    /// With a start date and `days` a whole day in range, a week if `field`
733    /// asks for one and the day starts a week, else a date; days otherwise
734    /// and for a duration.
735    #[must_use]
736    #[allow(clippy::cast_possible_truncation)]
737    pub fn from_days(days: f64, cx: CalendarContext, field: FieldOptions) -> Self {
738        let Some(start) = cx.start.filter(|_| !field.duration) else {
739            return Self::DaysFromStart(days);
740        };
741        let whole_day = |d: f64| {
742            (d.fract() == 0.0)
743                .then(|| start.checked_plus_days(d as i64))
744                .flatten()
745        };
746        if let Some(system) = cx.weeks.filter(|_| field.write_week) {
747            let week =
748                whole_day(days - if field.inclusive { 7.0 } else { 0.0 }).and_then(|first| {
749                    first
750                        .week(system)
751                        .filter(|week| week.first_day(system) == Ok(first))
752                });
753            if let Some(week) = week {
754                return Self::CalendarWeek(week);
755            }
756        }
757        whole_day(days - f64::from(field.inclusive))
758            .map_or(Self::DaysFromStart(days), Self::CalendarDate)
759    }
760}
761
762/// A date `YYYY-MM-DD`, a week `YYYY-Www`, or days with units.
763impl FromStr for Day {
764    type Err = CalendarError;
765
766    fn from_str(s: &str) -> Result<Self, CalendarError> {
767        let b = s.as_bytes();
768        if b.len() > 4 && b[4] == b'-' && b[..4].iter().all(u8::is_ascii_digit) {
769            if b.get(5) == Some(&b'W') {
770                s.parse().map(Self::CalendarWeek)
771            } else {
772                s.parse().map(Self::CalendarDate)
773            }
774        } else {
775            parse_days(s).map(Self::DaysFromStart)
776        }
777    }
778}
779
780/// Days from a sign and terms like `2w 3d 12h`.
781fn parse_days(s: &str) -> Result<f64, CalendarError> {
782    let invalid = || {
783        CalendarError::InvalidDays(format!(
784            "{s:?} is not a date (YYYY-MM-DD), a week (YYYY-Www) or days with units (3d, 2w, 12h)"
785        ))
786    };
787    let (sign, mut rest) = match s.strip_prefix('-') {
788        Some(rest) => (-1.0, rest),
789        None => (1.0, s),
790    };
791    let mut total = 0.0;
792    let mut terms = 0;
793    loop {
794        rest = rest.trim_start();
795        if rest.is_empty() {
796            break;
797        }
798        let end = rest
799            .find(|c: char| !(c.is_ascii_digit() || c == '.'))
800            .unwrap_or(rest.len());
801        let value: f64 = rest[..end].parse().map_err(|_| invalid())?;
802        rest = rest[end..].trim_start();
803        let end = rest
804            .find(|c: char| !c.is_ascii_alphabetic())
805            .unwrap_or(rest.len());
806        total += match &rest[..end] {
807            "w" | "week" | "weeks" => value * 7.0,
808            "d" | "day" | "days" => value,
809            "h" | "hour" | "hours" => value / 24.0,
810            "mo" | "month" | "months" | "y" | "year" | "years" => {
811                return Err(CalendarError::InvalidDays(format!(
812                    "{s:?}: months and years have no fixed length, so write a date instead"
813                )))
814            }
815            _ => return Err(invalid()),
816        };
817        rest = &rest[end..];
818        terms += 1;
819    }
820    if terms == 0 || !f64::is_finite(total) {
821        return Err(invalid());
822    }
823    Ok(sign * total)
824}
825
826/// Tagged form of [`Day`] for binary formats.
827#[derive(Serialize, Deserialize)]
828#[serde(remote = "Day")]
829enum BinaryDay {
830    DaysFromStart(f64),
831    CalendarDate(Date),
832    CalendarWeek(Week),
833}
834
835impl Serialize for Day {
836    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
837        match self {
838            _ if !serializer.is_human_readable() => BinaryDay::serialize(self, serializer),
839            Self::DaysFromStart(days) => serializer.serialize_f64(*days),
840            Self::CalendarDate(date) => date.serialize(serializer),
841            Self::CalendarWeek(week) => week.serialize(serializer),
842        }
843    }
844}
845
846struct DayVisitor;
847
848impl<'de> Visitor<'de> for DayVisitor {
849    type Value = Day;
850
851    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
852        f.write_str("days, a date YYYY-MM-DD, a week YYYY-Www, or days with units like 2w")
853    }
854
855    fn visit_f64<E: de::Error>(self, v: f64) -> Result<Day, E> {
856        Ok(Day::DaysFromStart(v))
857    }
858
859    #[allow(clippy::cast_precision_loss)]
860    fn visit_i64<E: de::Error>(self, v: i64) -> Result<Day, E> {
861        Ok(Day::DaysFromStart(v as f64))
862    }
863
864    #[allow(clippy::cast_precision_loss)]
865    fn visit_u64<E: de::Error>(self, v: u64) -> Result<Day, E> {
866        Ok(Day::DaysFromStart(v as f64))
867    }
868
869    fn visit_str<E: de::Error>(self, s: &str) -> Result<Day, E> {
870        s.parse().map_err(E::custom)
871    }
872
873    fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Day, A::Error> {
874        DateVisitor.visit_map(map).map(Day::CalendarDate)
875    }
876}
877
878impl<'de> Deserialize<'de> for Day {
879    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
880        if deserializer.is_human_readable() {
881            deserializer.deserialize_any(DayVisitor)
882        } else {
883            BinaryDay::deserialize(deserializer)
884        }
885    }
886}
887
888/// The enclosing start date and week system of a conversion.
889#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
890pub struct CalendarContext {
891    pub start: Option<Date>,
892    pub weeks: Option<WeekSystem>,
893}
894
895/// The `#[calendar(..)]` options of the field being converted; the default
896/// is a plain point in time.
897#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
898pub struct FieldOptions {
899    pub inclusive: bool,
900    pub duration: bool,
901    pub signed: bool,
902    /// `week`: write a day that starts a week as the week.
903    pub write_week: bool,
904}
905
906/// A type with day fields and a wire form that may hold dates.
907/// `#[calendar]` implements it for a struct.
908pub trait Calendar: Sized {
909    /// The same type with [`Day`] for each day.
910    type Wire;
911
912    /// Whether the type holds days itself (`f64`, or an `Option` or `Vec`
913    /// of one), so the field options `inclusive`, `duration`, `signed` and
914    /// `week` apply to it.
915    const DAYS: bool = false;
916
917    /// `field` holds the options of the field this value is in, which only
918    /// a type with [`Calendar::DAYS`] reads. A struct passes each of its
919    /// fields their own options, and one with its own start date or week
920    /// system puts those in `cx`.
921    ///
922    /// # Errors
923    /// A date with no start date, or a field's own conversion error.
924    fn from_calendar(
925        wire: Self::Wire,
926        cx: CalendarContext,
927        field: FieldOptions,
928    ) -> Result<Self, CalendarError>;
929
930    /// Whole days as dates when there is a start date.
931    fn to_calendar(&self, cx: CalendarContext, field: FieldOptions) -> Self::Wire;
932
933    /// Moves every point in time `days` later; durations and start dates
934    /// stay.
935    fn shift_days(&mut self, days: f64);
936
937    /// Moves every start date, including nested roots', `days` later.
938    /// Paired with `shift_days(-days)` it moves day 0 and keeps every date.
939    ///
940    /// # Errors
941    /// A start date moved outside years 0 to 9999; earlier ones have then
942    /// already moved.
943    fn shift_start_dates(&mut self, _days: i64) -> Result<(), CalendarError> {
944        Ok(())
945    }
946}
947
948/// A start date field, `Date` or `Option<Date>`, for `#[calendar]`.
949#[doc(hidden)]
950pub trait StartDate {
951    /// # Errors
952    /// The date moved outside years 0 to 9999.
953    fn shift_start_date(&mut self, days: i64) -> Result<(), CalendarError>;
954}
955
956impl StartDate for Date {
957    fn shift_start_date(&mut self, days: i64) -> Result<(), CalendarError> {
958        *self = self.checked_plus_days(days).ok_or_else(|| {
959            CalendarError::InvalidDate(format!(
960                "{self} moved {days} days is outside years 0 to 9999"
961            ))
962        })?;
963        Ok(())
964    }
965}
966
967impl StartDate for Option<Date> {
968    fn shift_start_date(&mut self, days: i64) -> Result<(), CalendarError> {
969        self.as_mut()
970            .map_or(Ok(()), |date| date.shift_start_date(days))
971    }
972}
973
974impl Calendar for f64 {
975    type Wire = Day;
976    const DAYS: bool = true;
977
978    fn from_calendar(
979        wire: Day,
980        cx: CalendarContext,
981        field: FieldOptions,
982    ) -> Result<Self, CalendarError> {
983        wire.resolve(cx, field)
984    }
985
986    fn to_calendar(&self, cx: CalendarContext, field: FieldOptions) -> Day {
987        Day::from_days(*self, cx, field)
988    }
989
990    fn shift_days(&mut self, days: f64) {
991        *self += days;
992    }
993}
994
995impl<T: Calendar> Calendar for Vec<T> {
996    type Wire = Vec<T::Wire>;
997    const DAYS: bool = T::DAYS;
998
999    fn from_calendar(
1000        wire: Self::Wire,
1001        cx: CalendarContext,
1002        field: FieldOptions,
1003    ) -> Result<Self, CalendarError> {
1004        wire.into_iter()
1005            .enumerate()
1006            .map(|(i, w)| T::from_calendar(w, cx, field).map_err(|e| e.at(&format!("[{i}]"))))
1007            .collect()
1008    }
1009
1010    fn to_calendar(&self, cx: CalendarContext, field: FieldOptions) -> Self::Wire {
1011        self.iter().map(|t| t.to_calendar(cx, field)).collect()
1012    }
1013
1014    fn shift_days(&mut self, days: f64) {
1015        for t in self {
1016            t.shift_days(days);
1017        }
1018    }
1019
1020    fn shift_start_dates(&mut self, days: i64) -> Result<(), CalendarError> {
1021        for (i, t) in self.iter_mut().enumerate() {
1022            t.shift_start_dates(days)
1023                .map_err(|e| e.at(&format!("[{i}]")))?;
1024        }
1025        Ok(())
1026    }
1027}
1028
1029impl<T: Calendar> Calendar for Option<T> {
1030    type Wire = Option<T::Wire>;
1031    const DAYS: bool = T::DAYS;
1032
1033    fn from_calendar(
1034        wire: Self::Wire,
1035        cx: CalendarContext,
1036        field: FieldOptions,
1037    ) -> Result<Self, CalendarError> {
1038        wire.map(|w| T::from_calendar(w, cx, field)).transpose()
1039    }
1040
1041    fn to_calendar(&self, cx: CalendarContext, field: FieldOptions) -> Self::Wire {
1042        self.as_ref().map(|t| t.to_calendar(cx, field))
1043    }
1044
1045    fn shift_days(&mut self, days: f64) {
1046        if let Some(t) = self {
1047            t.shift_days(days);
1048        }
1049    }
1050
1051    fn shift_start_dates(&mut self, days: i64) -> Result<(), CalendarError> {
1052        self.as_mut().map_or(Ok(()), |t| t.shift_start_dates(days))
1053    }
1054}
1055
1056#[derive(Clone, Copy, Debug, Default)]
1057struct CalendarSettings {
1058    start: Option<Date>,
1059    weeks: Option<WeekSystem>,
1060}
1061
1062define_data_plugin!(
1063    CalendarPlugin,
1064    CalendarSettings,
1065    CalendarSettings::default()
1066);
1067
1068/// The date of day 0 and the week system on a [`Context`], for writing
1069/// dates and weeks in reports.
1070pub trait ContextCalendarExt: ContextBase {
1071    /// Sets the date of day 0; takes a `Date` or a parameters' `Option<Date>`.
1072    fn set_start_date(&mut self, start: impl Into<Option<Date>>) {
1073        self.get_data_mut(CalendarPlugin).start = start.into();
1074    }
1075
1076    fn get_start_date(&self) -> Option<Date> {
1077        self.get_data(CalendarPlugin).start
1078    }
1079
1080    /// Takes a `WeekSystem` or a root's `WEEK_SYSTEM`.
1081    fn set_week_system(&mut self, weeks: impl Into<Option<WeekSystem>>) {
1082        self.get_data_mut(CalendarPlugin).weeks = weeks.into();
1083    }
1084
1085    fn get_week_system(&self) -> Option<WeekSystem> {
1086        self.get_data(CalendarPlugin).weeks
1087    }
1088
1089    /// The date of the current time, if there is a start date.
1090    fn get_current_date(&self) -> Option<Date> {
1091        self.get_start_date()?.date_at(self.get_current_time())
1092    }
1093
1094    /// The week of the current time, if there is a start date and a week
1095    /// system.
1096    fn get_current_week(&self) -> Option<Week> {
1097        self.get_current_date()?.week(self.get_week_system()?)
1098    }
1099}
1100
1101impl ContextCalendarExt for Context {}
1102
1103#[cfg(test)]
1104mod tests {
1105    use serde_json::json;
1106
1107    use super::*;
1108
1109    fn cx(start: Option<Date>) -> CalendarContext {
1110        CalendarContext { start, weeks: None }
1111    }
1112
1113    fn inclusive(inclusive: bool) -> FieldOptions {
1114        FieldOptions {
1115            inclusive,
1116            ..FieldOptions::default()
1117        }
1118    }
1119
1120    fn date(s: &str) -> Date {
1121        s.parse().unwrap()
1122    }
1123
1124    #[test]
1125    fn dates_round_trip_through_days() {
1126        let date: Date = "2026-05-14".parse().unwrap();
1127        assert_eq!(date.to_string(), "2026-05-14");
1128        assert_eq!(
1129            date.checked_plus_days(83).unwrap().to_string(),
1130            "2026-08-05"
1131        );
1132        assert_eq!(
1133            date.checked_plus_days(-38).unwrap().to_string(),
1134            "2026-04-06"
1135        );
1136        assert_eq!(date.days_until("2026-10-06".parse().unwrap()), 145);
1137        assert_eq!(Date::new(1970, 1, 1).unwrap().days_since_epoch(), 0);
1138        let leap = Date::new(2000, 2, 29).unwrap();
1139        assert_eq!(leap.checked_plus_days(1).unwrap().month(), 3);
1140    }
1141
1142    /// Every day in range maps to the next valid date and back.
1143    #[test]
1144    fn every_day_in_range_is_the_next_valid_date() {
1145        let mut previous = Date::new(0, 1, 1).unwrap();
1146        assert_eq!(previous.days_since_epoch(), MIN_DAYS);
1147        for days in MIN_DAYS + 1..=MAX_DAYS {
1148            let date = Date::from_days_since_epoch(days);
1149            assert_eq!(Date::new(date.year, date.month, date.day), Ok(date));
1150            assert!(previous < date, "{previous} {date}");
1151            assert_eq!(date.days_since_epoch(), days, "{date}");
1152            previous = date;
1153        }
1154        assert_eq!(previous, Date::new(9999, 12, 31).unwrap());
1155    }
1156
1157    #[test]
1158    fn a_date_string_in_code_gives_days_from_a_start() {
1159        let start: Date = "2026-05-14".parse().unwrap();
1160        assert_eq!(start.start_of("2026-06-01"), 18.0);
1161        assert_eq!(start.start_of("2026-05-01"), -13.0);
1162        assert_eq!(start.end_of("2026-08-05"), 84.0);
1163    }
1164
1165    #[test]
1166    #[should_panic(expected = "day 30 is not 1 to 28")]
1167    fn a_bad_date_string_in_code_panics_with_the_reason() {
1168        let _ = Date::new(2026, 5, 14).unwrap().start_of("2026-02-30");
1169    }
1170
1171    #[test]
1172    fn dates_stay_in_four_digit_years() {
1173        let (min, max) = (
1174            Date::new(0, 1, 1).unwrap(),
1175            Date::new(9999, 12, 31).unwrap(),
1176        );
1177        assert_eq!(min.checked_plus_days(-1), None);
1178        assert_eq!(max.checked_plus_days(1), None);
1179        assert_eq!(min.checked_plus_days(MAX_DAYS - MIN_DAYS), Some(max));
1180        assert_eq!(min.checked_plus_days(i64::MAX), None);
1181        assert_eq!(max.checked_plus_days(i64::MIN), None);
1182    }
1183
1184    #[test]
1185    fn a_time_falls_on_the_date_of_its_whole_day() {
1186        let start: Date = "2026-05-14".parse().unwrap();
1187        let date = |t: f64| start.date_at(t).map(|d| d.to_string());
1188        assert_eq!(date(0.0).as_deref(), Some("2026-05-14"));
1189        assert_eq!(date(18.99).as_deref(), Some("2026-06-01"));
1190        assert_eq!(date(-0.5).as_deref(), Some("2026-05-13"));
1191        assert_eq!(date(1e7), None);
1192        assert_eq!(date(f64::NAN), None);
1193        assert_eq!(date(f64::NEG_INFINITY), None);
1194    }
1195
1196    #[test]
1197    fn the_context_gives_the_date_of_the_current_time() {
1198        let mut context = Context::new();
1199        assert_eq!(context.get_current_date(), None);
1200        context.set_start_date(Some("2026-05-14".parse().unwrap()));
1201        context.add_plan(18.5, |context| {
1202            assert_eq!(
1203                context.get_current_date().unwrap().to_string(),
1204                "2026-06-01"
1205            );
1206            context.set_start_date(None);
1207            assert_eq!(context.get_current_date(), None);
1208        });
1209        context.execute();
1210
1211        // As a report column.
1212        let mut csv = csv::Writer::from_writer(Vec::new());
1213        csv.serialize(("2026-06-01".parse::<Date>().unwrap(), 3))
1214            .unwrap();
1215        assert_eq!(csv.into_inner().unwrap(), b"2026-06-01,3\n");
1216    }
1217
1218    #[test]
1219    fn dates_and_days_round_trip_through_bincode() {
1220        let config = bincode_next::config::standard();
1221        let date: Date = "2026-05-14".parse().unwrap();
1222        for day in [Day::DaysFromStart(2.5), Day::CalendarDate(date)] {
1223            let bytes = bincode_next::serde::encode_to_vec(day, config).unwrap();
1224            let (back, _): (Day, _) =
1225                bincode_next::serde::decode_from_slice(&bytes, config).unwrap();
1226            assert_eq!(back, day);
1227        }
1228        let bytes = bincode_next::serde::encode_to_vec(date, config).unwrap();
1229        let (back, _): (Date, _) = bincode_next::serde::decode_from_slice(&bytes, config).unwrap();
1230        assert_eq!(back, date);
1231    }
1232
1233    #[test]
1234    fn invalid_dates_are_rejected() {
1235        for text in [
1236            "2026-02-30",
1237            "2026-13-01",
1238            "2026-5-14",
1239            "26-05-14",
1240            "2026-05-14T00:00",
1241            "May 14",
1242            "2026-+5-14",
1243            "+999-05-14",
1244            "+2026-05-14",
1245            "20260514",
1246            " 2026-05-14",
1247            "2026-05-14\n",
1248            "10000-01-01",
1249            "",
1250        ] {
1251            assert!(text.parse::<Date>().is_err(), "{text}");
1252        }
1253        assert!(Date::new(2024, 2, 29).is_ok());
1254        assert!(Date::new(2023, 2, 29).is_err());
1255        assert!(Date::new(1900, 2, 29).is_err());
1256        assert!(Date::new(0, 2, 29).is_ok());
1257        assert!(Date::new(-1, 1, 1).is_err());
1258        assert!(Date::new(10000, 1, 1).is_err());
1259        let err = "2026-02-30".parse::<Date>().unwrap_err().to_string();
1260        assert!(err.contains("day 30 is not 1 to 28"), "{err}");
1261    }
1262
1263    #[test]
1264    fn a_day_reads_days_a_date_or_a_native_toml_date() {
1265        let start: Date = "2026-05-14".parse().unwrap();
1266        let days: Day = serde_json::from_value(json!(2.5)).unwrap();
1267        assert_eq!(days, Day::DaysFromStart(2.5));
1268        assert_eq!(days.resolve(cx(None), inclusive(false)).unwrap(), 2.5);
1269        let date: Day = serde_json::from_value(json!("2026-06-01")).unwrap();
1270        assert_eq!(
1271            date.resolve(cx(Some(start)), inclusive(false)).unwrap(),
1272            18.0
1273        );
1274        assert_eq!(
1275            date.resolve(cx(Some(start)), inclusive(true)).unwrap(),
1276            19.0
1277        );
1278        assert_eq!(
1279            date.resolve(cx(None), inclusive(false))
1280                .unwrap_err()
1281                .to_string(),
1282            "2026-06-01 is a date, but there is no start date"
1283        );
1284        let toml: Day = serde_json::from_value(json!({TOML_DATETIME: "2026-06-01"})).unwrap();
1285        assert_eq!(toml, date);
1286        let err = serde_json::from_value::<Day>(json!("2026-02-30"))
1287            .unwrap_err()
1288            .to_string();
1289        assert!(err.contains("day 30 is not 1 to 28"), "{err}");
1290
1291        assert_eq!(
1292            Day::from_days(18.0, cx(Some(start)), inclusive(false)),
1293            date
1294        );
1295        assert_eq!(Day::from_days(19.0, cx(Some(start)), inclusive(true)), date);
1296        assert_eq!(Day::from_days(2.5, cx(Some(start)), inclusive(false)), days);
1297        assert_eq!(
1298            Day::from_days(18.0, cx(None), inclusive(false)),
1299            Day::DaysFromStart(18.0)
1300        );
1301        assert_eq!(
1302            Day::from_days(1e12, cx(Some(start)), inclusive(false)),
1303            Day::DaysFromStart(1e12)
1304        );
1305        assert_eq!(
1306            Day::from_days(3e6, cx(Some(start)), inclusive(false)),
1307            Day::DaysFromStart(3e6)
1308        );
1309        assert!(matches!(
1310            Day::from_days(f64::NAN, cx(Some(start)), inclusive(false)),
1311            Day::DaysFromStart(d) if d.is_nan()
1312        ));
1313        assert_eq!(serde_json::to_value(date).unwrap(), json!("2026-06-01"));
1314        assert_eq!(serde_json::to_value(days).unwrap(), json!(2.5));
1315
1316        assert!(days < Day::DaysFromStart(3.0));
1317        assert!(date < Day::CalendarDate(start.checked_plus_days(19).unwrap()));
1318        assert_eq!(days.partial_cmp(&date), None);
1319    }
1320
1321    fn week(s: &str) -> Week {
1322        s.parse().unwrap()
1323    }
1324
1325    #[test]
1326    fn weekdays() {
1327        assert_eq!(date("1970-01-01").weekday(), Weekday::Thursday);
1328        assert_eq!(date("2000-01-01").weekday(), Weekday::Saturday);
1329        assert_eq!(date("2026-10-20").weekday(), Weekday::Tuesday);
1330        assert_eq!(date("0000-01-01").weekday(), Weekday::Saturday);
1331        assert_eq!(serde_json::to_value(Weekday::Sunday).unwrap(), json!("Sun"));
1332        for day in Weekday::ALL {
1333            assert_eq!(
1334                serde_json::from_value::<Weekday>(json!(day.to_string())).unwrap(),
1335                day
1336            );
1337        }
1338        for text in ["sun", "Sunday", "", "Sun "] {
1339            assert!(text.parse::<Weekday>().is_err(), "{text}");
1340        }
1341
1342        // A report row with a weekday column reads back.
1343        let mut csv = csv::Writer::from_writer(Vec::new());
1344        csv.serialize((Weekday::Tuesday, 3)).unwrap();
1345        let bytes = csv.into_inner().unwrap();
1346        let mut reader = csv::ReaderBuilder::new()
1347            .has_headers(false)
1348            .from_reader(&bytes[..]);
1349        let row: (Weekday, u32) = reader.deserialize().next().unwrap().unwrap();
1350        assert_eq!(row, (Weekday::Tuesday, 3));
1351        let config = bincode_next::config::standard();
1352        let bytes = bincode_next::serde::encode_to_vec(Weekday::Friday, config).unwrap();
1353        let (back, _): (Weekday, _) =
1354            bincode_next::serde::decode_from_slice(&bytes, config).unwrap();
1355        assert_eq!(back, Weekday::Friday);
1356    }
1357
1358    /// The weeks on either side of New Year, where ISO and epi weeks disagree.
1359    #[test]
1360    fn iso_and_epi_weeks_near_new_year() {
1361        for (day, iso, epi) in [
1362            ("2024-12-29", "2024-W52", "2025-W01"),
1363            ("2025-12-28", "2025-W52", "2025-W53"),
1364            ("2026-01-01", "2026-W01", "2025-W53"),
1365            ("2026-01-04", "2026-W01", "2026-W01"),
1366            ("2026-10-20", "2026-W43", "2026-W42"),
1367            ("2027-01-01", "2026-W53", "2026-W52"),
1368            ("2021-01-02", "2020-W53", "2020-W53"),
1369        ] {
1370            assert_eq!(date(day).week(WeekSystem::Iso), Some(week(iso)), "{day}");
1371            assert_eq!(date(day).week(WeekSystem::Epi), Some(week(epi)), "{day}");
1372        }
1373        assert_eq!(date("0000-01-01").week(WeekSystem::Iso), None);
1374        assert_eq!(
1375            date("0000-01-02").week(WeekSystem::Epi),
1376            Some(week("0000-W01"))
1377        );
1378        assert_eq!(WeekSystem::Iso.weeks_in(2026), 53);
1379        assert_eq!(WeekSystem::Epi.weeks_in(2026), 52);
1380        assert_eq!(WeekSystem::Epi.weeks_in(2025), 53);
1381        for year in [i32::MIN, i32::MAX] {
1382            assert!((52..=53).contains(&WeekSystem::Iso.weeks_in(year)));
1383        }
1384        assert_eq!(
1385            week("2025-W01").first_day(WeekSystem::Epi),
1386            Ok(date("2024-12-29"))
1387        );
1388        assert_eq!(
1389            week("2026-W53")
1390                .first_day(WeekSystem::Epi)
1391                .unwrap_err()
1392                .to_string(),
1393            "2026-W53: 2026 has 52 epi weeks"
1394        );
1395    }
1396
1397    /// Every day falls in a week that starts on the right weekday at most
1398    /// six days before it, and weeks count up by one or restart at 1. Only
1399    /// the days of year 0 whose week belongs to year -1 have none.
1400    #[test]
1401    fn every_day_is_in_its_week() {
1402        for (system, weekday) in [
1403            (WeekSystem::Iso, Weekday::Monday),
1404            (WeekSystem::Epi, Weekday::Sunday),
1405        ] {
1406            let mut days = MIN_DAYS;
1407            while Date::from_days_since_epoch(days).week(system).is_none() {
1408                days += 1;
1409            }
1410            assert!(days - MIN_DAYS < 7, "{system}");
1411            let mut previous = Date::from_days_since_epoch(days).week(system).unwrap();
1412            for days in days..=MAX_DAYS {
1413                let date = Date::from_days_since_epoch(days);
1414                let week = date.week(system).unwrap();
1415                let first = week.first_day(system).unwrap();
1416                assert_eq!(first.weekday(), weekday, "{date}");
1417                assert!((0..7).contains(&first.days_until(date)), "{date} {week}");
1418                assert!(week.number() <= system.weeks_in(week.year()), "{date}");
1419                if week != previous {
1420                    let next = Week::new(previous.year, previous.week + 1);
1421                    let rolled = previous.week == system.weeks_in(previous.year)
1422                        && week == Week::new(previous.year + 1, 1).unwrap();
1423                    assert!(next == Ok(week) || rolled, "{previous} {week}");
1424                }
1425                previous = week;
1426            }
1427        }
1428    }
1429
1430    #[test]
1431    fn weeks_parse_and_print() {
1432        assert_eq!(week("2026-W07").to_string(), "2026-W07");
1433        assert_eq!(
1434            (week("2026-W07").year(), week("2026-W07").number()),
1435            (2026, 7)
1436        );
1437        for text in [
1438            "2026-W7",
1439            "2026-W00",
1440            "2026-W54",
1441            "2026W07",
1442            "26-W07",
1443            "2026-w07",
1444            "2026-W07 ",
1445            "",
1446        ] {
1447            assert!(text.parse::<Week>().is_err(), "{text}");
1448        }
1449        let config = bincode_next::config::standard();
1450        let bytes = bincode_next::serde::encode_to_vec(week("2026-W07"), config).unwrap();
1451        let (back, _): (Week, _) = bincode_next::serde::decode_from_slice(&bytes, config).unwrap();
1452        assert_eq!(back, week("2026-W07"));
1453    }
1454
1455    #[test]
1456    fn a_week_string_in_code_gives_days_from_a_start() {
1457        let start = date("2026-05-14");
1458        assert_eq!(start.start_of_week("2026-W27", WeekSystem::Epi), 52.0);
1459        assert_eq!(start.end_of_week("2026-W27", WeekSystem::Epi), 59.0);
1460        assert_eq!(start.start_of_week("2026-W27", WeekSystem::Iso), 46.0);
1461    }
1462
1463    #[test]
1464    fn days_take_units() {
1465        let days = |s: &str| match s.parse::<Day>() {
1466            Ok(Day::DaysFromStart(d)) => Ok(d),
1467            Ok(other) => panic!("{s}: {other:?}"),
1468            Err(e) => Err(e.to_string()),
1469        };
1470        for (text, value) in [
1471            ("2w", 14.0),
1472            ("14d", 14.0),
1473            ("1w 2d", 9.0),
1474            ("1w2d", 9.0),
1475            ("36h", 1.5),
1476            ("0.5w", 3.5),
1477            ("1.5 days", 1.5),
1478            ("2 weeks", 14.0),
1479            ("-1w", -7.0),
1480            ("- 3d", -3.0),
1481        ] {
1482            assert_eq!(days(text), Ok(value), "{text}");
1483        }
1484        let huge = format!("{}w", "9".repeat(400));
1485        for text in ["3", "", "-", "w", "3x", "3d 2", "1.2.3d", "+3d", &huge] {
1486            assert!(
1487                days(text).unwrap_err().contains("days with units"),
1488                "{text}"
1489            );
1490        }
1491        for text in ["1month", "2y", "1 year"] {
1492            assert!(
1493                days(text).unwrap_err().contains("no fixed length"),
1494                "{text}"
1495            );
1496        }
1497        assert!(days("2026-5-14").unwrap_err().contains("is not a date"));
1498        assert_eq!(
1499            "2026-W12".parse::<Day>(),
1500            Ok(Day::CalendarWeek(week("2026-W12")))
1501        );
1502    }
1503
1504    #[test]
1505    fn a_week_resolves_to_its_first_day_or_its_end() {
1506        let epi = CalendarContext {
1507            start: Some(date("2026-05-14")),
1508            weeks: Some(WeekSystem::Epi),
1509        };
1510        let point = FieldOptions::default();
1511        let w27 = Day::CalendarWeek(week("2026-W27"));
1512        assert_eq!(w27.resolve(epi, point), Ok(52.0));
1513        assert_eq!(w27.resolve(epi, inclusive(true)), Ok(59.0));
1514        assert_eq!(
1515            w27.resolve(CalendarContext { weeks: None, ..epi }, point).unwrap_err().to_string(),
1516            "2026-W27 is a week, but no week system is set: add `weeks = \"iso\"` or `weeks = \"epi\"` to `#[calendar]`"
1517        );
1518        let no_start = w27.resolve(CalendarContext { start: None, ..epi }, point);
1519        assert_eq!(no_start, Err(CalendarError::NoStartDate(w27)));
1520        assert_eq!(
1521            no_start.unwrap_err().to_string(),
1522            "2026-W27 is a week, but there is no start date"
1523        );
1524        assert!(Day::CalendarWeek(week("2026-W53"))
1525            .resolve(epi, point)
1526            .is_err());
1527
1528        let weekly = FieldOptions {
1529            write_week: true,
1530            ..point
1531        };
1532        assert_eq!(Day::from_days(52.0, epi, weekly), w27);
1533        assert_eq!(
1534            Day::from_days(
1535                59.0,
1536                epi,
1537                FieldOptions {
1538                    inclusive: true,
1539                    ..weekly
1540                }
1541            ),
1542            w27
1543        );
1544        assert_eq!(
1545            Day::from_days(53.0, epi, weekly),
1546            Day::CalendarDate(date("2026-07-06"))
1547        );
1548        assert_eq!(
1549            Day::from_days(52.0, epi, point),
1550            Day::CalendarDate(date("2026-07-05"))
1551        );
1552        assert_eq!(serde_json::to_value(w27).unwrap(), json!("2026-W27"));
1553    }
1554
1555    #[test]
1556    fn a_duration_takes_units_but_no_dates_or_weeks() {
1557        let cx = CalendarContext {
1558            start: Some(date("2026-05-14")),
1559            weeks: Some(WeekSystem::Iso),
1560        };
1561        let duration = FieldOptions {
1562            duration: true,
1563            ..FieldOptions::default()
1564        };
1565        assert_eq!("2w".parse::<Day>().unwrap().resolve(cx, duration), Ok(14.0));
1566        let june = Day::CalendarDate(date("2026-06-01"));
1567        assert_eq!(
1568            june.resolve(cx, duration),
1569            Err(CalendarError::NotADuration(june))
1570        );
1571        assert_eq!(
1572            june.resolve(cx, duration).unwrap_err().to_string(),
1573            "a duration cannot be the date 2026-06-01"
1574        );
1575        assert_eq!(
1576            Day::CalendarWeek(week("2026-W01"))
1577                .resolve(cx, duration)
1578                .unwrap_err()
1579                .to_string(),
1580            "a duration cannot be the week 2026-W01"
1581        );
1582        assert_eq!(
1583            Day::DaysFromStart(-3.0).resolve(cx, duration),
1584            Err(CalendarError::InvalidDuration(-3.0))
1585        );
1586        assert_eq!(
1587            CalendarError::InvalidDuration(-3.0).to_string(),
1588            "a duration cannot be negative: -3"
1589        );
1590        assert_eq!(
1591            CalendarError::InvalidDuration(f64::NAN).to_string(),
1592            "a duration cannot be NaN"
1593        );
1594        let signed = FieldOptions {
1595            signed: true,
1596            ..duration
1597        };
1598        assert_eq!(Day::DaysFromStart(-3.0).resolve(cx, signed), Ok(-3.0));
1599        for field in [duration, signed] {
1600            assert!(Day::DaysFromStart(f64::NAN).resolve(cx, field).is_err());
1601            assert_eq!(
1602                Day::DaysFromStart(f64::INFINITY).resolve(cx, field),
1603                Ok(f64::INFINITY)
1604            );
1605        }
1606        assert_eq!(Day::from_days(18.0, cx, duration), Day::DaysFromStart(18.0));
1607    }
1608
1609    #[test]
1610    fn the_context_gives_the_week_of_the_current_time() {
1611        let mut context = Context::new();
1612        context.set_start_date(date("2026-05-14"));
1613        assert_eq!(context.get_current_week(), None);
1614        context.set_week_system(WeekSystem::Epi);
1615        assert_eq!(context.get_week_system(), Some(WeekSystem::Epi));
1616        context.add_plan(52.5, |context| {
1617            assert_eq!(context.get_current_week(), Some(week("2026-W27")));
1618        });
1619        context.execute();
1620
1621        let mut csv = csv::Writer::from_writer(Vec::new());
1622        csv.serialize((week("2026-W27"), Weekday::Sunday, 3))
1623            .unwrap();
1624        assert_eq!(csv.into_inner().unwrap(), b"2026-W27,Sun,3\n");
1625    }
1626}