Skip to main content

i18n_next/format/
date.rs

1//! `Intl.DateTimeFormat` (DESIGN 5.3, 5.4, spikes S9 / S10): the pattern of every supported
2//! option combination was taken from Node's ICU by `scripts/cldr.mjs` and sits in the data
3//! (`build.rs` compiled it: `\x01`, the CLDR letter, the width digit per field); this module
4//! only picks the pattern and renders it. A date and a time are joined by the locale's glue
5//! of the date part's width, unless ICU joins that pair otherwise (an override).
6//!
7//! The instant is split in the zone (`tz`) as proleptic Gregorian, as V8 sets up ICU; years
8//! show as years of the era (2 BC for -1). U+202F of ICU is a space here, as in V8's
9//! `format()`.
10
11use super::data::{
12    self, DATE_B, DATE_NAMES, DATE_OVER, DATE_OVER_KEYS, DATE_PATS, DATE_TIMES, Loc,
13};
14use std::fmt;
15
16/// An instant for [`I18n::td`](crate::I18n::td) and [`I18n::tdr`](crate::I18n::tdr), held
17/// as a JS `Date` holds it: whole milliseconds since 1970-01-01 UTC, within ±8.64e15
18/// (±100 000 000 days). Anything else is an invalid date: it formats as `Invalid Date`.
19///
20/// From `i64` (milliseconds), `f64` (milliseconds, truncated like `new Date(ms)`; `NaN`
21/// is invalid), off `wasm32-unknown-unknown` `SystemTime`; with feature `time`
22/// `OffsetDateTime`, `UtcDateTime` and `PrimitiveDateTime` (as UTC). Sub-millisecond
23/// parts are cut toward zero, as for `SystemTime`.
24///
25/// ```
26/// use i18n_next::Timestamp;
27///
28/// assert_eq!(Timestamp::from(1.9), Timestamp::from(1i64));
29/// assert!(!Timestamp::from(f64::NAN).is_valid());
30/// assert!(!Timestamp::from(8_640_000_000_000_001i64).is_valid());
31/// assert_eq!(Timestamp::from(1_700_000_000_000i64).millis(), Some(1_700_000_000_000));
32/// ```
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34pub struct Timestamp(Option<i64>);
35
36/// ECMAScript `TimeClip`: ±8.64e15 ms.
37const MAX_MS: i64 = 8_640_000_000_000_000;
38
39impl Timestamp {
40    /// The milliseconds, `None` for an invalid date.
41    #[must_use]
42    pub fn millis(self) -> Option<i64> {
43        self.0
44    }
45
46    /// Whether the date is valid (JS `!isNaN(date)`).
47    #[must_use]
48    pub fn is_valid(self) -> bool {
49        self.0.is_some()
50    }
51}
52
53impl From<i64> for Timestamp {
54    fn from(ms: i64) -> Self {
55        Timestamp((-MAX_MS..=MAX_MS).contains(&ms).then_some(ms))
56    }
57}
58
59impl From<f64> for Timestamp {
60    #[allow(
61        clippy::cast_possible_truncation,
62        reason = "the range is checked first"
63    )]
64    fn from(ms: f64) -> Self {
65        // `TimeClip`: NaN and out of range are invalid, the rest truncated toward zero
66        if ms.abs() <= MAX_MS as f64 {
67            Timestamp(Some(ms.trunc() as i64))
68        } else {
69            Timestamp(None)
70        }
71    }
72}
73
74#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
75impl From<std::time::SystemTime> for Timestamp {
76    fn from(t: std::time::SystemTime) -> Self {
77        let ms = match t.duration_since(std::time::UNIX_EPOCH) {
78            Ok(d) => i64::try_from(d.as_millis()).ok(),
79            // before 1970: whole milliseconds toward zero, as `Date` reads them
80            Err(e) => i64::try_from(e.duration().as_millis()).ok().map(|m| -m),
81        };
82        ms.map_or(Timestamp(None), Timestamp::from)
83    }
84}
85
86/// Whole milliseconds toward zero of nanoseconds since 1970 (as `From<SystemTime>`).
87#[cfg(feature = "time")]
88fn from_nanos(ns: i128) -> Timestamp {
89    i64::try_from(ns / 1_000_000).map_or(Timestamp(None), Timestamp::from)
90}
91
92/// The instant of a `time` date-time with an offset (feature `time`).
93#[cfg(feature = "time")]
94impl From<time::OffsetDateTime> for Timestamp {
95    fn from(t: time::OffsetDateTime) -> Self {
96        from_nanos(t.unix_timestamp_nanos())
97    }
98}
99
100/// The instant of a `time` UTC date-time (feature `time`).
101#[cfg(feature = "time")]
102impl From<time::UtcDateTime> for Timestamp {
103    fn from(t: time::UtcDateTime) -> Self {
104        from_nanos(t.unix_timestamp_nanos())
105    }
106}
107
108/// A `time` date-time without an offset, read as UTC (feature `time`).
109#[cfg(feature = "time")]
110impl From<time::PrimitiveDateTime> for Timestamp {
111    fn from(t: time::PrimitiveDateTime) -> Self {
112        Timestamp::from(t.assume_utc())
113    }
114}
115
116/// The time zone of a format: with the `tz` feature the crate's own (IANA through the
117/// platform, `DESIGN 5.4`); without it only UTC.
118#[cfg(feature = "tz")]
119pub(crate) use crate::tz::Zone;
120
121#[cfg(feature = "tz")]
122use crate::tz::{Civil, civil_from_days, civil_from_unix, days_from_civil};
123
124/// UTC alone (the `tz` feature is off).
125#[cfg(not(feature = "tz"))]
126#[derive(Debug, Clone)]
127pub(crate) struct Zone;
128
129#[cfg(not(feature = "tz"))]
130impl Zone {
131    pub(crate) fn utc() -> Zone {
132        Zone
133    }
134
135    pub(crate) fn system() -> Zone {
136        Zone
137    }
138
139    #[allow(clippy::unused_self, reason = "the `tz` zone's signature")]
140    pub(crate) fn offset_at(&self, _: i64) -> i32 {
141        0
142    }
143
144    pub(crate) fn named(_: &str) -> Option<Zone> {
145        None
146    }
147}
148
149// The calendar arithmetic of `tz`, for a build without it.
150#[cfg(not(feature = "tz"))]
151#[path = "../tz/civil.rs"]
152mod civil;
153#[cfg(not(feature = "tz"))]
154use civil::{Civil, civil_from_days, civil_from_unix, days_from_civil};
155
156/// A zone by its IANA name as `Intl` takes it (`UTC`, `Etc/UTC`, `GMT` in any case are UTC),
157/// `None` when the platform has no such zone (JS throws a `RangeError`).
158pub(crate) fn zone_named(name: &str) -> Option<Zone> {
159    const UTC: [&str; 6] = ["UTC", "Etc/UTC", "GMT", "Etc/GMT", "Etc/UCT", "UCT"];
160    if UTC.iter().any(|u| u.eq_ignore_ascii_case(name)) {
161        return Some(Zone::utc());
162    }
163    Zone::named(name)
164}
165
166/// The ISO week year (`Y`): the year of the Thursday of the date's week. Out of line: only
167/// `gd`'s patterns read it, and inlined LLVM hoists its arithmetic into every render.
168#[inline(never)]
169fn week_year(c: &Civil) -> i64 {
170    let days = days_from_civil(c.year, c.month, c.day);
171    let monday_based = (i64::from(c.weekday) + 6) % 7;
172    civil_from_days(days - monday_based + 3).0
173}
174
175/// The hour cycle asked for: none (the locale's, table `j`), one of `h11` `h12` `h23` `h24`
176/// (tables `K` `h` `H` `k`), or `hour12` (the locale's 12- or 24-hour cycle).
177#[derive(Debug, Clone, Copy, PartialEq, Eq)]
178pub(crate) enum Cycle {
179    Locale,
180    H11,
181    H12,
182    H23,
183    H24,
184    Hour12(bool),
185}
186
187/// What a date format shows: components (a date combination `0..216`, a time combination
188/// `0..27`, as `scripts/cldr.mjs` numbers them) or styles (`0..4`: full, long, medium,
189/// short; [`NO_STYLE`] for none; a time style is medium or short).
190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
191pub(crate) enum Shape {
192    Components { date: u8, time: u8 },
193    Styles { date: u8, time: u8 },
194}
195
196pub(crate) const NO_STYLE: u8 = u8::MAX;
197
198/// Resolved `Intl.DateTimeFormat` options.
199#[derive(Debug, Clone)]
200pub(crate) struct DateOptions {
201    pub(crate) shape: Shape,
202    pub(crate) cycle: Cycle,
203    /// The format's own `timeZone`; else the instance's.
204    pub(crate) zone: Option<Zone>,
205}
206
207impl DateOptions {
208    /// `new Intl.DateTimeFormat(locale)`: year, month and day, numeric.
209    pub(crate) const DEFAULT: DateOptions = DateOptions {
210        shape: Shape::Components {
211            date: DATE_NUMERIC,
212            time: 0,
213        },
214        cycle: Cycle::Locale,
215        zone: None,
216    };
217}
218
219/// Year, month and day numeric: `((1 * 6 + 1) * 3 + 1) * 4`.
220const DATE_NUMERIC: u8 = 88;
221
222// Slots of the date row and the time row (`build.rs` `pattern_slots`).
223const DATE_STYLES: usize = 216;
224const GLUE: usize = 220;
225const STYLE_GLUE: usize = 224;
226const HOUR_TABLES: usize = 9;
227const TIME_STYLES: usize = 99;
228
229/// The glue of a date combination (ICU's pattern generator): a long month with a weekday is
230/// full, a long month long, a short one medium, the rest short.
231fn glue_width(date: u8) -> usize {
232    match date / 12 % 6 {
233        3 if !date.is_multiple_of(4) => 0,
234        3 => 1,
235        4 => 2,
236        _ => 3,
237    }
238}
239
240/// The hour table of a cycle: 0 `j`, 1 `K`, 2 `h`, 3 `H`, 4 `k`.
241fn table(cycle: Cycle, loc: &Loc) -> usize {
242    let letter = match cycle {
243        Cycle::Locale => return 0,
244        Cycle::H11 => b'K',
245        Cycle::H12 => b'h',
246        Cycle::H23 => b'H',
247        Cycle::H24 => b'k',
248        Cycle::Hour12(true) => loc.hc12,
249        Cycle::Hour12(false) => loc.hc24,
250    };
251    match letter {
252        b'K' => 1,
253        b'h' => 2,
254        b'H' => 3,
255        _ => 4,
256    }
257}
258
259/// The override of `(kind, a, b, table)` among the locale's, as `build.rs` keys them.
260fn override_of(loc: &Loc, kind: u32, a: u8, b: u8, mode: usize) -> Option<&'static str> {
261    let key = (kind << 20) | (u32::from(a) << 12) | (u32::from(b) << 4) | mode as u32;
262    let start = loc.dover as usize;
263    let keys = DATE_OVER_KEYS.get(start..start + usize::from(loc.dover_len))?;
264    let i = keys.binary_search(&key).ok()?;
265    DATE_OVER.get(start + i).map(|&p| data::dpat(p))
266}
267
268/// What to render: one pattern, or a glue with its date and time parts.
269struct Picked {
270    pattern: &'static str,
271    date: &'static str,
272    time: &'static str,
273}
274
275fn pick(o: &DateOptions, loc: &Loc) -> Picked {
276    let row = DATE_PATS.get(usize::from(loc.dpats));
277    let times = DATE_TIMES.get(usize::from(loc.dtimes));
278    let p = |slot: usize| data::dpat(row.and_then(|r| r.get(slot)).copied().unwrap_or(0));
279    let t = |slot: usize| data::dpat(times.and_then(|r| r.get(slot)).copied().unwrap_or(0));
280    let mode = table(o.cycle, loc);
281    let one = |pattern| Picked {
282        pattern,
283        date: "",
284        time: "",
285    };
286    match o.shape {
287        Shape::Components { date, time } => {
288            let time_pattern = || match time {
289                1..9 => t(usize::from(time)),
290                _ => t(HOUR_TABLES + mode * 18 + usize::from(time) - 9),
291            };
292            match (date, time) {
293                (_, 0) => one(p(usize::from(date))),
294                (0, _) => one(time_pattern()),
295                _ => {
296                    let m = if time < 9 { 0 } else { mode };
297                    match override_of(loc, 0, date, time, m) {
298                        Some(full) => one(full),
299                        None => Picked {
300                            pattern: p(GLUE + glue_width(date)),
301                            date: p(usize::from(date)),
302                            time: time_pattern(),
303                        },
304                    }
305                }
306            }
307        }
308        Shape::Styles { date, time } => {
309            let time_pattern = || t(TIME_STYLES + mode * 2 + usize::from(time.saturating_sub(2)));
310            match (date, time) {
311                (_, NO_STYLE) => one(p(DATE_STYLES + usize::from(date))),
312                (NO_STYLE, _) => one(time_pattern()),
313                _ => match override_of(loc, 1, date, time, mode) {
314                    Some(full) => one(full),
315                    None => Picked {
316                        pattern: p(STYLE_GLUE + usize::from(date)),
317                        date: p(DATE_STYLES + usize::from(date)),
318                        time: time_pattern(),
319                    },
320                },
321            }
322        }
323    }
324}
325
326/// What fields read besides the instant.
327struct Cx {
328    names: &'static [u16],
329    digits: [&'static str; 10],
330    /// The digits are `0`–`9` (`digits` holds them too).
331    latin: bool,
332    loc: &'static Loc,
333}
334
335/// Formats `t` (in `zone`, unless the options have their own) into `out`; an invalid date
336/// writes `Invalid Date`, as `FormatService.formatDate`.
337pub(crate) fn write(
338    t: Timestamp,
339    o: &DateOptions,
340    loc: &'static Loc,
341    zone: &Zone,
342    out: &mut dyn fmt::Write,
343) -> fmt::Result {
344    let Some(ms) = t.0 else {
345        return out.write_str("Invalid Date");
346    };
347    let zone = o.zone.as_ref().unwrap_or(zone);
348    let secs = ms.div_euclid(1000);
349    let c = civil_from_unix(secs + i64::from(zone.offset_at(secs)));
350    let cx = Cx {
351        names: DATE_NAMES
352            .get(usize::from(loc.dnames))
353            .map_or(&[][..], |r| &r[..]),
354        digits: super::number::digit_table(loc),
355        latin: data::s(loc.digits).is_empty(),
356        loc,
357    };
358    let picked = pick(o, loc);
359    render(picked.pattern, &c, &cx, (picked.date, picked.time), out)
360}
361
362/// Writes a compiled pattern; a glue's `{1}` is `parts.0`, `{0}` `parts.1`.
363fn render(
364    p: &str,
365    c: &Civil,
366    cx: &Cx,
367    parts: (&str, &str),
368    out: &mut dyn fmt::Write,
369) -> fmt::Result {
370    let b = p.as_bytes();
371    let mut from = 0;
372    let mut i = 0;
373    while i < b.len() {
374        if b.get(i) != Some(&1) {
375            i += 1;
376            continue;
377        }
378        if from < i {
379            out.write_str(p.get(from..i).unwrap_or(""))?;
380        }
381        let letter = b.get(i + 1).copied().unwrap_or(0);
382        let width = b.get(i + 2).map_or(1, |w| w.wrapping_sub(b'0'));
383        i += 3;
384        from = i;
385        match (letter, width) {
386            (b'{', 1) => render(parts.0, c, cx, ("", ""), out)?,
387            (b'{', _) => render(parts.1, c, cx, ("", ""), out)?,
388            _ => field(letter, width, p, c, cx, out)?,
389        }
390    }
391    match p.get(from..) {
392        Some(rest) if !rest.is_empty() => out.write_str(rest),
393        _ => Ok(()),
394    }
395}
396
397/// `00`, `01`, … `99`: two Latin digits per write.
398static PAIRS: &str = match std::str::from_utf8(&PAIR_BYTES) {
399    Ok(s) => s,
400    Err(_) => "",
401};
402const PAIR_BYTES: [u8; 200] = {
403    let mut a = [0u8; 200];
404    let mut i = 0;
405    while i < 100 {
406        a[2 * i] = b'0' + (i / 10) as u8;
407        a[2 * i + 1] = b'0' + (i % 10) as u8;
408        i += 1;
409    }
410    a
411};
412
413/// Digits of `v`, at least `width` of them, in the locale's digits.
414fn number(v: u64, width: u8, cx: &Cx, out: &mut dyn fmt::Write) -> fmt::Result {
415    if cx.latin && v < 10_000 && width <= 4 {
416        // every calendar field but a long year: at most two writes of `PAIRS`
417        let v = v as usize;
418        let len = match v {
419            0..10 => 1,
420            10..100 => 2,
421            100..1000 => 3,
422            _ => 4,
423        }
424        .max(usize::from(width));
425        let pair = |n: usize| PAIRS.get(2 * n..2 * n + 2).unwrap_or("00");
426        let (hi, lo) = (pair(v / 100), pair(v % 100));
427        if len > 2 {
428            out.write_str(if len == 3 {
429                hi.get(1..).unwrap_or("")
430            } else {
431                hi
432            })?;
433        }
434        return out.write_str(if len == 1 {
435            lo.get(1..).unwrap_or("")
436        } else {
437            lo
438        });
439    }
440    let mut buf = [0u8; 20];
441    let mut n = v;
442    let mut len = 0;
443    while (n > 0 || len < usize::from(width.max(1))) && len < buf.len() {
444        if let Some(slot) = buf.get_mut(len) {
445            *slot = (n % 10) as u8;
446        }
447        n /= 10;
448        len += 1;
449    }
450    for d in buf.get(..len).unwrap_or(&[]).iter().rev() {
451        out.write_str(cx.digits.get(usize::from(*d)).copied().unwrap_or("0"))?;
452    }
453    Ok(())
454}
455
456/// A name of the row: list `set` (`build.rs` `NAME_SETS` order), entry `i`.
457fn name(cx: &Cx, set: usize, i: usize) -> &'static str {
458    // months: 6 lists of 12; weekdays: 8 of 7 from 72; AM / PM and eras: 6 of 2 from 128
459    let at = match set {
460        0..6 => set * 12 + i,
461        6..14 => 72 + (set - 6) * 7 + i,
462        _ => 128 + (set - 14) * 2 + i,
463    };
464    data::dname(cx.names.get(at).copied().unwrap_or(0))
465}
466
467/// Width letters to a list: 3 abbreviated, 4 wide, 5 narrow, 6 short.
468fn width_index(width: u8) -> usize {
469    match width {
470        4 => 1,
471        5 => 2,
472        6 => 3,
473        _ => 0,
474    }
475}
476
477fn field(
478    letter: u8,
479    width: u8,
480    p: &str,
481    c: &Civil,
482    cx: &Cx,
483    out: &mut dyn fmt::Write,
484) -> fmt::Result {
485    match letter {
486        b'y' => {
487            // the year of the era: 2 BC for -1
488            let y = if c.year > 0 { c.year } else { 1 - c.year }.unsigned_abs();
489            if width == 2 {
490                number(y % 100, 2, cx, out)
491            } else {
492                number(y, width, cx, out)
493            }
494        }
495        b'Y' => {
496            let y = week_year(c);
497            if y < 0 {
498                out.write_str(data::s(
499                    data::PATTERNS
500                        .get(usize::from(cx.loc.decimal_pat))
501                        .map_or(0, |pat| pat.np),
502                ))?;
503            }
504            let a = y.unsigned_abs();
505            number(if width == 2 { a % 100 } else { a }, width, cx, out)
506        }
507        b'M' | b'L' if width <= 2 => number(u64::from(c.month), width, cx, out),
508        b'M' | b'L' => {
509            let set = usize::from(letter == b'L') * 3 + width_index(width).min(2);
510            out.write_str(name(cx, set, usize::from(c.month).saturating_sub(1)))
511        }
512        b'r' => {
513            // not CLDR's `r`: a numeric month in lowercase Roman numerals (`haw`)
514            const ROMAN: [&str; 12] = [
515                "i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix", "x", "xi", "xii",
516            ];
517            out.write_str(
518                ROMAN
519                    .get(usize::from(c.month).saturating_sub(1))
520                    .copied()
521                    .unwrap_or(""),
522            )
523        }
524        b'd' => number(u64::from(c.day), width, cx, out),
525        b'E' | b'c' => {
526            let set = 6 + usize::from(letter == b'c') * 4 + width_index(width);
527            out.write_str(name(cx, set, usize::from(c.weekday)))
528        }
529        b'h' => number(
530            u64::from(match c.hour % 12 {
531                0 => 12,
532                h => h,
533            }),
534            width,
535            cx,
536            out,
537        ),
538        b'H' => number(u64::from(c.hour), width, cx, out),
539        b'K' => number(u64::from(c.hour % 12), width, cx, out),
540        b'k' => number(
541            u64::from(if c.hour == 0 { 24 } else { c.hour }),
542            width,
543            cx,
544            out,
545        ),
546        b'm' => number(u64::from(c.minute), width, cx, out),
547        b's' => number(u64::from(c.second), width, cx, out),
548        b'a' => out.write_str(name(
549            cx,
550            14 + width_index(width).min(2),
551            usize::from(c.hour >= 12),
552        )),
553        b'B' => out.write_str(flexible(p, c, cx, width)),
554        b'G' => out.write_str(name(
555            cx,
556            17 + width_index(width).min(2),
557            usize::from(c.year > 0),
558        )),
559        _ => Ok(()),
560    }
561}
562
563/// A flexible day period (`B`, ICU): `noon` at 12:00 exactly (minutes and seconds the pattern
564/// shows are zero) when the locale has one, else the period of the hour.
565fn flexible(p: &str, c: &Civil, cx: &Cx, width: u8) -> &'static str {
566    let Some(row) = DATE_B.get(usize::from(cx.loc.db)) else {
567        return name(cx, 14, usize::from(c.hour >= 12));
568    };
569    let base = width_index(width).min(2) * 25;
570    let shows = |l: u8| p.as_bytes().windows(2).any(|w| w == [1, l]);
571    let noon = row.get(base + 24).copied().unwrap_or(0);
572    let exact = (!shows(b'm') || c.minute == 0) && (!shows(b's') || c.second == 0);
573    let i = if c.hour == 12 && noon != 0 && exact {
574        noon
575    } else {
576        row.get(base + usize::from(c.hour)).copied().unwrap_or(0)
577    };
578    data::dname(i)
579}