Skip to main content

relate_core/temporal/
between.rs

1//! Temporal difference (`duration.between` and its per-unit form): classify
2//! the operand pair once into a comparison domain, then shape the difference
3//! per unit. Split from [`super::arith`] so the additive/scaling family and
4//! the between family each own one job.
5//!
6//! Every computation over a user-controlled magnitude goes through checked
7//! arithmetic or chrono's `try_*` / `checked_*` constructors and returns
8//! `Err(Error::ty(..))` on out-of-range results. Nothing in this module may
9//! panic on query input.
10
11use chrono::{Datelike, Duration as ChronoDur, NaiveDateTime, NaiveTime};
12
13use crate::{Error, Result};
14
15use super::arith::{add_months, checked_add_dur};
16use super::zone::{add_offset, sub_offset, zone_offset_at, zone_region};
17use super::{civil_epoch_days, range_err, time_to_nanos, utc_time_nanos, Temporal, NANOS_PER_DAY};
18
19fn utc_in_zone(local: NaiveDateTime, zone: &str) -> Option<NaiveDateTime> {
20    // The single-or-earliest rule is the exported resolver (ADR-0178); its
21    // gap/unknown-zone outcomes collapse to this path's `None`, and the
22    // checked subtraction keeps an out-of-range `local - offset` a `None`.
23    let offset = zone_offset_at(zone, local).ok()?;
24    sub_offset(local, offset).ok()
25}
26
27/// `t` read at the zone the pair classified (`zone`), anchored to `ctx`'s
28/// wall date when `t` is a bare time of day.
29fn as_utc_instant(t: &Temporal, ctx: &Temporal, zone: &str) -> Option<NaiveDateTime> {
30    match t {
31        Temporal::DateTime { utc, .. } => Some(*utc),
32        Temporal::Date(d) => utc_in_zone(d.and_time(NaiveTime::MIN), zone),
33        Temporal::LocalDateTime(dt) => utc_in_zone(*dt, zone),
34        Temporal::LocalTime(tm) => utc_in_zone(wall_dt(ctx)?.date().and_time(*tm), zone),
35        Temporal::Time { time, offset } => {
36            let local = wall_dt(ctx)?.date().and_time(*time);
37            // checked_neg: a user-parsed offset can be exactly i32::MIN, and
38            // that reading stays a typed no-reading error (pinned by
39            // `temporal_arith_out_of_range_errors_not_panics`).
40            add_offset(local, offset.checked_neg()?).ok()
41        }
42        Temporal::Duration { .. } | Temporal::CivilDate { .. } | Temporal::CivilDateTime { .. } => {
43            None
44        }
45    }
46}
47
48fn wall_dt(t: &Temporal) -> Option<NaiveDateTime> {
49    match t {
50        Temporal::Date(d) => Some(d.and_time(NaiveTime::MIN)),
51        Temporal::LocalDateTime(dt) => Some(*dt),
52        Temporal::CivilDate { .. } | Temporal::CivilDateTime { .. } => None,
53        Temporal::DateTime { utc, offset, .. } => add_offset(*utc, *offset).ok(),
54        _ => None,
55    }
56}
57
58fn utc_dt(t: &Temporal) -> Option<NaiveDateTime> {
59    match t {
60        Temporal::DateTime { utc, .. } => Some(*utc),
61        other => wall_dt(other),
62    }
63}
64
65fn time_nanos_of(t: &Temporal, as_utc: bool) -> Option<i64> {
66    match t {
67        Temporal::LocalTime(tm) => Some(time_to_nanos(*tm)),
68        Temporal::Time { time, offset } => Some(if as_utc {
69            utc_time_nanos(*time, *offset)
70        } else {
71            time_to_nanos(*time)
72        }),
73        Temporal::Date(_) => Some(0),
74        Temporal::LocalDateTime(dt) => Some(time_to_nanos(dt.time())),
75        Temporal::DateTime { utc, offset, .. } => {
76            if as_utc {
77                Some(time_to_nanos(utc.time()))
78            } else {
79                let local = add_offset(*utc, *offset).ok()?;
80                Some(time_to_nanos(local.time()))
81            }
82        }
83        Temporal::Duration { .. } => None,
84        Temporal::CivilDate { .. } => Some(0),
85        Temporal::CivilDateTime { time, .. } => Some(time_to_nanos(*time)),
86    }
87}
88
89/// `t` overshot `db` when stepping away from `da`: the tentative result
90/// landed on the far side of `db` in the direction of travel.
91fn overshot(da: NaiveDateTime, db: NaiveDateTime, t: NaiveDateTime) -> bool {
92    if db >= da {
93        t > db
94    } else {
95        t < db
96    }
97}
98
99/// The exact i128 nanosecond difference between two in-chrono-range
100/// datetimes, read as whole calendar days plus within-day nanos: two chrono
101/// datetimes can differ by more than i64 nanoseconds (±262143 years
102/// ≈ ±8.8e21 ns), where `TimeDelta::num_nanoseconds` returns `None`.
103fn nanos_between(da: NaiveDateTime, db: NaiveDateTime) -> i128 {
104    i128::from((db.date() - da.date()).num_days()) * NANOS_PER_DAY
105        + i128::from(time_to_nanos(db.time()))
106        - i128::from(time_to_nanos(da.time()))
107}
108
109/// One difference in the producer's own terms: the calendar decomposition
110/// (`months`, then `days`, then sub-day `nanos`) that `Full` and `Months`
111/// read, and the whole-span `span_days` / `span_nanos` that `Days` and
112/// `Seconds` read. Each producer computes every field once; only
113/// [`shaped_duration`] selects, so no producer pre-projects for a unit.
114struct BetweenFields {
115    months: i64,
116    /// Producer-bounded: a within-month adjusted day count
117    /// ([`calendar_between`]) or a day-of-month difference ([`civil_fields`]),
118    /// so it fits `i64` by construction. The unbounded magnitude is
119    /// `span_days`, range-checked only when the `Days` unit keeps it.
120    days: i64,
121    nanos: i128,
122    span_days: i128,
123    span_nanos: i128,
124}
125
126impl BetweenFields {
127    /// A difference that is entirely sub-day nanoseconds (the time-of-day
128    /// domain): no months, no whole days.
129    fn from_nanos(nanos: i128) -> Self {
130        Self {
131            months: 0,
132            days: 0,
133            nanos,
134            span_days: 0,
135            span_nanos: nanos,
136        }
137    }
138}
139
140/// Shape a [`BetweenFields`] per `unit`: `Full` keeps the calendar
141/// decomposition, `Months` the month count, `Days` the whole-span day count,
142/// `Seconds` the whole-span nanosecond count. The one place the per-unit
143/// `Duration` shaping lives; the assembly goes through
144/// [`Temporal::duration_checked`], so a between result cannot exceed the
145/// duration representability bound either.
146fn shaped_duration(fields: BetweenFields, unit: BetweenUnit) -> Result<Temporal> {
147    // `span_days` is the unbounded magnitude (a civil span over unbounded
148    // i64 years), range-checked against the day bound only when the `Days`
149    // unit keeps it.
150    let (months, days, nanos) = match unit {
151        BetweenUnit::Full => (fields.months, fields.days, fields.nanos),
152        BetweenUnit::Months => (fields.months, 0, 0),
153        BetweenUnit::Days => (
154            0,
155            i64::try_from(fields.span_days).map_err(|_| range_err())?,
156            0,
157        ),
158        BetweenUnit::Seconds => (0, 0, fields.span_nanos),
159    };
160    Temporal::duration_checked(months, days, nanos)
161}
162
163/// The calendar difference between two in-chrono-range datetimes: months and
164/// days adjusted so the remainder is under one month and one day
165/// respectively, the sub-day remainder, and the whole-span day and
166/// nanosecond counts.
167fn calendar_between(da: NaiveDateTime, db: NaiveDateTime) -> Result<BetweenFields> {
168    // Chrono-range years are i32-bounded, so this difference cannot overflow.
169    let months =
170        i64::from(db.year() - da.year()) * 12 + i64::from(db.month()) - i64::from(da.month());
171    let step = if db >= da { 1 } else { -1 };
172    let mut adj_months = months;
173    let tentative = add_months(da, adj_months)?;
174    if overshot(da, db, tentative) {
175        adj_months -= step;
176    }
177    let after_m = add_months(da, adj_months)?;
178    let days = (db.date() - after_m.date()).num_days();
179    let mut adj_days = days;
180    let after_d = checked_add_dur(after_m, ChronoDur::try_days(adj_days))?;
181    if overshot(da, db, after_d) {
182        adj_days -= step;
183    }
184    let after_d = checked_add_dur(after_m, ChronoDur::try_days(adj_days))?;
185    // `after_d` is within a day of `db`.
186    Ok(BetweenFields {
187        months: adj_months,
188        days: adj_days,
189        nanos: nanos_between(after_d, db),
190        span_days: i128::from((db - da).num_days()),
191        span_nanos: nanos_between(da, db),
192    })
193}
194
195pub fn duration_between(a: &Temporal, b: &Temporal) -> Result<Temporal> {
196    duration_between_unit(a, b, BetweenUnit::Full)
197}
198
199#[derive(Clone, Copy)]
200pub enum BetweenUnit {
201    Full,
202    Months,
203    Days,
204    Seconds,
205}
206
207/// A civil value's parts: the unbounded i64 year, month, day, and the
208/// within-day nanosecond count, named so call sites cannot swap fields.
209#[derive(Clone, Copy)]
210struct CivilParts {
211    year: i64,
212    month: u32,
213    day: u32,
214    nanos: i64,
215}
216
217fn civil_parts(t: &Temporal) -> Option<CivilParts> {
218    match t {
219        Temporal::CivilDate { year, month, day } => Some(CivilParts {
220            year: *year,
221            month: *month,
222            day: *day,
223            nanos: 0,
224        }),
225        Temporal::CivilDateTime {
226            year,
227            month,
228            day,
229            time,
230        } => Some(CivilParts {
231            year: *year,
232            month: *month,
233            day: *day,
234            nanos: time_to_nanos(*time),
235        }),
236        Temporal::Date(d) => Some(CivilParts {
237            year: i64::from(d.year()),
238            month: d.month(),
239            day: d.day(),
240            nanos: 0,
241        }),
242        Temporal::LocalDateTime(dt) => Some(CivilParts {
243            year: i64::from(dt.year()),
244            month: dt.month(),
245            day: dt.day(),
246            nanos: time_to_nanos(dt.time()),
247        }),
248        _ => None,
249    }
250}
251
252/// Whether `t` is a genuinely civil value (unbounded i64 years).
253fn is_civil(t: &Temporal) -> bool {
254    matches!(
255        t,
256        Temporal::CivilDate { .. } | Temporal::CivilDateTime { .. }
257    )
258}
259
260/// The civil parts of both operands when they are date-like and at least one
261/// is a genuinely civil value (unbounded i64 years); `None` leaves the pair
262/// to the chrono/zone domains below.
263fn civil_parts_pair(a: &Temporal, b: &Temporal) -> Option<(CivilParts, CivilParts)> {
264    if !is_civil(a) && !is_civil(b) {
265        return None;
266    }
267    Some((civil_parts(a)?, civil_parts(b)?))
268}
269
270/// The civil difference in the same shape [`calendar_between`] produces: the
271/// day-of-month difference is the `Full` day field (civil values carry no
272/// month-relative day breakdown), and the whole-span day count feeds `Days`
273/// and `Seconds`.
274fn civil_fields(a: CivilParts, b: CivilParts) -> Result<BetweenFields> {
275    // Civil years are unbounded i64; compute in i128 and error when the
276    // result does not fit the Duration fields.
277    let months =
278        (i128::from(b.year) - i128::from(a.year)) * 12 + i128::from(b.month) - i128::from(a.month);
279    let months = i64::try_from(months).map_err(|_| range_err())?;
280    let span_days =
281        civil_epoch_days(b.year, b.month, b.day) - civil_epoch_days(a.year, a.month, a.day);
282    let nanos = i128::from(b.nanos) - i128::from(a.nanos);
283    Ok(BetweenFields {
284        months,
285        days: i64::from(b.day) - i64::from(a.day),
286        nanos,
287        span_days,
288        // Fits i128 for any i64 year (~5.8e35 ns at ±i64::MAX years).
289        span_nanos: span_days * NANOS_PER_DAY + nanos,
290    })
291}
292
293/// The exact civil difference shaped per `unit`.
294fn civil_duration(a: CivilParts, b: CivilParts, unit: BetweenUnit) -> Result<Temporal> {
295    shaped_duration(civil_fields(a, b)?, unit)
296}
297
298/// The one classification of the operand pair that selects the comparison
299/// domain (F-1-3): every predicate is evaluated exactly once here, and
300/// `duration_between_unit` matches on the outcome instead of re-deriving it.
301enum PairDomain<'a> {
302    /// Both operands are date-like and at least one is a genuinely civil
303    /// value (unbounded i64 years): the exact i128 difference.
304    Civil { a: CivilParts, b: CivilParts },
305    /// At least one operand is a time of day: compare within-day nanos, read
306    /// at UTC when both operands are zoned (`as_utc`). `both_times` marks a
307    /// pair with no date at all, whose month- and day-sized units are
308    /// undefined.
309    TimeOnly { as_utc: bool, both_times: bool },
310    /// Compare at `zone`, the pair's first IANA region, anchored to `ctx`'s
311    /// wall date for a bare time of day.
312    Zoned { zone: &'a str, ctx: &'a Temporal },
313    /// Both operands are zoned without an IANA region: compare UTC instants.
314    Instant,
315    /// Neither operand is zoned: compare naive wall clocks.
316    Wall,
317}
318
319/// An operand's comparison shape, classified once per operand so the pair
320/// match never re-probes the value.
321enum OperandShape<'a> {
322    /// A time of day; `zoned` distinguishes `Temporal::Time` (an
323    /// offset-carrying time) from `Temporal::LocalTime`.
324    Time { zoned: bool },
325    /// A `Temporal::DateTime`; `zone` is the IANA region it names, if any.
326    DateTime { zone: Option<&'a str> },
327    /// A date, local datetime, civil value or duration.
328    Other,
329}
330
331fn operand_shape(t: &Temporal) -> OperandShape<'_> {
332    match t {
333        Temporal::LocalTime(_) => OperandShape::Time { zoned: false },
334        Temporal::Time { .. } => OperandShape::Time { zoned: true },
335        Temporal::DateTime { zone, .. } => OperandShape::DateTime {
336            zone: zone_region(zone.as_deref()),
337        },
338        Temporal::Date(_)
339        | Temporal::CivilDate { .. }
340        | Temporal::LocalDateTime(_)
341        | Temporal::CivilDateTime { .. }
342        | Temporal::Duration { .. } => OperandShape::Other,
343    }
344}
345
346fn pair_domain<'a>(a: &'a Temporal, b: &'a Temporal) -> PairDomain<'a> {
347    if let Some((a_parts, b_parts)) = civil_parts_pair(a, b) {
348        return PairDomain::Civil {
349            a: a_parts,
350            b: b_parts,
351        };
352    }
353    use OperandShape::*;
354    match (operand_shape(a), operand_shape(b)) {
355        // Both time-of-day: within-day nanos, read at UTC when both zoned.
356        (Time { zoned: za }, Time { zoned: zb }) => PairDomain::TimeOnly {
357            as_utc: za && zb,
358            both_times: true,
359        },
360        // A time of day against a non-IANA datetime: the nanos are read at
361        // UTC when the time side is `Temporal::Time` (the datetime side is
362        // always zoned).
363        (Time { zoned }, DateTime { zone: None }) | (DateTime { zone: None }, Time { zoned }) => {
364            PairDomain::TimeOnly {
365                as_utc: zoned,
366                both_times: false,
367            }
368        }
369        // A time of day against a date-like value: never at UTC.
370        (Time { .. }, Other) | (Other, Time { .. }) => PairDomain::TimeOnly {
371            as_utc: false,
372            both_times: false,
373        },
374        // An IANA-zoned datetime reads the pair at its zone; the first
375        // operand wins when both name one.
376        (DateTime { zone: Some(zone) }, _) => PairDomain::Zoned { zone, ctx: a },
377        (_, DateTime { zone: Some(zone) }) => PairDomain::Zoned { zone, ctx: b },
378        // Both sides zoned without an IANA region: compare UTC instants.
379        (DateTime { zone: None }, DateTime { zone: None }) => PairDomain::Instant,
380        // The remaining pairs hold at most one zoned side: wall clocks.
381        (DateTime { zone: None }, Other) | (Other, DateTime { zone: None }) | (Other, Other) => {
382            PairDomain::Wall
383        }
384    }
385}
386
387/// Both operands mapped by `f`, or the `duration.between` type error when a
388/// value has no reading in the pair's domain. The one map-or-error step: the
389/// datetime resolvers and the time-of-day arm share it.
390fn map_pair<T>(a: &Temporal, b: &Temporal, f: impl Fn(&Temporal) -> Option<T>) -> Result<(T, T)> {
391    let map_one = |t: &Temporal| f(t).ok_or_else(between_err);
392    Ok((map_one(a)?, map_one(b)?))
393}
394
395/// Error returned when an operand has no reading in the pair's comparison
396/// domain (`duration.between`'s typed no-reading signal).
397fn between_err() -> Error {
398    Error::ty("duration.between")
399}
400
401/// Shape the difference between the pair's two resolved datetimes per `unit`.
402fn calendar_duration(da: NaiveDateTime, db: NaiveDateTime, unit: BetweenUnit) -> Result<Temporal> {
403    shaped_duration(calendar_between(da, db)?, unit)
404}
405
406pub fn duration_between_unit(a: &Temporal, b: &Temporal, unit: BetweenUnit) -> Result<Temporal> {
407    match pair_domain(a, b) {
408        PairDomain::Civil {
409            a: a_parts,
410            b: b_parts,
411        } => civil_duration(a_parts, b_parts, unit),
412        PairDomain::TimeOnly { as_utc, both_times } => {
413            let (a_nanos, b_nanos) = map_pair(a, b, |t| time_nanos_of(t, as_utc))?;
414            // Two times have no date at all, so a month- or day-sized unit
415            // is undefined between them; a time against a dated value keeps
416            // the zero-month/zero-day reading.
417            if both_times && matches!(unit, BetweenUnit::Months | BetweenUnit::Days) {
418                return Err(Error::ty("Unsupported unit for a pair of times"));
419            }
420            shaped_duration(
421                BetweenFields::from_nanos(i128::from(b_nanos) - i128::from(a_nanos)),
422                unit,
423            )
424        }
425        PairDomain::Zoned { zone, ctx } => {
426            let (da, db) = map_pair(a, b, |t| as_utc_instant(t, ctx, zone))?;
427            calendar_duration(da, db, unit)
428        }
429        PairDomain::Instant => {
430            let (da, db) = map_pair(a, b, utc_dt)?;
431            calendar_duration(da, db, unit)
432        }
433        PairDomain::Wall => {
434            let (da, db) = map_pair(a, b, wall_dt)?;
435            calendar_duration(da, db, unit)
436        }
437    }
438}