intl 0.5.1

Pure-Rust, no_std internationalization primitives (a pure-Rust ICU analog). The `unicode` module provides General_Category, character predicates, scripts, East Asian Width, numeric values, case mapping/folding, UAX #15 normalization (NFC/NFD/NFKC/NFKD), and UTS #10 collation — property tables compiled into const-fn match lookups, with feature-selectable codepoint ranges.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
//! Embedded CLDR locale tables (`no_std`, no `alloc`).
//!
//! The locale formatter data (number symbols/patterns, list connectors,
//! relative-time strings, currency symbols) is generated by the offline codegen
//! into flat binary blobs committed under `src/cldr/` and embedded here with
//! [`include_bytes!`]. Because the data is just bytes, this layer has no
//! dependency on the (alloc-only) formatter runtime types and compiles in every
//! configuration; only the formatting functions that build `String`s need
//! `alloc`.
//!
//! Blob layout (little-endian): `[u16 count]` then `count` records of
//! `[u8 key_len][key][u16 payload_len][payload]`. Within a payload a string is
//! `[u8 len][bytes]` and an optional string uses a leading `0xFF` for `None`.
//!
//! The whole module is `no_std`/no-`alloc` and always compiled; its accessors
//! are unused when the (alloc-gated) formatters are not built.
#![allow(dead_code)]

// ---- Shared formatter record types (plain data, borrowing from the blobs). ----

/// A resolved CLDR number pattern (affixes + grouping / fraction-digit counts).
#[derive(Debug, Clone, Copy)]
pub struct Pattern {
    /// Literal text before the number.
    pub prefix: &'static str,
    /// Literal text after the number (for percent/currency, the sign/symbol).
    pub suffix: &'static str,
    /// Minimum integer digits.
    pub min_int: u8,
    /// Minimum fraction digits.
    pub min_frac: u8,
    /// Maximum fraction digits.
    pub max_frac: u8,
    /// Primary (rightmost) grouping size, or 0 for no grouping.
    pub primary_group: u8,
    /// Secondary grouping size (e.g. 2 for Indian `#,##,##0`).
    pub secondary_group: u8,
}

/// The number symbols and patterns for one locale.
#[derive(Debug, Clone, Copy)]
pub struct NumberSpec {
    /// Decimal separator.
    pub decimal: &'static str,
    /// Grouping separator.
    pub group: &'static str,
    /// Minus sign.
    pub minus: &'static str,
    /// Plus sign.
    pub plus: &'static str,
    /// Percent sign.
    pub percent: &'static str,
    /// The standard decimal pattern.
    pub dec: Pattern,
    /// The standard percent pattern.
    pub pct: Pattern,
}

/// The four CLDR list connector patterns (each contains `{0}` and `{1}`).
#[derive(Debug, Clone, Copy)]
pub struct ListPatterns {
    /// Joins the first two items of a 3+ list.
    pub start: &'static str,
    /// Joins an accumulated head with the next middle item.
    pub middle: &'static str,
    /// Joins the accumulated head with the final item.
    pub end: &'static str,
    /// Joins exactly two items.
    pub two: &'static str,
}

/// The list patterns for one locale (both styles).
#[derive(Debug, Clone, Copy)]
pub struct ListSpec {
    /// Conjunction ("and") patterns.
    pub and: ListPatterns,
    /// Disjunction ("or") patterns.
    pub or: ListPatterns,
}

/// CLDR relative-time strings for one unit. `past`/`future` are indexed by the
/// `PluralCategory` discriminant.
#[derive(Debug, Clone, Copy)]
pub struct RelUnit {
    /// Literal for offset −1 ("yesterday"), if any.
    pub prev: Option<&'static str>,
    /// Literal for offset 0 ("today"), if any.
    pub cur: Option<&'static str>,
    /// Literal for offset +1 ("tomorrow"), if any.
    pub next: Option<&'static str>,
    /// Past patterns ("{0} days ago") by plural category.
    pub past: [Option<&'static str>; 6],
    /// Future patterns ("in {0} days") by plural category.
    pub future: [Option<&'static str>; 6],
}

/// Gregorian calendar names and patterns for one locale (full/long/medium/short
/// styles are indexed 0..4).
#[derive(Debug, Clone, Copy)]
pub struct CalendarSpec {
    /// Wide month names (January…), indexed by month−1.
    pub months_wide: [&'static str; 12],
    /// Abbreviated month names (Jan…).
    pub months_abbr: [&'static str; 12],
    /// Wide weekday names (Sunday…), indexed Sun..Sat.
    pub days_wide: [&'static str; 7],
    /// Abbreviated weekday names (Sun…).
    pub days_abbr: [&'static str; 7],
    /// AM marker.
    pub am: &'static str,
    /// PM marker.
    pub pm: &'static str,
    /// Date patterns by style.
    pub date: [&'static str; 4],
    /// Time patterns by style.
    pub time: [&'static str; 4],
    /// Date+time combining patterns by style (`{1}` date, `{0}` time).
    pub datetime: [&'static str; 4],
    /// Narrow month names (J, F, M…), indexed by month−1.
    pub months_narrow: [&'static str; 12],
    /// Narrow weekday names (S, M, T…), indexed Sun..Sat.
    pub days_narrow: [&'static str; 7],
    /// Wide era names (Before Christ, Anno Domini), indexed 0 = BCE, 1 = CE.
    pub eras_wide: [&'static str; 2],
    /// Abbreviated era names (BC, AD).
    pub eras_abbr: [&'static str; 2],
    /// Narrow era names (B, A).
    pub eras_narrow: [&'static str; 2],
    /// Wide flexible day-period names, indexed by the day-period key order
    /// (midnight, noon, morning1, morning2, afternoon1, afternoon2, evening1,
    /// evening2, night1, night2); `None` where the locale has no such period.
    pub day_periods_wide: [Option<&'static str>; 10],
    /// Abbreviated flexible day-period names (same indexing).
    pub day_periods_abbr: [Option<&'static str>; 10],
    /// Narrow flexible day-period names (same indexing).
    pub day_periods_narrow: [Option<&'static str>; 10],
    /// Minute-resolution flexible day-period range rules: a packed list of
    /// `[u16 from_minute][u16 to_minute][u8 period_index]` records (each 5 bytes,
    /// non-wrapping, `from < to`). A minute-of-day falling in `[from, to)` maps to
    /// `period_index` (an index into the `day_periods_*` arrays). The `_at`
    /// midnight/noon points are applied by the caller at the exact instant.
    pub day_period_rules: &'static [u8],
}

impl CalendarSpec {
    /// The flexible day-period index for a `minute` of day (0..=1439) from the
    /// locale's CLDR range rules, or `0xFF` if no range covers it.
    #[cfg(feature = "datetime")]
    pub(crate) fn day_period_index(&self, minute: u16) -> u8 {
        let b = self.day_period_rules;
        let mut o = 0;
        while o + 5 <= b.len() {
            let from = u16::from_le_bytes([b[o], b[o + 1]]);
            let to = u16::from_le_bytes([b[o + 2], b[o + 3]]);
            let idx = b[o + 4];
            o += 5;
            if minute >= from && minute < to {
                return idx;
            }
        }
        0xFF
    }
}

/// CLDR relative-time strings for all units of one locale.
#[derive(Debug, Clone, Copy)]
pub struct RelativeSpec {
    /// One [`RelUnit`] per relative unit (year, month, week, day, hour, minute,
    /// second).
    pub units: [RelUnit; 7],
}

// ---- Embedded blobs. ----

#[cfg(feature = "number")]
const NUMBERS: &[u8] = include_bytes!("cldr/numbers.bin");
#[cfg(feature = "list")]
const LISTS: &[u8] = include_bytes!("cldr/lists.bin");
#[cfg(feature = "relative")]
const RELATIVE: &[u8] = include_bytes!("cldr/relative.bin");
#[cfg(feature = "currency")]
const CURRENCY: &[u8] = include_bytes!("cldr/currency.bin");
#[cfg(feature = "currency")]
const CURRENCY_DIGITS: &[u8] = include_bytes!("cldr/currency_digits.bin");
#[cfg(feature = "displaynames")]
const DISPLAY_LANG: &[u8] = include_bytes!("cldr/display_languages.bin");
#[cfg(feature = "displaynames")]
const DISPLAY_TERR: &[u8] = include_bytes!("cldr/display_territories.bin");
#[cfg(feature = "units")]
const UNITS: &[u8] = include_bytes!("cldr/units.bin");
#[cfg(feature = "datetime")]
const CALENDAR: &[u8] = include_bytes!("cldr/calendar.bin");
#[cfg(feature = "datetime")]
const SKELETONS: &[u8] = include_bytes!("cldr/skeletons.bin");
#[cfg(feature = "datetime")]
const INTERVALS: &[u8] = include_bytes!("cldr/intervals.bin");
#[cfg(feature = "locale")]
const LIKELY: &[u8] = include_bytes!("cldr/likely.bin");
#[cfg(feature = "locale")]
const ALIASES: &[u8] = include_bytes!("cldr/aliases.bin");
#[cfg(feature = "locale")]
const BCP47: &[u8] = include_bytes!("cldr/bcp47.bin");
#[cfg(feature = "datetime")]
const TIMEZONE: &[u8] = include_bytes!("cldr/timezone.bin");
#[cfg(feature = "spellout")]
const RBNF: &[u8] = include_bytes!("cldr/rbnf.bin");
#[cfg(feature = "number")]
const COMPACT: &[u8] = include_bytes!("cldr/compact.bin");
#[cfg(feature = "number")]
const NUMSYS_DIGITS: &[u8] = include_bytes!("cldr/numsys_digits.bin");
#[cfg(feature = "number")]
const NUMSYS_DEFAULT: &[u8] = include_bytes!("cldr/numsys_default.bin");
#[cfg(feature = "number")]
const ORDSUFFIX: &[u8] = include_bytes!("cldr/ordsuffix.bin");
#[cfg(feature = "collation")]
const COLLATION: &[u8] = include_bytes!("cldr/collation.bin");
#[cfg(feature = "calendars-extra")]
const ISLAMIC: &[u8] = include_bytes!("cldr/islamic.bin");
#[cfg(feature = "calendars-extra")]
const PERSIAN: &[u8] = include_bytes!("cldr/persian.bin");
#[cfg(feature = "calendars-extra")]
const CHINESE: &[u8] = include_bytes!("cldr/chinese.bin");
#[cfg(feature = "calendars-extra")]
const JAPANESE: &[u8] = include_bytes!("cldr/japanese.bin");
#[cfg(feature = "calendars-extra")]
const JAPANESE_HIST: &[u8] = include_bytes!("cldr/japanese_hist.bin");

/// The CLDR collation tailoring rule string for an exact (lowercased) locale
/// key, or `None`. Used by `unicode::collate::Tailoring::for_locale`.
#[cfg(feature = "collation")]
pub(crate) fn collation_rule(lang: &str) -> Option<&'static str> {
    core::str::from_utf8(rbnf_like_payload(COLLATION, lang)?).ok()
}

/// Look up a `[u16 count]`-prefixed `(key, payload)` blob by exact key.
#[cfg(feature = "collation")]
fn rbnf_like_payload(blob: &'static [u8], lang: &str) -> Option<&'static [u8]> {
    let count = rd_u16(blob, 0);
    let mut o = 2;
    for _ in 0..count {
        let klen = blob[o] as usize;
        o += 1;
        let k = &blob[o..o + klen];
        o += klen;
        let plen = rd_u16(blob, o);
        o += 2;
        if k == lang.as_bytes() {
            return Some(&blob[o..o + plen]);
        }
        o += plen;
    }
    None
}

/// The ordinal suffix for `category` (0=zero…5=other) in an exact (lowercased)
/// locale key.
#[cfg(feature = "number")]
pub(crate) fn ordinal_suffix(lang: &str, category: usize) -> Option<&'static str> {
    let mut c = find(ORDSUFFIX, lang)?;
    let mut s = "";
    for i in 0..6 {
        let v = c.str();
        if i == category {
            s = v;
        }
    }
    Some(s)
}

/// The 10 digit glyphs of a numbering system (e.g. `"arab"` → `"٠١٢٣٤٥٦٧٨٩"`).
#[cfg(feature = "number")]
pub(crate) fn numbering_digits(system: &str) -> Option<&'static str> {
    find(NUMSYS_DIGITS, system).map(|mut c| c.str())
}

/// The default numbering system for an exact (lowercased) locale key.
#[cfg(feature = "number")]
pub(crate) fn default_numbering(lang: &str) -> Option<&'static str> {
    find(NUMSYS_DEFAULT, lang).map(|mut c| c.str())
}

/// Compact (short) decimal patterns for magnitudes 10³…10¹⁴ in an exact
/// (lowercased) locale key.
#[cfg(feature = "number")]
pub(crate) fn compact_patterns(lang: &str) -> Option<[&'static str; 24]> {
    let mut c = find(COMPACT, lang)?;
    Some(core::array::from_fn(|_| c.str()))
}

/// The raw RBNF payload bytes for an exact (lowercased) locale key (parsed by
/// the `spellout` module).
#[cfg(feature = "spellout")]
pub(crate) fn rbnf_payload(lang: &str) -> Option<&'static [u8]> {
    let count = rd_u16(RBNF, 0);
    let mut o = 2;
    for _ in 0..count {
        let klen = RBNF[o] as usize;
        o += 1;
        let k = &RBNF[o..o + klen];
        o += klen;
        let plen = rd_u16(RBNF, o);
        o += 2;
        if k == lang.as_bytes() {
            return Some(&RBNF[o..o + plen]);
        }
        o += plen;
    }
    None
}

/// Month names + patterns for a non-Gregorian calendar (Islamic, Persian) in one
/// locale. Calendars with at most 12 named months share this shape.
#[derive(Debug, Clone, Copy)]
pub struct AltCalSpec {
    /// Wide month names, indexed by month−1.
    pub months_wide: [&'static str; 12],
    /// Abbreviated month names.
    pub months_abbr: [&'static str; 12],
    /// Wide era names, indexed 0 = current era (`"Anno Hegirae"` / `"AP"`),
    /// 1 = pre-era (`"Before Hijrah"` / `"BP"`; empty when the calendar defines
    /// only one era, as Persian does).
    pub eras_wide: [&'static str; 2],
    /// Abbreviated era names (e.g. `"AH"`/`"BH"`, `"AP"`).
    pub eras_abbr: [&'static str; 2],
    /// Narrow era names.
    pub eras_narrow: [&'static str; 2],
    /// Date patterns by style (full/long/medium/short).
    pub date: [&'static str; 4],
}

#[cfg(feature = "calendars-extra")]
fn alt_cal_spec(blob: &'static [u8], lang: &str) -> Option<AltCalSpec> {
    let mut c = find(blob, lang)?;
    Some(AltCalSpec {
        months_wide: core::array::from_fn(|_| c.str()),
        months_abbr: core::array::from_fn(|_| c.str()),
        eras_wide: [c.str(), c.str()],
        eras_abbr: [c.str(), c.str()],
        eras_narrow: [c.str(), c.str()],
        date: core::array::from_fn(|_| c.str()),
    })
}

/// Islamic-calendar names + patterns for an exact (lowercased) locale key.
#[cfg(feature = "calendars-extra")]
pub(crate) fn islamic_spec(lang: &str) -> Option<AltCalSpec> {
    alt_cal_spec(ISLAMIC, lang)
}

/// Persian-calendar names + patterns for an exact (lowercased) locale key.
#[cfg(feature = "calendars-extra")]
pub(crate) fn persian_spec(lang: &str) -> Option<AltCalSpec> {
    alt_cal_spec(PERSIAN, lang)
}

/// Chinese-calendar names + patterns for one locale: the 60 sexagenary (cyclic)
/// year names (the `U` field), numeric month names (wide + abbreviated), the
/// leap-month marker pattern (wide + abbreviated) and the four date patterns.
#[derive(Debug, Clone, Copy)]
pub struct ChineseCalSpec {
    /// The 60 sexagenary cyclic year names, indexed by the 1-based
    /// stem-branch number minus 1 (e.g. index 40 → 甲辰 / `jia-chen`). The CLDR
    /// widths are identical, so this one set serves every `U` width.
    pub cyclic: [&'static str; 60],
    /// Wide numeric month names (e.g. `"正月"` / `"First Month"`), indexed month−1.
    pub months_wide: [&'static str; 12],
    /// Abbreviated numeric month names (e.g. `"Mo1"`), indexed month−1.
    pub months_abbr: [&'static str; 12],
    /// Wide leap-month marker pattern (contains `{0}`, e.g. `"闰{0}"` / `"{0}bis"`).
    pub leap_wide: &'static str,
    /// Abbreviated leap-month marker pattern.
    pub leap_abbr: &'static str,
    /// Date patterns by style (full/long/medium/short).
    pub date: [&'static str; 4],
}

/// Chinese-calendar names + patterns for an exact (lowercased) locale key.
#[cfg(feature = "calendars-extra")]
pub(crate) fn chinese_spec(lang: &str) -> Option<ChineseCalSpec> {
    let mut c = find(CHINESE, lang)?;
    Some(ChineseCalSpec {
        cyclic: core::array::from_fn(|_| c.str()),
        months_wide: core::array::from_fn(|_| c.str()),
        months_abbr: core::array::from_fn(|_| c.str()),
        leap_wide: c.str(),
        leap_abbr: c.str(),
        date: core::array::from_fn(|_| c.str()),
    })
}

/// Japanese-calendar data for one locale: the 5 modern eras (Meiji, Taishō,
/// Shōwa, Heisei, Reiwa) in three widths and the four date patterns. The Japanese
/// calendar shares the Gregorian month and weekday names, so only the era and the
/// (year-within-era) year field differ; those names are taken from the Gregorian
/// [`CalendarSpec`] by the caller.
#[derive(Debug, Clone, Copy)]
pub struct JapaneseCalSpec {
    /// Wide era names (`eraNames`), indexed by modern-era number (0 = Meiji …
    /// 4 = Reiwa). Used for the `GGGG` field width.
    pub eras_wide: [&'static str; 5],
    /// Abbreviated era names (`eraAbbr`); the `G`/`GG`/`GGG` field width.
    pub eras_abbr: [&'static str; 5],
    /// Narrow era names (`eraNarrow`, e.g. `"R"`); the `GGGGG` field width.
    pub eras_narrow: [&'static str; 5],
    /// Date patterns by style (full/long/medium/short). Every pattern carries a
    /// `G` (era) field.
    pub date: [&'static str; 4],
    /// Gannen bitmask: bit `i` (full=0, long=1, medium=2, short=3) is set when
    /// that style's year field uses the `jpanyear` numbering system, i.e. year 1
    /// of an era prints as 元 (gannen) instead of `1`.
    pub gannen: u8,
}

/// Japanese-calendar names + patterns for an exact (lowercased) locale key.
#[cfg(feature = "calendars-extra")]
pub(crate) fn japanese_spec(lang: &str) -> Option<JapaneseCalSpec> {
    let mut c = find(JAPANESE, lang)?;
    Some(JapaneseCalSpec {
        eras_wide: core::array::from_fn(|_| c.str()),
        eras_abbr: core::array::from_fn(|_| c.str()),
        eras_narrow: core::array::from_fn(|_| c.str()),
        date: core::array::from_fn(|_| c.str()),
        gannen: c.u8(),
    })
}

/// Number of pre-Meiji historical Japanese era names in `japanese_hist.bin`
/// (CLDR era indices 0 = Taika .. 231 = Keiō); must match codegen's
/// `HIST_ERA_COUNT`.
#[cfg(feature = "calendars-extra")]
pub(crate) const HIST_ERA_COUNT: usize = 232;

/// The localized pre-Meiji nengō (era) name for CLDR era `index` (0..=231) in
/// an exact (lowercased) locale key, as `[wide, abbr, narrow]`, or `None` if the
/// locale is absent. See `emit_japanese_hist` for the blob layout.
#[cfg(feature = "calendars-extra")]
pub(crate) fn japanese_hist_eras(lang: &str, index: usize) -> Option<[&'static str; 3]> {
    if index >= HIST_ERA_COUNT {
        return None;
    }
    let b = JAPANESE_HIST;
    let nloc = rd_u16(b, 0);
    let mut o = 2;
    let mut setid: Option<usize> = None;
    for _ in 0..nloc {
        let klen = b[o] as usize;
        o += 1;
        let k = &b[o..o + klen];
        o += klen;
        let sid = rd_u16(b, o);
        o += 2;
        if k == lang.as_bytes() {
            setid = Some(sid);
        }
    }
    let setid = setid?;
    let nsets = rd_u16(b, o);
    o += 2;
    let table = o;
    let sets_base = table + nsets * 4;
    let set_off = rd_u32(b, table + setid * 4);
    let mut c = Cursor {
        b,
        o: sets_base + set_off,
    };
    let mut res = [""; 3];
    for slot in &mut res {
        for i in 0..HIST_ERA_COUNT {
            let s = c.str();
            if i == index {
                *slot = s;
            }
        }
    }
    Some(res)
}

/// Localized GMT offset formats for one locale.
#[derive(Debug, Clone, Copy)]
pub struct TzSpec {
    /// The GMT pattern, e.g. `"GMT{0}"` / `"UTC{0}"`.
    pub gmt: &'static str,
    /// The zero-offset form, e.g. `"GMT"` / `"UTC"`.
    pub zero: &'static str,
    /// The `+HH:mm;-HH:mm` hour format (positive/negative subpatterns).
    pub hour: &'static str,
}

/// Localized GMT offset formats for an exact (lowercased) locale key.
#[cfg(feature = "datetime")]
pub(crate) fn tz_spec(lang: &str) -> Option<TzSpec> {
    let mut c = find(TIMEZONE, lang)?;
    Some(TzSpec {
        gmt: c.str(),
        zero: c.str(),
        hour: c.str(),
    })
}

/// The maximized locale for a likelySubtags key (e.g. `"en"` → `"en-Latn-US"`).
#[cfg(feature = "locale")]
pub(crate) fn likely_subtags(key: &str) -> Option<&'static str> {
    find(LIKELY, key).map(|mut c| c.str())
}

/// Look up a CLDR deprecated-subtag alias by its type-prefixed key and return
/// the replacement, or `None`. The 1-char prefix selects the alias kind: `'l'`
/// language / grandfathered whole tag, `'s'` script, `'t'` territory, `'v'`
/// variant (e.g. `"liw"` → `"he"`, `"sQaai"` → `"Zinh"`, `"tBU"` → `"MM"`). A
/// multi-subtag or one→many replacement is returned space-separated. This module
/// is alloc-free, so the caller (in `locale.rs`) builds the prefixed key.
#[cfg(feature = "locale")]
pub(crate) fn alias_lookup(prefixed_key: &str) -> Option<&'static str> {
    find(ALIASES, prefixed_key).map(|mut c| c.str())
}

/// Canonical replacement for a deprecated `-u-`/`-t-` extension type value, or
/// `None`. The key is `"<keyword>/<value>"` lowercased, e.g. `"ca/islamicc"` →
/// `"islamic-civil"`, `"ms/imperial"` → `"uksystem"`, `"m0/names"` → `"prprname"`.
/// The returned value keeps CLDR `-` subtag separators.
#[cfg(feature = "locale")]
pub(crate) fn bcp47_type_alias(keyword_and_value: &str) -> Option<&'static str> {
    find(BCP47, keyword_and_value).map(|mut c| c.str())
}

/// Number of curated units (must match codegen's `UNITS` and the `Unit` enum).
pub(crate) const UNIT_COUNT: usize = 28;

fn rd_u16(b: &[u8], o: usize) -> usize {
    u16::from_le_bytes([b[o], b[o + 1]]) as usize
}

#[cfg(feature = "calendars-extra")]
fn rd_u32(b: &[u8], o: usize) -> usize {
    u32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]]) as usize
}

/// A forward cursor over a record payload in a `'static` blob.
struct Cursor {
    b: &'static [u8],
    o: usize,
}
impl Cursor {
    fn u8(&mut self) -> u8 {
        let v = self.b[self.o];
        self.o += 1;
        v
    }
    fn u16(&mut self) -> usize {
        let v = rd_u16(self.b, self.o);
        self.o += 2;
        v
    }
    fn str(&mut self) -> &'static str {
        let n = self.u8() as usize;
        let s = &self.b[self.o..self.o + n];
        self.o += n;
        core::str::from_utf8(s).unwrap_or("")
    }
    fn opt(&mut self) -> Option<&'static str> {
        if self.b[self.o] == 0xFF {
            self.o += 1;
            None
        } else {
            Some(self.str())
        }
    }
    fn skip_opt(&mut self) {
        if self.b[self.o] == 0xFF {
            self.o += 1;
        } else {
            let n = self.b[self.o] as usize;
            self.o += 1 + n;
        }
    }
    /// Read a length-prefixed day-period rule list: a `[u8 count]` followed by
    /// `count` 5-byte records, returned as a raw slice (parsed lazily).
    fn dp_rules(&mut self) -> &'static [u8] {
        let n = self.u8() as usize * 5;
        let s = &self.b[self.o..self.o + n];
        self.o += n;
        s
    }
    fn pattern(&mut self) -> Pattern {
        Pattern {
            prefix: self.str(),
            suffix: self.str(),
            min_int: self.u8(),
            min_frac: self.u8(),
            max_frac: self.u8(),
            primary_group: self.u8(),
            secondary_group: self.u8(),
        }
    }
}

/// Locate the record for `key` and return a cursor at its payload.
fn find(blob: &'static [u8], key: &str) -> Option<Cursor> {
    let count = rd_u16(blob, 0);
    let mut o = 2;
    for _ in 0..count {
        let klen = blob[o] as usize;
        o += 1;
        let k = &blob[o..o + klen];
        o += klen;
        let plen = rd_u16(blob, o);
        o += 2;
        if k == key.as_bytes() {
            return Some(Cursor { b: blob, o });
        }
        o += plen;
    }
    None
}

/// Number symbols + patterns for an exact (lowercased) locale key.
#[cfg(feature = "number")]
pub(crate) fn number_spec(lang: &str) -> Option<NumberSpec> {
    let mut c = find(NUMBERS, lang)?;
    Some(NumberSpec {
        decimal: c.str(),
        group: c.str(),
        minus: c.str(),
        plus: c.str(),
        percent: c.str(),
        dec: c.pattern(),
        pct: c.pattern(),
    })
}

fn list_patterns(c: &mut Cursor) -> ListPatterns {
    ListPatterns {
        start: c.str(),
        middle: c.str(),
        end: c.str(),
        two: c.str(),
    }
}

/// List connector patterns for an exact (lowercased) locale key.
#[cfg(feature = "list")]
pub(crate) fn list_spec(lang: &str) -> Option<ListSpec> {
    let mut c = find(LISTS, lang)?;
    Some(ListSpec {
        and: list_patterns(&mut c),
        or: list_patterns(&mut c),
    })
}

/// Relative-time strings for an exact (lowercased) locale key.
#[cfg(feature = "relative")]
pub(crate) fn relative_spec(lang: &str) -> Option<RelativeSpec> {
    let mut c = find(RELATIVE, lang)?;
    let units = core::array::from_fn(|_| RelUnit {
        prev: c.opt(),
        cur: c.opt(),
        next: c.opt(),
        past: core::array::from_fn(|_| c.opt()),
        future: core::array::from_fn(|_| c.opt()),
    });
    Some(RelativeSpec { units })
}

/// Standard currency pattern for an exact (lowercased) locale key.
#[cfg(feature = "currency")]
pub(crate) fn currency_pattern(lang: &str) -> Option<Pattern> {
    let mut c = find(CURRENCY, lang)?;
    Some(c.pattern())
}

/// The currency unit pattern (number + code/name, e.g. `"{0} {1}"`) for `lang`.
#[cfg(feature = "currency")]
pub(crate) fn currency_unit_pattern(lang: &str) -> Option<&'static str> {
    let mut c = find(CURRENCY, lang)?;
    let _ = c.pattern();
    Some(c.str())
}

/// Currency display forms `(symbol, narrow symbol, display name)` for `code` in
/// `lang` (exact lowercased key), if present.
#[cfg(feature = "currency")]
pub(crate) fn currency_forms(
    lang: &str,
    code: &str,
) -> Option<(&'static str, &'static str, &'static str)> {
    let mut c = find(CURRENCY, lang)?;
    let _ = c.pattern();
    let _ = c.str(); // unit pattern
    let n = c.u16();
    for _ in 0..n {
        let cd = c.str();
        let sym = c.str();
        let narrow = c.str();
        let name = c.str();
        if cd == code {
            return Some((sym, narrow, name));
        }
    }
    None
}

/// Default fraction digits for a currency code (2 if unknown).
#[cfg(feature = "currency")]
pub(crate) fn currency_digits(code: &str) -> u8 {
    match find(CURRENCY_DIGITS, code) {
        Some(mut c) => c.u8(),
        None => 2,
    }
}

/// Look up `code`'s display name in `display_locale`'s nested code→name table.
fn display_name(blob: &'static [u8], display_locale: &str, code: &str) -> Option<&'static str> {
    let mut c = find(blob, display_locale)?;
    let count = c.u16();
    for _ in 0..count {
        let cd = c.str();
        let name = c.str();
        if cd == code {
            return Some(name);
        }
    }
    None
}

/// Display name of language `code` in `display_locale` (exact lowercased keys).
#[cfg(feature = "displaynames")]
pub(crate) fn language_name(display_locale: &str, code: &str) -> Option<&'static str> {
    display_name(DISPLAY_LANG, display_locale, code)
}

/// The date pattern for a CLDR `skeleton` (e.g. `"yMMMd"`) in an exact
/// (lowercased) locale key; skeletons are matched case-sensitively.
#[cfg(feature = "datetime")]
pub(crate) fn skeleton_pattern(lang: &str, skeleton: &str) -> Option<&'static str> {
    display_name(SKELETONS, lang, skeleton)
}

/// The CLDR `intervalFormatFallback` string (e.g. `"{0} – {1}"`) for an exact
/// (lowercased) locale key.
#[cfg(feature = "datetime")]
pub(crate) fn interval_fallback(lang: &str) -> Option<&'static str> {
    find(INTERVALS, lang).map(|mut c| c.str())
}

/// The CLDR interval pattern for a `skeleton` (e.g. `"yMMMd"`) whose greatest
/// differing field is `field` (a CLDR field letter byte such as `b'y'`), in an
/// exact (lowercased) locale key. Skeletons are matched case-sensitively.
#[cfg(feature = "datetime")]
pub(crate) fn interval_pattern(lang: &str, skeleton: &str, field: u8) -> Option<&'static str> {
    let mut c = find(INTERVALS, lang)?;
    let _fallback = c.str();
    let count = c.u16();
    for _ in 0..count {
        let sk = c.str();
        let fcount = c.u8();
        let mut found: Option<&'static str> = None;
        for _ in 0..fcount {
            let letter = c.u8();
            let pat = c.str();
            if sk == skeleton && letter == field {
                found = Some(pat);
            }
        }
        if sk == skeleton {
            return found;
        }
    }
    None
}

/// Display name of region `code` in `display_locale`.
#[cfg(feature = "displaynames")]
pub(crate) fn region_name(display_locale: &str, code: &str) -> Option<&'static str> {
    display_name(DISPLAY_TERR, display_locale, code)
}

/// Gregorian calendar names + patterns for an exact (lowercased) locale key.
#[cfg(feature = "datetime")]
pub(crate) fn calendar_spec(lang: &str) -> Option<CalendarSpec> {
    let mut c = find(CALENDAR, lang)?;
    Some(CalendarSpec {
        months_wide: core::array::from_fn(|_| c.str()),
        months_abbr: core::array::from_fn(|_| c.str()),
        days_wide: core::array::from_fn(|_| c.str()),
        days_abbr: core::array::from_fn(|_| c.str()),
        am: c.str(),
        pm: c.str(),
        date: core::array::from_fn(|_| c.str()),
        time: core::array::from_fn(|_| c.str()),
        datetime: core::array::from_fn(|_| c.str()),
        months_narrow: core::array::from_fn(|_| c.str()),
        days_narrow: core::array::from_fn(|_| c.str()),
        eras_wide: core::array::from_fn(|_| c.str()),
        eras_abbr: core::array::from_fn(|_| c.str()),
        eras_narrow: core::array::from_fn(|_| c.str()),
        day_periods_wide: core::array::from_fn(|_| c.opt()),
        day_periods_abbr: core::array::from_fn(|_| c.opt()),
        day_periods_narrow: core::array::from_fn(|_| c.opt()),
        day_period_rules: c.dp_rules(),
    })
}

/// Unit pattern for `(width, unit, plural category)` in an exact locale key,
/// falling back to the `other` category. `width` is 0 (long) or 1 (short).
#[cfg(feature = "units")]
pub(crate) fn unit_pattern(
    lang: &str,
    width: usize,
    unit: usize,
    cat: usize,
) -> Option<&'static str> {
    let mut c = find(UNITS, lang)?;
    // Skip to this (width, unit)'s block of 6 plural-count slots.
    let base = (width * UNIT_COUNT + unit) * 6;
    for _ in 0..base {
        c.skip_opt();
    }
    let slots: [Option<&'static str>; 6] = core::array::from_fn(|_| c.opt());
    slots[cat].or(slots[5])
}