Skip to main content

nodejs/
datefmt.rs

1//! `Date.prototype.toLocaleString` / `toLocaleDateString` / `toLocaleTimeString`
2//! with their `options` argument, in the `en-US` shape.
3//!
4//! Node formats these through ICU: ECMA-402's `CreateDateTimeFormat` turns the
5//! options bag into a SKELETON (`"yMMMMEEEEd"`, `"hm"`, …), and ICU's
6//! `DateTimePatternGenerator` turns the skeleton into a PATTERN
7//! (`"EEEE, MMMM d, y"`) by a distance search over the locale's
8//! `availableFormats`, adjusting field widths, appending fields no pattern
9//! carries and gluing a date half to a time half. That is what this module is: a
10//! port of `dtptngen.cpp`'s `getBestPattern` / `getBestRaw` /
11//! `getBestAppending` / `adjustFieldTypes` over the en data ICU 79 (CLDR 49)
12//! ships, so every option combination resolves to the pattern node's does —
13//! including the odd ones, like
14//! `{day: '2-digit', hour: '2-digit', second: 'numeric'}` printing
15//! `09, 9 (hour: 13)`.
16//!
17//! The `locales` argument is still ignored: every locale formats as en-US, as
18//! `numfmt` does for numbers (see BUGS.md).
19
20use crate::host::{self, with_host};
21use fusevm::Value;
22
23// ICU's `UDateTimePatternField` indices.
24const ERA: usize = 0;
25const YEAR: usize = 1;
26const QUARTER: usize = 2;
27const MONTH: usize = 3;
28const WEEK_OF_YEAR: usize = 4;
29const WEEK_OF_MONTH: usize = 5;
30const WEEKDAY: usize = 6;
31const DAY_OF_YEAR: usize = 7;
32const DAY_OF_WEEK_IN_MONTH: usize = 8;
33const DAY: usize = 9;
34const DAYPERIOD: usize = 10;
35const HOUR: usize = 11;
36const MINUTE: usize = 12;
37const SECOND: usize = 13;
38const FRACTIONAL: usize = 14;
39const ZONE: usize = 15;
40const FIELD_COUNT: usize = 16;
41
42const DATE_MASK: u32 = (1 << DAYPERIOD) - 1;
43const TIME_MASK: u32 = ((1 << FIELD_COUNT) - 1) & !DATE_MASK;
44const SECOND_AND_FRACTIONAL: u32 = (1 << SECOND) | (1 << FRACTIONAL);
45
46// ICU's field "types": numeric types are positive (and the field LENGTH is added
47// to them in a skeleton), text widths negative; the distance between two
48// skeletons is the sum of the type differences.
49const NUMERIC: i32 = 0x100;
50const DELTA: i32 = 0x10;
51const NARROW: i32 = -0x101;
52const SHORTER: i32 = -0x102;
53const SHORT: i32 = -0x103;
54const LONG: i32 = -0x104;
55const EXTRA_FIELD: i32 = 0x10000;
56const MISSING_FIELD: i32 = 0x1000;
57
58/// ICU's `dtTypes` table, in its order: `(pattern char, field, type, min length)`.
59/// A run of `c` repeated `n` times is the LAST row for `c` whose min length is
60/// at most `n`.
61const TYPES: &[(char, usize, i32, usize)] = &[
62    ('G', ERA, SHORT, 1),
63    ('G', ERA, LONG, 4),
64    ('G', ERA, NARROW, 5),
65    ('y', YEAR, NUMERIC, 1),
66    ('Q', QUARTER, NUMERIC, 1),
67    ('Q', QUARTER, SHORT, 3),
68    ('Q', QUARTER, LONG, 4),
69    ('Q', QUARTER, NARROW, 5),
70    ('M', MONTH, NUMERIC, 1),
71    ('M', MONTH, SHORT, 3),
72    ('M', MONTH, LONG, 4),
73    ('M', MONTH, NARROW, 5),
74    ('L', MONTH, NUMERIC + DELTA, 1),
75    ('L', MONTH, SHORT - DELTA, 3),
76    ('L', MONTH, LONG - DELTA, 4),
77    ('L', MONTH, NARROW - DELTA, 5),
78    ('w', WEEK_OF_YEAR, NUMERIC, 1),
79    ('W', WEEK_OF_MONTH, NUMERIC, 1),
80    ('E', WEEKDAY, SHORT, 1),
81    ('E', WEEKDAY, LONG, 4),
82    ('E', WEEKDAY, NARROW, 5),
83    ('E', WEEKDAY, SHORTER, 6),
84    ('c', WEEKDAY, NUMERIC + 2 * DELTA, 1),
85    ('c', WEEKDAY, SHORT - 2 * DELTA, 3),
86    ('c', WEEKDAY, LONG - 2 * DELTA, 4),
87    ('c', WEEKDAY, NARROW - 2 * DELTA, 5),
88    ('c', WEEKDAY, SHORTER - 2 * DELTA, 6),
89    ('d', DAY, NUMERIC, 1),
90    ('d', DAY, SHORT, 3),
91    ('D', DAY_OF_YEAR, NUMERIC, 1),
92    ('F', DAY_OF_WEEK_IN_MONTH, NUMERIC, 1),
93    ('a', DAYPERIOD, SHORT, 1),
94    ('a', DAYPERIOD, LONG, 4),
95    ('a', DAYPERIOD, NARROW, 5),
96    ('B', DAYPERIOD, SHORT - 3 * DELTA, 1),
97    ('B', DAYPERIOD, LONG - 3 * DELTA, 4),
98    ('B', DAYPERIOD, NARROW - 3 * DELTA, 5),
99    ('H', HOUR, NUMERIC + 10 * DELTA, 1),
100    ('k', HOUR, NUMERIC + 11 * DELTA, 1),
101    ('h', HOUR, NUMERIC, 1),
102    ('K', HOUR, NUMERIC + DELTA, 1),
103    ('m', MINUTE, NUMERIC, 1),
104    ('s', SECOND, NUMERIC, 1),
105    ('S', FRACTIONAL, NUMERIC, 1),
106    ('v', ZONE, SHORT - 2 * DELTA, 1),
107    ('v', ZONE, LONG - 2 * DELTA, 4),
108    ('z', ZONE, SHORT, 1),
109    ('z', ZONE, LONG, 4),
110    ('O', ZONE, SHORT - 3 * DELTA, 1),
111    ('O', ZONE, LONG - 3 * DELTA, 4),
112];
113
114/// The `dtTypes` row a run of `c` × `len` belongs to (`getCanonicalIndex`).
115fn type_row(c: char, len: usize) -> Option<(usize, i32, usize)> {
116    TYPES
117        .iter()
118        .rev()
119        .find(|r| r.0 == c && r.3 <= len)
120        .or_else(|| TYPES.iter().find(|r| r.0 == c))
121        .map(|r| (r.1, r.2, r.3))
122}
123
124/// One token of a pattern: a field (a run of one letter), or literal text kept
125/// verbatim — a quoted run with its quotes, or punctuation and spaces.
126#[derive(Clone, Debug, PartialEq)]
127enum Tok {
128    Field(char, usize),
129    Lit(String),
130}
131
132fn tokenize(pattern: &str) -> Vec<Tok> {
133    let cs: Vec<char> = pattern.chars().collect();
134    let mut out = Vec::new();
135    let mut i = 0;
136    while i < cs.len() {
137        let c = cs[i];
138        if c.is_ascii_alphabetic() {
139            let start = i;
140            while i < cs.len() && cs[i] == c {
141                i += 1;
142            }
143            out.push(Tok::Field(c, i - start));
144        } else if c == '\'' {
145            // A quoted literal runs to the next lone quote; `''` is a quote.
146            let start = i;
147            i += 1;
148            while i < cs.len() {
149                if cs[i] == '\'' {
150                    if cs.get(i + 1) == Some(&'\'') {
151                        i += 2;
152                        continue;
153                    }
154                    i += 1;
155                    break;
156                }
157                i += 1;
158            }
159            out.push(Tok::Lit(cs[start..i].iter().collect()));
160        } else {
161            out.push(Tok::Lit(c.to_string()));
162            i += 1;
163        }
164    }
165    out
166}
167
168/// A skeleton (ICU's `PtnSkeleton`): per field, the run that names it, its
169/// type, and the length of its BASE form (the row's minimum length).
170#[derive(Clone, Debug, PartialEq, Default)]
171struct Skeleton {
172    orig: [Option<(char, usize)>; FIELD_COUNT],
173    ty: [i32; FIELD_COUNT],
174    base: [Option<(char, usize)>; FIELD_COUNT],
175    /// The `a` ICU adds to a 12-hour skeleton that names no day period.
176    added_day_period: bool,
177}
178
179impl Skeleton {
180    /// `DateTimeMatcher::set`: the skeleton a pattern (or skeleton string)
181    /// denotes. Literals are skipped.
182    fn of(pattern: &str) -> Skeleton {
183        let mut s = Skeleton::default();
184        for t in tokenize(pattern) {
185            let Tok::Field(c, len) = t else { continue };
186            let Some((field, ty, min)) = type_row(c, len) else {
187                continue;
188            };
189            s.orig[field] = Some((c, len));
190            let base_char = TYPES
191                .iter()
192                .find(|r| r.1 == field && r.2 == ty)
193                .map_or(c, |r| r.0);
194            s.base[field] = Some((base_char, min));
195            s.ty[field] = if ty > 0 { ty + len as i32 } else { ty };
196        }
197        // ICU #20739: minutes with fractional seconds but no seconds force a
198        // seconds field, so the fraction has something to follow.
199        if s.orig[MINUTE].is_some() && s.orig[FRACTIONAL].is_some() && s.orig[SECOND].is_none() {
200            s.orig[SECOND] = Some(('s', 1));
201            s.base[SECOND] = Some(('s', 1));
202            s.ty[SECOND] = NUMERIC + 1;
203        }
204        // A 12-hour skeleton without a day period gets ICU's default `a`; a
205        // 24-hour one drops any day period it names.
206        if let Some((h, _)) = s.orig[HOUR] {
207            if h == 'h' || h == 'K' {
208                if s.orig[DAYPERIOD].is_none() {
209                    s.orig[DAYPERIOD] = Some(('a', 1));
210                    s.base[DAYPERIOD] = Some(('a', 1));
211                    s.ty[DAYPERIOD] = SHORT;
212                    s.added_day_period = true;
213                }
214            } else if s.orig[DAYPERIOD].is_some() {
215                s.orig[DAYPERIOD] = None;
216                s.base[DAYPERIOD] = None;
217                s.ty[DAYPERIOD] = 0;
218            }
219        }
220        s
221    }
222
223    fn mask(&self) -> u32 {
224        (0..FIELD_COUNT)
225            .filter(|&i| self.ty[i] != 0)
226            .fold(0, |m, i| m | (1 << i))
227    }
228
229    /// The base pattern's text (`getBasePattern`), which keys ICU's buckets.
230    fn base_string(&self) -> String {
231        self.base
232            .iter()
233            .flatten()
234            .map(|&(c, n)| c.to_string().repeat(n))
235            .collect()
236    }
237
238    /// `DateTimeMatcher::getDistance`, restricted to the fields in `include`.
239    fn distance(&self, other: &Skeleton, include: u32) -> (i32, u32, u32) {
240        let (mut d, mut missing, mut extra) = (0, 0u32, 0u32);
241        for i in 0..FIELD_COUNT {
242            let mine = if include & (1 << i) == 0 {
243                0
244            } else {
245                self.ty[i]
246            };
247            let theirs = other.ty[i];
248            if mine == theirs {
249                continue;
250            }
251            if mine == 0 {
252                d += EXTRA_FIELD;
253                extra |= 1 << i;
254            } else if theirs == 0 {
255                d += MISSING_FIELD;
256                missing |= 1 << i;
257            } else {
258                d += (mine - theirs).abs();
259            }
260        }
261        (d, missing, extra)
262    }
263}
264
265/// One generator entry: the skeleton it is matched by, its pattern, and
266/// whether the skeleton was given explicitly (an `availableFormats` key) or
267/// derived from the pattern (a canonical item or a style pattern).
268struct Entry {
269    skel: Skeleton,
270    pattern: &'static str,
271    specified: bool,
272}
273
274/// en's `availableFormats` (ICU 79 / CLDR 49, root merged under en), in the
275/// resource bundle's key order. The `ddd` items are CLDR 49's ordinal day
276/// (`9th`), which no ECMA-402 request names; the `yy` items carry a literal
277/// `’` that only a two-digit-year request may match (see `best_raw`). The
278/// week-numbering items are left out: ECMA-402 never asks for a week field,
279/// and they carry fields no request has, so they never win.
280const AVAILABLE_FORMATS: &[(&str, &str)] = &[
281    ("Bh", "h B"),
282    ("Bhm", "h:mm B"),
283    ("Bhms", "h:mm:ss B"),
284    ("E", "ccc"),
285    ("EBh", "E h B"),
286    ("EBhm", "E h:mm B"),
287    ("EBhms", "E h:mm:ss B"),
288    ("EHm", "E HH:mm"),
289    ("EHms", "E HH:mm:ss"),
290    ("Ed", "d E"),
291    ("Eh", "E h a"),
292    ("Ehm", "E h:mm a"),
293    ("Ehms", "E h:mm:ss a"),
294    ("Gy", "y G"),
295    ("GyM", "M/y G"),
296    ("GyMEd", "E, M/d/y G"),
297    ("GyMMM", "MMM y G"),
298    ("GyMMMEd", "E, MMM d, y G"),
299    ("GyMMMEddd", "E, MMM ddd, y G"),
300    ("GyMMMM", "MMMM y G"),
301    ("GyMMMMEd", "E, MMMM d, y G"),
302    ("GyMMMMEddd", "E, MMMM ddd, y G"),
303    ("GyMMMMd", "MMMM d, y G"),
304    ("GyMMMMddd", "MMMM ddd, y G"),
305    ("GyMMMd", "MMM d, y G"),
306    ("GyMMMddd", "MMM ddd, y G"),
307    ("GyMd", "M/d/y G"),
308    ("H", "HH"),
309    ("Hm", "HH:mm"),
310    ("Hms", "HH:mm:ss"),
311    ("Hmsv", "HH:mm:ss v"),
312    ("Hmv", "HH:mm v"),
313    ("Hv", "HH v"),
314    ("M", "L"),
315    ("MEd", "E, M/d"),
316    ("MMM", "LLL"),
317    ("MMMEd", "E, MMM d"),
318    ("MMMEddd", "E, MMM ddd"),
319    ("MMMMEd", "E, MMMM d"),
320    ("MMMMEddd", "E, MMMM ddd"),
321    ("MMMMd", "MMMM d"),
322    ("MMMMddd", "MMMM ddd"),
323    ("MMMd", "MMM d"),
324    ("MMMddd", "MMM ddd"),
325    ("Md", "M/d"),
326    ("d", "d"),
327    ("h", "h a"),
328    ("hm", "h:mm a"),
329    ("hms", "h:mm:ss a"),
330    ("hmsv", "h:mm:ss a v"),
331    ("hmv", "h:mm a v"),
332    ("hv", "h a v"),
333    ("ms", "mm:ss"),
334    ("y", "y"),
335    ("yM", "M/y"),
336    ("yMEd", "E, M/d/y"),
337    ("yMMM", "MMM y"),
338    ("yMMMEd", "E, MMM d, y"),
339    ("yMMMEddd", "E, MMM ddd, y"),
340    ("yMMMM", "MMMM y"),
341    ("yMMMMEd", "E, MMMM d, y"),
342    ("yMMMMEddd", "E, MMMM ddd, y"),
343    ("yMMMMd", "MMMM d, y"),
344    ("yMMMMddd", "MMMM ddd, y"),
345    ("yMMMd", "MMM d, y"),
346    ("yMMMddd", "MMM ddd, y"),
347    ("yMd", "M/d/y"),
348    ("yQQQ", "QQQ y"),
349    ("yQQQQ", "QQQQ y"),
350    ("yy", "’yy"),
351    ("yyMMM", "MMM ’yy"),
352    ("yyMMMd", "MMM d, ’yy"),
353];
354
355/// en's date styles (`full` … `short`) and time styles. ICU's own patterns put
356/// U+202F before the day period; V8 swaps it for a space, so these do too.
357const DATE_STYLES: [&str; 4] = ["EEEE, MMMM d, y", "MMMM d, y", "MMM d, y", "M/d/yy"];
358const TIME_STYLES: [&str; 4] = ["h:mm:ss a zzzz", "h:mm:ss a z", "h:mm:ss a", "h:mm a"];
359
360/// en's `dateTimeFormats` (the `atTime` set, which is what the generator and
361/// the styles use), indexed like the styles.
362const DATE_TIME_GLUE: [&str; 4] = ["{1} 'at' {0}", "{1} 'at' {0}", "{1}, {0}", "{1}, {0}"];
363
364/// The generator's entries in ICU's ITERATION order, built as `initData` does:
365/// canonical one-field items, then the style patterns, then the `mm:ss` hack,
366/// all without override; then `availableFormats`, overriding. Iteration walks
367/// ICU's buckets — keyed by the base pattern's first letter, `A`–`Z` then
368/// `a`–`z` — each in insertion order, and that order breaks distance ties.
369fn entries() -> &'static [Entry] {
370    static ENTRIES: std::sync::OnceLock<Vec<Entry>> = std::sync::OnceLock::new();
371    ENTRIES.get_or_init(|| {
372        let mut list: Vec<Entry> = Vec::new();
373        // `addPatternWithSkeleton` with `override = false` and no skeleton: a
374        // BASE conflict or an identical skeleton keeps the earlier entry.
375        let add_derived = |list: &mut Vec<Entry>, pattern: &'static str| {
376            let skel = Skeleton::of(pattern);
377            let base = skel.base_string();
378            if list.iter().any(|e| e.skel.base_string() == base) {
379                return;
380            }
381            list.push(Entry {
382                skel,
383                pattern,
384                specified: false,
385            });
386        };
387        const CANONICAL: &[&str] = &[
388            "G", "y", "Q", "M", "w", "W", "E", "D", "F", "d", "a", "H", "m", "s", "S", "v",
389        ];
390        for p in CANONICAL {
391            add_derived(&mut list, p);
392        }
393        for i in 0..4 {
394            add_derived(&mut list, DATE_STYLES[i]);
395            add_derived(&mut list, TIME_STYLES[i]);
396        }
397        // `hackTimes` on the medium time pattern.
398        add_derived(&mut list, "mm:ss");
399        for &(key, pattern) in AVAILABLE_FORMATS {
400            let skel = Skeleton::of(key);
401            match list.iter_mut().find(|e| e.skel == skel) {
402                Some(e) => {
403                    e.pattern = pattern;
404                    e.specified = true;
405                }
406                None => list.push(Entry {
407                    skel,
408                    pattern,
409                    specified: true,
410                }),
411            }
412        }
413        let bucket = |e: &Entry| {
414            let c = e.skel.base_string().chars().next().unwrap_or('a');
415            if c.is_ascii_uppercase() {
416                c as u32 - 'A' as u32
417            } else {
418                26 + c as u32 - 'a' as u32
419            }
420        };
421        list.sort_by_key(bucket);
422        list
423    })
424}
425
426/// `yearLengthIsCompatible`: a numeric two-digit year in `trial` matches only a
427/// request for a numeric two-digit year.
428fn year_length_compatible(req: &Skeleton, trial: &Skeleton) -> bool {
429    let len = |s: &Skeleton| s.orig[YEAR].map_or(0, |(_, n)| n);
430    req.ty[YEAR] <= 0 || trial.ty[YEAR] <= 0 || len(trial) != 2 || len(req) == 2
431}
432
433/// `getBestRaw`: the entry nearest `req` over the fields in `include`, with
434/// the missing and extra field masks of that match.
435///
436/// An entry whose skeleton names a TWO-digit numeric year (`yyMMMd` →
437/// `MMM d, ’yy`) is skipped unless the request asks for one too
438/// (`yearLengthIsCompatible`): its literal `’` only makes sense before two
439/// digits, and on distance alone `yyyy` is nearer `yy` than `y`.
440fn best_raw(req: &Skeleton, include: u32) -> (&'static Entry, u32, u32) {
441    let mut best: Option<(&Entry, i32, u32, u32)> = None;
442    for e in entries() {
443        if !year_length_compatible(req, &e.skel) {
444            continue;
445        }
446        let (d, missing, extra) = req.distance(&e.skel, include);
447        let better = match best {
448            None => true,
449            Some((_, bd, bmissing, _)) => d < bd || (d == bd && bmissing < missing),
450        };
451        if better {
452            best = Some((e, d, missing, extra));
453            if d == 0 {
454                break;
455            }
456        }
457    }
458    let (e, _, missing, extra) = best.expect("the generator has entries");
459    (e, missing, extra)
460}
461
462/// `adjustFieldTypes` with `UDATPG_MATCH_HOUR_FIELD_LENGTH` (what V8 passes):
463/// each field the request names takes the request's width, except where ICU
464/// keeps the pattern's own.
465fn adjust(
466    pattern: &str,
467    entry_skel: Option<&Skeleton>,
468    req: &Skeleton,
469    fix_fraction: bool,
470) -> String {
471    let mut out = String::new();
472    for t in tokenize(pattern) {
473        let (c, len) = match t {
474            Tok::Lit(s) => {
475                out.push_str(&s);
476                continue;
477            }
478            Tok::Field(c, len) => (c, len),
479        };
480        let Some((field, row_ty, _)) = type_row(c, len) else {
481            out.push_str(&c.to_string().repeat(len));
482            continue;
483        };
484        if fix_fraction && field == SECOND {
485            out.push_str(&c.to_string().repeat(len));
486            out.push('.');
487            if let Some((fc, flen)) = req.orig[FRACTIONAL] {
488                out.push_str(&fc.to_string().repeat(flen));
489            }
490            continue;
491        }
492        if req.ty[field] == 0 {
493            out.push_str(&c.to_string().repeat(len));
494            continue;
495        }
496        let (req_char, mut req_len) = req.orig[field].unwrap_or((c, len));
497        if req_char == 'E' && req_len < 3 {
498            req_len = 3;
499        }
500        let mut adj_len = req_len;
501        if field == MINUTE || field == SECOND {
502            adj_len = len;
503        } else if let Some(spec) = entry_skel {
504            let skel_len = spec.orig[field].map_or(0, |(_, n)| n);
505            let pat_numeric = row_ty > 0;
506            // Since ICU 79 the pattern is compared against the REQUESTED
507            // field's kind; ICU 77 compared it against the specified skeleton's.
508            let req_numeric = req.ty[field] > 0;
509            if skel_len == req_len || pat_numeric != req_numeric {
510                adj_len = len;
511            }
512        }
513        let keep_pattern_char = matches!(field, HOUR | MONTH | WEEKDAY | YEAR);
514        let mut ch = if keep_pattern_char { c } else { req_char };
515        if field == HOUR {
516            // en's default hour character is `h`.
517            ch = match req_char {
518                'h' => 'h',
519                'K' => 'h',
520                _ => ch,
521            };
522        }
523        out.push_str(&ch.to_string().repeat(adj_len));
524    }
525    out
526}
527
528/// `getBestAppending`: the pattern for the fields in `fields`, appending (with
529/// en's `appendItems`) whatever the nearest pattern lacks.
530fn best_appending(req: &Skeleton, fields: u32) -> String {
531    if fields == 0 {
532        return String::new();
533    }
534    let (e, mut missing, extra) = best_raw(req, fields);
535    let spec = |e: &Entry| e.specified.then_some(&e.skel).cloned();
536    let mut spec_skel = spec(e);
537    let mut result = adjust(e.pattern, spec_skel.as_ref(), req, false);
538    if missing == 0 && extra == 0 {
539        return result;
540    }
541    let mut last_missing = 0;
542    while missing != 0 {
543        if last_missing == missing {
544            break;
545        }
546        if missing & SECOND_AND_FRACTIONAL == 1 << FRACTIONAL
547            && fields & SECOND_AND_FRACTIONAL == SECOND_AND_FRACTIONAL
548        {
549            result = adjust(&result, spec_skel.as_ref(), req, true);
550            missing &= !(1 << FRACTIONAL);
551            continue;
552        }
553        let starting = missing;
554        let (e, m, _) = best_raw(req, missing);
555        missing = m;
556        spec_skel = spec(e);
557        let temp = adjust(e.pattern, spec_skel.as_ref(), req, false);
558        let found = starting & !missing;
559        let top = 31 - found.leading_zeros() as usize;
560        result = append_item(top, &result, &temp);
561        last_missing = missing;
562    }
563    result
564}
565
566/// en's `appendItems` (CLDR 49), with each field's wide display name. A
567/// missing weekday is PREPENDED behind a comma (`Day-Of-Week` is `{1}, {0}`),
568/// so `{weekday: 'short', year: 'numeric', second: 'numeric'}` is `Fri, 2024, 9`.
569fn append_item(field: usize, result: &str, temp: &str) -> String {
570    let name = match field {
571        ERA => "era",
572        YEAR => "year",
573        QUARTER => "quarter",
574        MONTH => "month",
575        WEEK_OF_YEAR => "week",
576        WEEK_OF_MONTH => "week of month",
577        WEEKDAY => "day of the week",
578        DAY_OF_YEAR => "day of year",
579        DAY_OF_WEEK_IN_MONTH => "weekday of the month",
580        DAY => "day",
581        DAYPERIOD => "AM/PM",
582        HOUR => "hour",
583        MINUTE => "minute",
584        SECOND => "second",
585        FRACTIONAL => "F14",
586        _ => "time zone",
587    };
588    match field {
589        ERA | YEAR | ZONE => format!("{result} {temp}"),
590        WEEKDAY => format!("{temp}, {result}"),
591        QUARTER | MONTH | WEEK_OF_YEAR | DAY | HOUR | MINUTE | SECOND => {
592            format!("{result} ('{name}': {temp})")
593        }
594        _ => format!("{result} \u{251C}'{name}': {temp}\u{2524}"),
595    }
596}
597
598/// `getBestPattern(skeleton, UDATPG_MATCH_HOUR_FIELD_LENGTH)`.
599fn best_pattern(skeleton: &str) -> String {
600    let req = Skeleton::of(skeleton);
601    let (e, missing, extra) = best_raw(&req, u32::MAX);
602    if missing == 0 && extra == 0 {
603        return adjust(e.pattern, e.specified.then_some(&e.skel), &req, false);
604    }
605    let needed = req.mask();
606    let date = best_appending(&req, needed & DATE_MASK);
607    let time = best_appending(&req, needed & TIME_MASK);
608    if date.is_empty() {
609        return time;
610    }
611    if time.is_empty() {
612        return date;
613    }
614    let month_len = req.base[MONTH].map_or(0, |(_, n)| n);
615    let style = match month_len {
616        4 if req.base[WEEKDAY].is_some() => 0,
617        4 => 1,
618        3 => 2,
619        _ => 3,
620    };
621    glue(style, &date, &time)
622}
623
624fn glue(style: usize, date: &str, time: &str) -> String {
625    DATE_TIME_GLUE[style]
626        .replace("{1}", date)
627        .replace("{0}", time)
628}
629
630// ── options ──────────────────────────────────────────────────────────────────
631
632/// Which `toLocale*String` is asking: what it requires and defaults to
633/// (ECMA-402 `ToDateTimeOptions`).
634#[derive(Clone, Copy, PartialEq)]
635pub enum Required {
636    Any,
637    Date,
638    Time,
639}
640
641/// The hour cycle (`hourCycle` / `hour12`).
642#[derive(Clone, Copy, PartialEq)]
643enum Hc {
644    H11,
645    H12,
646    H23,
647    H24,
648}
649
650/// The zone a format renders in.
651#[derive(Clone)]
652enum Zone {
653    /// The process's zone (`TZ`).
654    Local,
655    Utc,
656    /// A fixed offset east of UTC, in minutes (`"+05:30"`, `Etc/GMT-5`).
657    Fixed(i64),
658    /// A named IANA zone from the system zoneinfo.
659    Named(std::rc::Rc<crate::tzif::Tz>),
660}
661
662fn out_of_range(method: &str, value: &str, name: &str) -> String {
663    host::range_error(&format!(
664        "Value {value} out of range for {method} options property {name}"
665    ))
666}
667
668fn string_option(
669    opts: &Value,
670    method: &str,
671    name: &str,
672    allowed: &[&str],
673) -> Result<Option<String>, String> {
674    let v = crate::builtins::get_property(opts, name)?;
675    if matches!(v, Value::Undef) {
676        return Ok(None);
677    }
678    let s = host::to_string_value(&v)?;
679    let s = with_host(|h| h.str_of(&s));
680    if !allowed.is_empty() && !allowed.contains(&s.as_str()) {
681        return Err(out_of_range(method, &s, name));
682    }
683    Ok(Some(s))
684}
685
686/// A resolved format: the ICU pattern and the zone it renders in.
687pub struct Format {
688    pattern: String,
689    zone: Zone,
690}
691
692const TEXT_WIDTHS: &[&str] = &["narrow", "short", "long"];
693const NUMERIC_WIDTHS: &[&str] = &["numeric", "2-digit"];
694
695/// `CreateDateTimeFormat` for the `toLocale*String` family: read and validate
696/// the options bag in the order V8 does, apply `ToDateTimeOptions`, and resolve
697/// the pattern.
698pub fn resolve(opts: &Value, required: Required, method: &str) -> Result<Format, String> {
699    if with_host(|h| h.is_null(opts)) {
700        return Err(host::type_error(&format!(
701            "{method} called on null or undefined"
702        )));
703    }
704    let is_object = matches!(opts, Value::Obj(_)) && !with_host(|h| host::is_primitive(h, opts));
705    let undef = Value::Undef;
706    let o = if is_object { opts } else { &undef };
707    let get = |name: &str, allowed: &[&str]| -> Result<Option<String>, String> {
708        if is_object {
709            string_option(o, method, name, allowed)
710        } else {
711            Ok(None)
712        }
713    };
714    let hour12 = if is_object {
715        let v = crate::builtins::get_property(o, "hour12")?;
716        (!matches!(v, Value::Undef)).then(|| with_host(|h| h.truthy(&v)))
717    } else {
718        None
719    };
720    let hour_cycle = get("hourCycle", &["h11", "h12", "h23", "h24"])?;
721    let time_zone = if is_object {
722        let v = crate::builtins::get_property(o, "timeZone")?;
723        if matches!(v, Value::Undef) {
724            None
725        } else {
726            let s = host::to_string_value(&v)?;
727            Some(with_host(|h| h.str_of(&s)))
728        }
729    } else {
730        None
731    };
732    let weekday = get("weekday", TEXT_WIDTHS)?;
733    let era = get("era", TEXT_WIDTHS)?;
734    let mut year = get("year", NUMERIC_WIDTHS)?;
735    let mut month = get("month", &["numeric", "2-digit", "narrow", "short", "long"])?;
736    let mut day = get("day", NUMERIC_WIDTHS)?;
737    let day_period = get("dayPeriod", TEXT_WIDTHS)?;
738    let mut hour = get("hour", NUMERIC_WIDTHS)?;
739    let mut minute = get("minute", NUMERIC_WIDTHS)?;
740    let mut second = get("second", NUMERIC_WIDTHS)?;
741    let fsd = if is_object {
742        let v = crate::builtins::get_property(o, "fractionalSecondDigits")?;
743        if matches!(v, Value::Undef) {
744            None
745        } else {
746            let n = host::to_number_value(&v)?;
747            if n.is_nan() || !(1.0..=3.0).contains(&n) {
748                return Err(host::range_error(
749                    "fractionalSecondDigits value is out of range.",
750                ));
751            }
752            Some(n.floor() as usize)
753        }
754    } else {
755        None
756    };
757    let tz_name = get(
758        "timeZoneName",
759        &[
760            "short",
761            "long",
762            "shortOffset",
763            "longOffset",
764            "shortGeneric",
765            "longGeneric",
766        ],
767    )?;
768    let style_names = &["full", "long", "medium", "short"];
769    let date_style = get("dateStyle", style_names)?;
770    let time_style = get("timeStyle", style_names)?;
771
772    let zone = match time_zone {
773        None => Zone::Local,
774        Some(z) => parse_zone(&z)?,
775    };
776
777    let mut hc = match (hour12, hour_cycle.as_deref()) {
778        (Some(true), _) => Some(Hc::H12),
779        (Some(false), _) => Some(Hc::H23),
780        (None, Some("h11")) => Some(Hc::H11),
781        (None, Some("h12")) => Some(Hc::H12),
782        (None, Some("h23")) => Some(Hc::H23),
783        (None, Some("h24")) => Some(Hc::H24),
784        _ => None,
785    };
786
787    if date_style.is_some() || time_style.is_some() {
788        let explicit = weekday.is_some()
789            || era.is_some()
790            || year.is_some()
791            || month.is_some()
792            || day.is_some()
793            || day_period.is_some()
794            || hour.is_some()
795            || minute.is_some()
796            || second.is_some()
797            || fsd.is_some()
798            || tz_name.is_some();
799        if explicit {
800            return Err(host::type_error("Invalid option : option"));
801        }
802        if required == Required::Date && time_style.is_some() {
803            return Err(host::type_error("Invalid option : timeStyle"));
804        }
805        if required == Required::Time && date_style.is_some() {
806            return Err(host::type_error("Invalid option : dateStyle"));
807        }
808        let index = |s: &Option<String>| {
809            s.as_deref()
810                .and_then(|s| style_names.iter().position(|n| *n == s))
811        };
812        let (ds, ts) = (index(&date_style), index(&time_style));
813        let time = ts.map(|t| {
814            let p = TIME_STYLES[t];
815            match hc {
816                // The style's own `h` stands for the locale default; another
817                // cycle is the style's skeleton regenerated with that hour.
818                None | Some(Hc::H12) => p.to_string(),
819                Some(c) => {
820                    let skel: String = Skeleton::of(p)
821                        .orig
822                        .iter()
823                        .flatten()
824                        .filter(|(ch, _)| *ch != 'a')
825                        .map(|&(ch, n)| {
826                            let ch = if ch == 'h' { hour_char(c) } else { ch };
827                            ch.to_string().repeat(n)
828                        })
829                        .collect();
830                    best_pattern(&skel)
831                }
832            }
833        });
834        let pattern = match (ds, time) {
835            (Some(d), Some(t)) => glue(d, DATE_STYLES[d], &t),
836            (Some(d), None) => DATE_STYLES[d].to_string(),
837            (None, Some(t)) => t,
838            (None, None) => unreachable!("a style was given"),
839        };
840        return Ok(Format {
841            pattern: replace_hour_cycle(&pattern, hc),
842            zone,
843        });
844    }
845
846    // ToDateTimeOptions.
847    let mut need_defaults = true;
848    if matches!(required, Required::Date | Required::Any)
849        && (weekday.is_some() || year.is_some() || month.is_some() || day.is_some())
850    {
851        need_defaults = false;
852    }
853    if matches!(required, Required::Time | Required::Any)
854        && (day_period.is_some()
855            || hour.is_some()
856            || minute.is_some()
857            || second.is_some()
858            || fsd.is_some())
859    {
860        need_defaults = false;
861    }
862    if need_defaults && matches!(required, Required::Date | Required::Any) {
863        year = Some("numeric".into());
864        month = Some("numeric".into());
865        day = Some("numeric".into());
866    }
867    if need_defaults && matches!(required, Required::Time | Required::Any) {
868        hour = Some("numeric".into());
869        minute = Some("numeric".into());
870        second = Some("numeric".into());
871        // An hour the caller did not ask for follows only the 12/24 split of
872        // the cycle: node prints `12:00:00 AM` under `h11` and `00:00:00` under
873        // `h24` for a defaulted hour, and `0`/`24` only for an explicit one.
874        hc = hc.map(|c| match c {
875            Hc::H11 | Hc::H12 => Hc::H12,
876            Hc::H23 | Hc::H24 => Hc::H23,
877        });
878    }
879
880    let mut skel = String::new();
881    let mut push = |c: char, n: usize| skel.push_str(&c.to_string().repeat(n));
882    let text_len = |w: &str| match w {
883        "narrow" => 5,
884        "long" => 4,
885        _ => 3,
886    };
887    if let Some(w) = &era {
888        push('G', text_len(w));
889    }
890    if let Some(w) = &year {
891        push('y', if w == "2-digit" { 2 } else { 1 });
892    }
893    if let Some(w) = &month {
894        push(
895            'M',
896            match w.as_str() {
897                "numeric" => 1,
898                "2-digit" => 2,
899                w => text_len(w),
900            },
901        );
902    }
903    if let Some(w) = &weekday {
904        push('E', text_len(w));
905    }
906    if let Some(w) = &day {
907        push('d', if w == "2-digit" { 2 } else { 1 });
908    }
909    if let Some(w) = &day_period {
910        push('B', text_len(w));
911    }
912    if let Some(w) = &hour {
913        push(
914            hour_char(hc.unwrap_or(Hc::H12)),
915            if w == "2-digit" { 2 } else { 1 },
916        );
917    }
918    if let Some(w) = &minute {
919        push('m', if w == "2-digit" { 2 } else { 1 });
920    }
921    if let Some(w) = &second {
922        push('s', if w == "2-digit" { 2 } else { 1 });
923    }
924    if let Some(n) = fsd {
925        push('S', n);
926    }
927    if let Some(w) = &tz_name {
928        let (c, n) = match w.as_str() {
929            "short" => ('z', 1),
930            "long" => ('z', 4),
931            "shortOffset" => ('O', 1),
932            "longOffset" => ('O', 4),
933            "shortGeneric" => ('v', 1),
934            _ => ('v', 4),
935        };
936        push(c, n);
937    }
938    let pattern = best_pattern(&skel);
939    Ok(Format {
940        pattern: replace_hour_cycle(&pattern, if hour.is_some() { hc } else { None }),
941        zone,
942    })
943}
944
945fn hour_char(hc: Hc) -> char {
946    match hc {
947        Hc::H11 => 'K',
948        Hc::H12 => 'h',
949        Hc::H23 => 'H',
950        Hc::H24 => 'k',
951    }
952}
953
954/// V8's `ReplaceHourCycleInPattern`: every hour field outside quotes takes the
955/// requested cycle's letter.
956fn replace_hour_cycle(pattern: &str, hc: Option<Hc>) -> String {
957    let Some(hc) = hc else {
958        return pattern.to_string();
959    };
960    let want = hour_char(hc);
961    let mut quoted = false;
962    pattern
963        .chars()
964        .map(|c| match c {
965            '\'' => {
966                quoted = !quoted;
967                c
968            }
969            'H' | 'h' | 'K' | 'k' if !quoted => want,
970            _ => c,
971        })
972        .collect()
973}
974
975/// The `timeZone` option: UTC under any of its names, or a fixed offset.
976/// A named IANA zone is not modelled and is reported as invalid.
977fn parse_zone(z: &str) -> Result<Zone, String> {
978    let upper = z.to_ascii_uppercase();
979    const UTC_NAMES: &[&str] = &[
980        "UTC",
981        "ETC/UTC",
982        "GMT",
983        "ETC/GMT",
984        "UCT",
985        "ETC/UCT",
986        "ETC/UNIVERSAL",
987        "UNIVERSAL",
988        "ETC/ZULU",
989        "ZULU",
990        "ETC/GREENWICH",
991        "GREENWICH",
992        "GMT0",
993        "ETC/GMT0",
994        "GMT+0",
995        "GMT-0",
996        "ETC/GMT+0",
997        "ETC/GMT-0",
998    ];
999    if UTC_NAMES.contains(&upper.as_str()) {
1000        return Ok(Zone::Utc);
1001    }
1002    // `Etc/GMT+5` is five hours WEST of Greenwich.
1003    if let Some(rest) = upper.strip_prefix("ETC/GMT") {
1004        let (sign, digits) = rest.split_at(1.min(rest.len()));
1005        if let (Some(s), Ok(h)) = (
1006            match sign {
1007                "+" => Some(-1),
1008                "-" => Some(1),
1009                _ => None,
1010            },
1011            digits.parse::<i64>(),
1012        ) {
1013            if !digits.is_empty() && digits.len() <= 2 && h <= 14 && !digits.starts_with('0') {
1014                return Ok(Zone::Fixed(s * h * 60));
1015            }
1016        }
1017    }
1018    // `±HH:MM`, `±HHMM`, `±HH`.
1019    let b = z.as_bytes();
1020    if matches!(b.first(), Some(b'+') | Some(b'-')) {
1021        let sign = if b[0] == b'-' { -1 } else { 1 };
1022        let rest = &z[1..];
1023        let digits: String = rest.chars().filter(|c| *c != ':').collect();
1024        let well_formed = match rest.len() {
1025            2 => rest.bytes().all(|c| c.is_ascii_digit()),
1026            4 => rest.bytes().all(|c| c.is_ascii_digit()),
1027            5 => rest.as_bytes()[2] == b':' && digits.bytes().all(|c| c.is_ascii_digit()),
1028            _ => false,
1029        };
1030        if well_formed {
1031            let h: i64 = digits[..2].parse().unwrap_or(99);
1032            let m: i64 = digits
1033                .get(2..)
1034                .filter(|s| !s.is_empty())
1035                .map_or(Ok(0), str::parse)
1036                .unwrap_or(99);
1037            if h <= 23 && m <= 59 {
1038                return Ok(Zone::Fixed(sign * (h * 60 + m)));
1039            }
1040        }
1041    }
1042    match crate::tzif::load(z) {
1043        Some(tz) => Ok(Zone::Named(tz)),
1044        None => Err(host::range_error(&format!(
1045            "Invalid time zone specified: {z}"
1046        ))),
1047    }
1048}
1049
1050// ── rendering ────────────────────────────────────────────────────────────────
1051
1052const MONTHS_LONG: [&str; 12] = [
1053    "January",
1054    "February",
1055    "March",
1056    "April",
1057    "May",
1058    "June",
1059    "July",
1060    "August",
1061    "September",
1062    "October",
1063    "November",
1064    "December",
1065];
1066const DAYS_LONG: [&str; 7] = [
1067    "Sunday",
1068    "Monday",
1069    "Tuesday",
1070    "Wednesday",
1071    "Thursday",
1072    "Friday",
1073    "Saturday",
1074];
1075
1076/// The broken-down wall clock a pattern reads its fields from.
1077struct Fields {
1078    year: i64,
1079    month: usize,
1080    day: i64,
1081    weekday: usize,
1082    hour: i64,
1083    minute: i64,
1084    second: i64,
1085    millis: i64,
1086    /// Offset east of UTC, in seconds (a pre-1900 local mean time is not a
1087    /// whole number of minutes).
1088    offset_sec: i64,
1089    /// The zone's abbreviation at this instant (`EST`), from 1970 on; `None`
1090    /// for UTC, a fixed offset, or an earlier instant.
1091    abbrev: Option<String>,
1092    /// Whether the zone is UTC itself, which has names of its own.
1093    utc: bool,
1094    /// The zone's IANA id and whether this instant is daylight time, from 1970
1095    /// on — what its specific names (`z`, `zzzz`) are looked up by.
1096    zone: Option<(String, bool)>,
1097    /// The instant, in UTC epoch seconds.
1098    epoch_secs: i64,
1099}
1100
1101impl Format {
1102    /// Render the time value `ms` (finite) with this format.
1103    pub fn format(&self, ms: f64) -> String {
1104        let secs = (ms / 1000.0).floor() as i64;
1105        let (offset_ms, abbrev, zone) = match &self.zone {
1106            Zone::Local => (
1107                crate::stdlib::date::zone_offset_ms(ms),
1108                crate::stdlib::date::zone_abbrev(ms),
1109                crate::tznames::local_zone_id().and_then(|id| {
1110                    let dst = crate::tzif::load(&id)?.at(secs).dst;
1111                    Some((id, dst))
1112                }),
1113            ),
1114            Zone::Utc => (0.0, None, None),
1115            Zone::Fixed(m) => (*m as f64 * 60_000.0, None, None),
1116            Zone::Named(tz) => {
1117                let ty = tz.at(secs);
1118                (
1119                    ty.offset as f64 * 1000.0,
1120                    Some(ty.abbrev),
1121                    Some((tz.name.clone(), ty.dst)),
1122                )
1123            }
1124        };
1125        let local = ms + offset_ms;
1126        let (day_num, rem) = crate::stdlib::date::split_day(local);
1127        let (year, month, day) = crate::stdlib::date::civil_from_days(day_num);
1128        let f = Fields {
1129            year,
1130            month: month as usize,
1131            day,
1132            weekday: (((day_num % 7) + 4 + 7) % 7) as usize,
1133            hour: rem / 3_600_000,
1134            minute: rem / 60_000 % 60,
1135            second: rem / 1000 % 60,
1136            millis: rem % 1000,
1137            offset_sec: (offset_ms / 1000.0) as i64,
1138            // ICU maps a zone to its named metazone only from 1970 on;
1139            // before that every zone is named by its offset.
1140            utc: match &self.zone {
1141                Zone::Utc => true,
1142                Zone::Fixed(_) => false,
1143                Zone::Local => offset_ms == 0.0 && abbrev.as_deref().map_or(true, |a| a == "UTC"),
1144                Zone::Named(_) => offset_ms == 0.0 && abbrev.as_deref() == Some("UTC"),
1145            },
1146            abbrev: abbrev.filter(|_| ms >= 0.0),
1147            zone: zone.filter(|_| ms >= 0.0),
1148            epoch_secs: secs,
1149        };
1150        let pattern_has_minute = self.pattern.contains('m');
1151        let pattern_has_second = self.pattern.contains('s');
1152        let mut out = String::new();
1153        for t in tokenize(&self.pattern) {
1154            match t {
1155                Tok::Lit(s) => {
1156                    if s.len() >= 2 && s.starts_with('\'') {
1157                        let inner = &s[1..s.len() - 1];
1158                        if inner.is_empty() {
1159                            out.push('\'');
1160                        } else {
1161                            out.push_str(&inner.replace("''", "'"));
1162                        }
1163                    } else {
1164                        out.push_str(&s);
1165                    }
1166                }
1167                Tok::Field(c, n) => {
1168                    out.push_str(&self.field(c, n, &f, pattern_has_minute, pattern_has_second))
1169                }
1170            }
1171        }
1172        out
1173    }
1174
1175    fn field(&self, c: char, n: usize, f: &Fields, has_min: bool, has_sec: bool) -> String {
1176        let num = |v: i64, n: usize| format!("{:0width$}", v, width = n);
1177        let bc = f.year <= 0;
1178        match c {
1179            'G' => match (n, bc) {
1180                (1..=3, false) => "AD".into(),
1181                (1..=3, true) => "BC".into(),
1182                (4, false) => "Anno Domini".into(),
1183                (4, true) => "Before Christ".into(),
1184                (_, false) => "A".into(),
1185                (_, true) => "B".into(),
1186            },
1187            'y' => {
1188                let y = if bc { 1 - f.year } else { f.year };
1189                if n == 2 {
1190                    num(y % 100, 2)
1191                } else {
1192                    num(y, n)
1193                }
1194            }
1195            'M' | 'L' => match n {
1196                1 | 2 => num(f.month as i64 + 1, n),
1197                3 => MONTHS_LONG[f.month][..3].to_string(),
1198                4 => MONTHS_LONG[f.month].to_string(),
1199                _ => MONTHS_LONG[f.month][..1].to_string(),
1200            },
1201            'E' | 'c' => match n {
1202                4 => DAYS_LONG[f.weekday].to_string(),
1203                5 => DAYS_LONG[f.weekday][..1].to_string(),
1204                6 => DAYS_LONG[f.weekday][..2].to_string(),
1205                _ => DAYS_LONG[f.weekday][..3].to_string(),
1206            },
1207            'd' => num(f.day, n),
1208            'a' => match (n, f.hour < 12) {
1209                (5, true) => "a".into(),
1210                (5, false) => "p".into(),
1211                (_, true) => "AM".into(),
1212                (_, false) => "PM".into(),
1213            },
1214            'B' => {
1215                // en's flexible day periods. ICU never says "midnight"; it says
1216                // "noon" only when nothing finer than the hour is shown or
1217                // what is shown is zero.
1218                let noon =
1219                    f.hour == 12 && (!has_min || f.minute == 0) && (!has_sec || f.second == 0);
1220                if noon {
1221                    return if n == 5 { "n".into() } else { "noon".into() };
1222                }
1223                match f.hour {
1224                    0..=11 => "in the morning",
1225                    12..=17 => "in the afternoon",
1226                    18..=20 => "in the evening",
1227                    _ => "at night",
1228                }
1229                .into()
1230            }
1231            'h' => num(if f.hour % 12 == 0 { 12 } else { f.hour % 12 }, n),
1232            'K' => num(f.hour % 12, n),
1233            'H' => num(f.hour, n),
1234            'k' => num(if f.hour == 0 { 24 } else { f.hour }, n),
1235            'm' => num(f.minute, n),
1236            's' => num(f.second, n),
1237            'S' => {
1238                let digits = format!("{:03}", f.millis);
1239                let mut s: String = digits.chars().take(n).collect();
1240                while s.len() < n {
1241                    s.push('0');
1242                }
1243                s
1244            }
1245            'z' | 'O' | 'v' => self.zone_name(c, n, f),
1246            _ => c.to_string().repeat(n),
1247        }
1248    }
1249
1250    /// The `timeZoneName` text. UTC has names of its own. A specific name (`z`,
1251    /// `zzzz`) comes from the zone's metazone ([`crate::tznames`]), else the GMT
1252    /// offset. A generic one (`v`, `vvvv`) is known only for the zones in
1253    /// [`named_zone`], keyed by abbreviation; any other zone is named by its
1254    /// offset.
1255    fn zone_name(&self, c: char, n: usize, f: &Fields) -> String {
1256        let long = n >= 4;
1257        let utc = f.utc;
1258        if let ('z', false, Some((id, dst))) = (c, utc, &f.zone) {
1259            return crate::tznames::specific_name(id, f.epoch_secs, *dst, long)
1260                .map_or_else(|| gmt_offset(f.offset_sec, long), str::to_string);
1261        }
1262        let named = f.abbrev.as_deref().and_then(named_zone);
1263        match (c, utc, named) {
1264            ('z', true, _) if long => "Coordinated Universal Time".into(),
1265            ('z', true, _) => "UTC".into(),
1266            ('z', false, Some((_, long_name, _, _))) if long => long_name.into(),
1267            ('z', false, Some((Some(short), _, _, _))) => short.into(),
1268            ('v', false, Some((_, _, _, generic_long))) if long => generic_long.into(),
1269            ('v', false, Some((_, _, generic, _))) => generic.into(),
1270            _ => gmt_offset(f.offset_sec, long),
1271        }
1272    }
1273}
1274
1275/// `GMT-5`, `GMT+5:30` (short) or `GMT-05:00` (long); `GMT+0` / `GMT+00:00` at
1276/// zero, and a seconds part when the offset has one (`GMT-4:56:02`).
1277fn gmt_offset(secs: i64, long: bool) -> String {
1278    let sign = if secs < 0 { '-' } else { '+' };
1279    let a = secs.abs();
1280    let (h, m, s) = (a / 3600, a / 60 % 60, a % 60);
1281    let tail = if s != 0 {
1282        format!(":{s:02}")
1283    } else {
1284        String::new()
1285    };
1286    if long {
1287        format!("GMT{sign}{h:02}:{m:02}{tail}")
1288    } else if m == 0 && s == 0 {
1289        format!("GMT{sign}{h}")
1290    } else {
1291        format!("GMT{sign}{h}:{m:02}{tail}")
1292    }
1293}
1294
1295/// The zones en names by the abbreviation `localtime_r` reports:
1296/// `(short, long, short generic, long generic)`, `None` where en writes the
1297/// GMT offset instead.
1298type ZoneNames = (
1299    Option<&'static str>,
1300    &'static str,
1301    &'static str,
1302    &'static str,
1303);
1304
1305fn named_zone(abbrev: &str) -> Option<ZoneNames> {
1306    let us = |short, long, region: &'static str| -> ZoneNames {
1307        let generic: &'static str = match region {
1308            "Eastern" => "ET",
1309            "Central" => "CT",
1310            "Mountain" => "MT",
1311            "Pacific" => "PT",
1312            _ => "AKT",
1313        };
1314        let generic_long: &'static str = match region {
1315            "Eastern" => "Eastern Time",
1316            "Central" => "Central Time",
1317            "Mountain" => "Mountain Time",
1318            "Pacific" => "Pacific Time",
1319            _ => "Alaska Time",
1320        };
1321        (Some(short), long, generic, generic_long)
1322    };
1323    Some(match abbrev {
1324        "EST" => us("EST", "Eastern Standard Time", "Eastern"),
1325        "EDT" => us("EDT", "Eastern Daylight Time", "Eastern"),
1326        "CST" => us("CST", "Central Standard Time", "Central"),
1327        "CDT" => us("CDT", "Central Daylight Time", "Central"),
1328        "MST" => us("MST", "Mountain Standard Time", "Mountain"),
1329        "MDT" => us("MDT", "Mountain Daylight Time", "Mountain"),
1330        "PST" => us("PST", "Pacific Standard Time", "Pacific"),
1331        "PDT" => us("PDT", "Pacific Daylight Time", "Pacific"),
1332        "AKST" => us("AKST", "Alaska Standard Time", "Alaska"),
1333        "AKDT" => us("AKDT", "Alaska Daylight Time", "Alaska"),
1334        // Hawaii keeps no daylight time, so its generic names are its
1335        // standard ones.
1336        "HST" => (
1337            Some("HST"),
1338            "Hawaii-Aleutian Standard Time",
1339            "HST",
1340            "Hawaii-Aleutian Standard Time",
1341        ),
1342        "GMT" => (
1343            Some("GMT"),
1344            "Greenwich Mean Time",
1345            "GMT",
1346            "Greenwich Mean Time",
1347        ),
1348        _ => return None,
1349    })
1350}
1351
1352/// `Date.prototype.toLocale{,Date,Time}String(locales, options)`.
1353pub fn date_to_locale(
1354    ms: f64,
1355    opts: &Value,
1356    required: Required,
1357    method: &str,
1358) -> Result<String, String> {
1359    if ms.is_nan() {
1360        return Ok("Invalid Date".into());
1361    }
1362    Ok(resolve(opts, required, method)?.format(ms))
1363}
1364
1365#[cfg(test)]
1366mod tests {
1367    use super::*;
1368
1369    #[test]
1370    fn patterns_match_icu() {
1371        assert_eq!(best_pattern("yMd"), "M/d/y");
1372        assert_eq!(best_pattern("yMMMMEEEEd"), "EEEE, MMMM d, y");
1373        assert_eq!(best_pattern("hms"), "h:mm:ss a");
1374        assert_eq!(best_pattern("yMdhms"), "M/d/y, h:mm:ss a");
1375        assert_eq!(best_pattern("Hms"), "HH:mm:ss");
1376        assert_eq!(best_pattern("MMMMMh"), "LLLLL, h a");
1377        assert_eq!(best_pattern("ss"), "s");
1378        assert_eq!(best_pattern("ddHHs"), "dd, s ('hour': HH)");
1379    }
1380}