intl 0.3.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
//! 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],
}

/// 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. ----

const NUMBERS: &[u8] = include_bytes!("cldr/numbers.bin");
const LISTS: &[u8] = include_bytes!("cldr/lists.bin");
const RELATIVE: &[u8] = include_bytes!("cldr/relative.bin");
const CURRENCY: &[u8] = include_bytes!("cldr/currency.bin");
const CURRENCY_DIGITS: &[u8] = include_bytes!("cldr/currency_digits.bin");
const DISPLAY_LANG: &[u8] = include_bytes!("cldr/display_languages.bin");
const DISPLAY_TERR: &[u8] = include_bytes!("cldr/display_territories.bin");
const UNITS: &[u8] = include_bytes!("cldr/units.bin");
const CALENDAR: &[u8] = include_bytes!("cldr/calendar.bin");
const SKELETONS: &[u8] = include_bytes!("cldr/skeletons.bin");
const LIKELY: &[u8] = include_bytes!("cldr/likely.bin");
const TIMEZONE: &[u8] = include_bytes!("cldr/timezone.bin");
const RBNF: &[u8] = include_bytes!("cldr/rbnf.bin");
const COMPACT: &[u8] = include_bytes!("cldr/compact.bin");
const NUMSYS_DIGITS: &[u8] = include_bytes!("cldr/numsys_digits.bin");
const NUMSYS_DEFAULT: &[u8] = include_bytes!("cldr/numsys_default.bin");
const ORDSUFFIX: &[u8] = include_bytes!("cldr/ordsuffix.bin");
#[cfg(feature = "collation")]
const COLLATION: &[u8] = include_bytes!("cldr/collation.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.
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"` → `"٠١٢٣٤٥٦٧٨٩"`).
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.
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.
pub(crate) fn compact_patterns(lang: &str) -> Option<[&'static str; 12]> {
    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).
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
}
const ISLAMIC: &[u8] = include_bytes!("cldr/islamic.bin");
const PERSIAN: &[u8] = include_bytes!("cldr/persian.bin");

/// 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],
    /// Era abbreviation (e.g. `"AH"`, `"AP"`).
    pub era: &'static str,
    /// Date patterns by style (full/long/medium/short).
    pub date: [&'static str; 4],
}

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()),
        era: c.str(),
        date: core::array::from_fn(|_| c.str()),
    })
}

/// Islamic-calendar names + patterns for an exact (lowercased) locale key.
pub(crate) fn islamic_spec(lang: &str) -> Option<AltCalSpec> {
    alt_cal_spec(ISLAMIC, lang)
}

/// Persian-calendar names + patterns for an exact (lowercased) locale key.
pub(crate) fn persian_spec(lang: &str) -> Option<AltCalSpec> {
    alt_cal_spec(PERSIAN, lang)
}

/// 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.
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"`).
pub(crate) fn likely_subtags(key: &str) -> Option<&'static str> {
    find(LIKELY, key).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
}

/// 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;
        }
    }
    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.
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.
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.
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.
pub(crate) fn currency_pattern(lang: &str) -> Option<Pattern> {
    let mut c = find(CURRENCY, lang)?;
    Some(c.pattern())
}

/// Currency symbol for `code` in `lang` (exact lowercased key), if present.
pub(crate) fn currency_symbol(lang: &str, code: &str) -> Option<&'static str> {
    let mut c = find(CURRENCY, lang)?;
    let _ = c.pattern();
    let n = c.u8();
    for _ in 0..n {
        let cd = c.str();
        let sym = c.str();
        if cd == code {
            return Some(sym);
        }
    }
    None
}

/// Default fraction digits for a currency code (2 if unknown).
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).
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.
pub(crate) fn skeleton_pattern(lang: &str, skeleton: &str) -> Option<&'static str> {
    display_name(SKELETONS, lang, skeleton)
}

/// Display name of region `code` in `display_locale`.
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.
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()),
    })
}

/// 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).
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])
}