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
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
//! Locale-aware date and time formatting (CLDR / UTS #35, Gregorian).
//! Requires the `alloc` feature.
//!
//! A [`DateTime`] holds the broken-down fields (no calendar arithmetic or time
//! zones); [`format_date`] / [`format_time`] / [`format_datetime`] render it with
//! the locale's CLDR patterns, month/weekday names, and am/pm markers. The
//! weekday is derived from the proleptic Gregorian date.
//!
//! ```
//! use intl::datetime::{DateTime, format_date, format_time, DateStyle};
//! let dt = DateTime { year: 2026, month: 6, day: 4, hour: 14, minute: 30, second: 5 };
//! assert_eq!(format_date("en", &dt, DateStyle::Long), "June 4, 2026");
//! assert_eq!(format_date("en", &dt, DateStyle::Medium), "Jun 4, 2026");
//! assert_eq!(format_time("en", &dt, DateStyle::Short), "2:30\u{202f}PM");
//! ```

use crate::cldr::{calendar_spec, CalendarSpec};
use alloc::string::{String, ToString};
use alloc::vec::Vec;

/// A broken-down Gregorian date and time. Fields are not validated.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DateTime {
    /// Proleptic Gregorian year (e.g. 2026).
    pub year: i32,
    /// Month, 1–12.
    pub month: u8,
    /// Day of month, 1–31.
    pub day: u8,
    /// Hour, 0–23.
    pub hour: u8,
    /// Minute, 0–59.
    pub minute: u8,
    /// Second, 0–59.
    pub second: u8,
}

impl DateTime {
    /// Render as a machine-readable ISO-8601 timestamp
    /// (`YYYY-MM-DDTHH:MM:SS`), independent of locale.
    #[must_use]
    pub fn to_iso8601(&self) -> String {
        alloc::format!(
            "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}",
            self.year,
            self.month,
            self.day,
            self.hour,
            self.minute,
            self.second
        )
    }

    /// The ISO-8601 weekday: 1 = Monday … 7 = Sunday.
    #[must_use]
    pub fn weekday(&self) -> u8 {
        crate::calendar::day_of_week(self.year as i64, self.month as i64, self.day as i64)
    }

    /// This date-time advanced by `delta` seconds (negative to go back), with
    /// day/month/year carry handled through the proleptic Gregorian calendar.
    ///
    /// ```
    /// use intl::datetime::DateTime;
    /// let dt = DateTime { year: 2026, month: 12, day: 31, hour: 23, minute: 59, second: 30 };
    /// let next = dt.add_seconds(90); // crosses into the new year
    /// assert_eq!(next, DateTime { year: 2027, month: 1, day: 1, hour: 0, minute: 1, second: 0 });
    /// ```
    #[must_use]
    pub fn add_seconds(&self, delta: i64) -> DateTime {
        let jdn =
            crate::calendar::gregorian_to_jdn(self.year as i64, self.month as i64, self.day as i64);
        // Saturating arithmetic: an extreme year combined with an extreme delta
        // would otherwise overflow i64 and panic in debug builds.
        let total = jdn
            .saturating_mul(86_400)
            .saturating_add(self.hour as i64 * 3600)
            .saturating_add(self.minute as i64 * 60)
            .saturating_add(self.second as i64)
            .saturating_add(delta);
        let (new_jdn, sod) = (total.div_euclid(86_400), total.rem_euclid(86_400));
        let (y, m, d) = crate::calendar::jdn_to_gregorian(new_jdn);
        DateTime {
            year: y as i32,
            month: m as u8,
            day: d as u8,
            hour: (sod / 3600) as u8,
            minute: (sod % 3600 / 60) as u8,
            second: (sod % 60) as u8,
        }
    }

    /// This date advanced by `delta` whole days (keeping the time of day).
    #[must_use]
    pub fn add_days(&self, delta: i64) -> DateTime {
        self.add_seconds(delta * 86_400)
    }

    /// Parse an ISO-8601 timestamp such as `"2026-06-04T14:30:05"`. Accepts a
    /// space instead of `T`, an omitted time or seconds, and a trailing `Z`.
    /// Returns `None` if malformed. (A time-zone offset, if present, is ignored.)
    #[must_use]
    pub fn parse_iso8601(s: &str) -> Option<DateTime> {
        let s = s.trim().trim_end_matches('Z');
        let (date, time) = match s.split_once(['T', ' ']) {
            Some((d, t)) => (d, Some(t)),
            None => (s, None),
        };
        let mut dp = date.split('-');
        let year: i32 = dp.next()?.parse().ok()?;
        let month: u8 = dp.next()?.parse().ok()?;
        let day: u8 = dp.next()?.parse().ok()?;
        if dp.next().is_some() || !(1..=12).contains(&month) || !(1..=31).contains(&day) {
            return None;
        }
        let (hour, minute, second) = match time {
            None => (0, 0, 0),
            Some(t) => {
                // Drop any zone offset on the time component.
                let t = t.split(['+', '-']).next().unwrap_or(t);
                let mut tp = t.split(':');
                let h: u8 = tp.next()?.parse().ok()?;
                let mi: u8 = tp.next()?.parse().ok()?;
                let se: u8 = match tp.next() {
                    Some(x) => x.parse().ok()?,
                    None => 0,
                };
                (h, mi, se)
            }
        };
        Some(DateTime {
            year,
            month,
            day,
            hour,
            minute,
            second,
        })
    }
}

/// One of the four CLDR length styles.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DateStyle {
    /// Full ("Thursday, June 4, 2026").
    Full,
    /// Long ("June 4, 2026").
    Long,
    /// Medium ("Jun 4, 2026").
    Medium,
    /// Short ("6/4/26").
    Short,
}

impl DateStyle {
    fn idx(self) -> usize {
        match self {
            DateStyle::Full => 0,
            DateStyle::Long => 1,
            DateStyle::Medium => 2,
            DateStyle::Short => 3,
        }
    }
}

/// Day of week for a proleptic Gregorian date: 0 = Sunday … 6 = Saturday
/// (Sakamoto's algorithm).
fn weekday(dt: &DateTime) -> usize {
    let t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
    // Compute in i64: i32 year arithmetic here overflows for extreme years (and
    // `year - 1` underflows at i32::MIN) on unvalidated DateTime input.
    let m = (dt.month as i64).clamp(1, 12);
    let d = dt.day as i64;
    let y = if m < 3 {
        dt.year as i64 - 1
    } else {
        dt.year as i64
    };
    (y + y / 4 - y / 100 + y / 400 + t[(m - 1) as usize] + d).rem_euclid(7) as usize
}

fn two(n: i64) -> String {
    alloc::format!("{n:02}")
}

/// Render one date-field run (`field` repeated `n` times) of a CLDR pattern.
fn field(field: char, n: usize, dt: &DateTime, s: &CalendarSpec) -> String {
    let m = dt.month as usize;
    // Index for the 12-element month-name arrays, clamped so an out-of-range
    // (unvalidated) month never indexes out of bounds.
    let mi = m.clamp(1, 12) - 1;
    match field {
        'y' | 'Y' => {
            if n == 2 {
                two((dt.year.rem_euclid(100)) as i64)
            } else {
                dt.year.to_string()
            }
        }
        'M' | 'L' => match n {
            1 => m.to_string(),
            2 => two(m as i64),
            3 => s.months_abbr[mi].to_string(),
            _ => s.months_wide[mi].to_string(),
        },
        'd' => {
            if n >= 2 {
                two(dt.day as i64)
            } else {
                dt.day.to_string()
            }
        }
        'E' | 'e' | 'c' => {
            let w = weekday(dt);
            if n >= 4 {
                s.days_wide[w].to_string()
            } else {
                s.days_abbr[w].to_string()
            }
        }
        'h' => {
            // Widen first: `dt.hour + 11` would overflow u8 for hour > 244.
            let h = ((dt.hour as u16 + 11) % 12) + 1; // 12-hour clock
            if n >= 2 {
                two(h as i64)
            } else {
                h.to_string()
            }
        }
        'H' => {
            if n >= 2 {
                two(dt.hour as i64)
            } else {
                dt.hour.to_string()
            }
        }
        'm' => {
            if n >= 2 {
                two(dt.minute as i64)
            } else {
                dt.minute.to_string()
            }
        }
        's' => {
            if n >= 2 {
                two(dt.second as i64)
            } else {
                dt.second.to_string()
            }
        }
        'a' | 'b' => if dt.hour < 12 { s.am } else { s.pm }.to_string(),
        _ => String::new(), // unsupported field (e.g. time zone) -> nothing
    }
}

/// Interpret a CLDR date/time pattern, handling quoted literals.
fn render(pattern: &str, dt: &DateTime, s: &CalendarSpec) -> String {
    let c: Vec<char> = pattern.chars().collect();
    let mut out = String::new();
    let mut i = 0;
    while i < c.len() {
        let ch = c[i];
        if ch == '\'' {
            i += 1;
            if i < c.len() && c[i] == '\'' {
                out.push('\'');
                i += 1;
                continue;
            }
            while i < c.len() && c[i] != '\'' {
                out.push(c[i]);
                i += 1;
            }
            i += 1; // closing quote
        } else if ch.is_ascii_alphabetic() {
            let start = i;
            while i < c.len() && c[i] == ch {
                i += 1;
            }
            out.push_str(&field(ch, i - start, dt, s));
        } else {
            out.push(ch);
            i += 1;
        }
    }
    out
}

fn spec(lang: &str) -> CalendarSpec {
    let norm: String = lang
        .chars()
        .map(|c| {
            if c == '_' {
                '-'
            } else {
                c.to_ascii_lowercase()
            }
        })
        .collect();
    let mut end = norm.len();
    loop {
        if let Some(s) = calendar_spec(&norm[..end]) {
            return s;
        }
        match norm[..end].rfind('-') {
            Some(i) => end = i,
            None => return calendar_spec("en").expect("root calendar present"),
        }
    }
}

/// Format the date part of `dt` in `lang` at the given `style`.
#[must_use]
pub fn format_date(lang: &str, dt: &DateTime, style: DateStyle) -> String {
    let s = spec(lang);
    render(s.date[style.idx()], dt, &s)
}

/// Format the time part of `dt` in `lang` at the given `style`.
#[must_use]
pub fn format_time(lang: &str, dt: &DateTime, style: DateStyle) -> String {
    let s = spec(lang);
    render(s.time[style.idx()], dt, &s)
}

/// Format `dt` with a CLDR *skeleton* (e.g. `"yMMMd"`, `"Hm"`, `"MMMEd"`) — the
/// modern, flexible date API: the skeleton names the fields you want and the
/// locale supplies their order and punctuation. Falls back through the locale
/// chain (and to English), then to the medium date pattern for an unknown
/// skeleton.
///
/// ```
/// use intl::datetime::{DateTime, format_skeleton};
/// let dt = DateTime { year: 2026, month: 6, day: 4, hour: 14, minute: 30, second: 5 };
/// assert_eq!(format_skeleton("en", &dt, "yMMMd"), "Jun 4, 2026");
/// assert_eq!(format_skeleton("de", &dt, "yMMMd"), "4. Juni 2026");
/// assert_eq!(format_skeleton("en", &dt, "Hm"), "14:30");
/// ```
#[must_use]
pub fn format_skeleton(lang: &str, dt: &DateTime, skeleton: &str) -> String {
    let s = spec(lang);
    let norm: String = lang
        .chars()
        .map(|c| {
            if c == '_' {
                '-'
            } else {
                c.to_ascii_lowercase()
            }
        })
        .collect();
    let mut end = norm.len();
    let pattern = loop {
        if let Some(p) = crate::cldr::skeleton_pattern(&norm[..end], skeleton) {
            break p;
        }
        match norm[..end].rfind('-') {
            Some(i) => end = i,
            None => break crate::cldr::skeleton_pattern("en", skeleton).unwrap_or(s.date[2]),
        }
    };
    render(pattern, dt, &s)
}

/// Render a non-Gregorian date with a calendar's month names/era; the weekday
/// name (if any) uses the Gregorian day names at the date's `jdn`.
fn render_alt(
    cal: &crate::cldr::AltCalSpec,
    style: DateStyle,
    year: i64,
    month: i64,
    day: i64,
    jdn: i64,
    greg: &CalendarSpec,
) -> String {
    let wd = ((jdn.rem_euclid(7) + 1) % 7) as usize; // 0 = Sunday
    let c: Vec<char> = cal.date[style.idx()].chars().collect();
    let mut out = String::new();
    let mut i = 0;
    while i < c.len() {
        let ch = c[i];
        if ch == '\'' {
            i += 1;
            if i < c.len() && c[i] == '\'' {
                out.push('\'');
                i += 1;
                continue;
            }
            while i < c.len() && c[i] != '\'' {
                out.push(c[i]);
                i += 1;
            }
            i += 1;
        } else if ch.is_ascii_alphabetic() {
            let start = i;
            while i < c.len() && c[i] == ch {
                i += 1;
            }
            let (n, m) = (i - start, month as usize);
            let mi = m.clamp(1, 12) - 1; // unvalidated month must not index OOB
            match ch {
                'y' | 'Y' => out.push_str(&year.to_string()),
                'M' | 'L' => match n {
                    1 => out.push_str(&m.to_string()),
                    2 => out.push_str(&two(m as i64)),
                    3 => out.push_str(cal.months_abbr[mi]),
                    _ => out.push_str(cal.months_wide[mi]),
                },
                'd' => out.push_str(&day.to_string()),
                'E' | 'e' | 'c' => out.push_str(if n >= 4 {
                    greg.days_wide[wd]
                } else {
                    greg.days_abbr[wd]
                }),
                'G' => out.push_str(cal.era),
                _ => {}
            }
        } else {
            out.push(ch);
            i += 1;
        }
    }
    out
}

fn alt_spec(lang: &str, f: fn(&str) -> Option<crate::cldr::AltCalSpec>) -> crate::cldr::AltCalSpec {
    let norm: String = lang
        .chars()
        .map(|c| {
            if c == '_' {
                '-'
            } else {
                c.to_ascii_lowercase()
            }
        })
        .collect();
    let mut end = norm.len();
    loop {
        if let Some(s) = f(&norm[..end]) {
            return s;
        }
        match norm[..end].rfind('-') {
            Some(i) => end = i,
            None => return f("en").expect("root calendar present"),
        }
    }
}

/// Format an Islamic (Hijri) date in `lang`, e.g.
/// `format_islamic_date("en", 1445, 9, 1, DateStyle::Long)` →
/// `"Ramadan 1, 1445 AH"` (localized month names + era).
#[must_use]
pub fn format_islamic_date(
    lang: &str,
    year: i64,
    month: i64,
    day: i64,
    style: DateStyle,
) -> String {
    let cal = alt_spec(lang, crate::cldr::islamic_spec);
    let jdn = crate::calendar::islamic_to_jdn(year, month, day);
    render_alt(&cal, style, year, month, day, jdn, &spec(lang))
}

/// Format a Persian (Solar Hijri) date in `lang`, e.g.
/// `format_persian_date("en", 1404, 1, 1, DateStyle::Long)` →
/// `"Farvardin 1, 1404 AP"` (localized month names + era).
#[must_use]
pub fn format_persian_date(
    lang: &str,
    year: i64,
    month: i64,
    day: i64,
    style: DateStyle,
) -> String {
    let cal = alt_spec(lang, crate::cldr::persian_spec);
    let jdn = crate::calendar::persian_to_jdn(year, month, day);
    render_alt(&cal, style, year, month, day, jdn, &spec(lang))
}

/// Format a fixed UTC offset (in minutes) in the localized GMT form, e.g.
/// `"GMT+5:30"`-style output: `format_gmt_offset("en", 330)` → `"GMT+05:30"`,
/// `format_gmt_offset("fr", -480)` → `"UTC−08:00"`, `0` → `"GMT"` / `"UTC"`.
/// This is the data-light part of time-zone support (a concrete offset, not the
/// IANA zone database).
#[must_use]
pub fn format_gmt_offset(lang: &str, offset_minutes: i32) -> String {
    let norm: String = lang
        .chars()
        .map(|c| {
            if c == '_' {
                '-'
            } else {
                c.to_ascii_lowercase()
            }
        })
        .collect();
    let mut end = norm.len();
    let tz = loop {
        if let Some(t) = crate::cldr::tz_spec(&norm[..end]) {
            break t;
        }
        match norm[..end].rfind('-') {
            Some(i) => end = i,
            None => break crate::cldr::tz_spec("en").expect("root tz present"),
        }
    };
    if offset_minutes == 0 {
        return String::from(tz.zero);
    }
    let (pos, neg) = tz.hour.split_once(';').unwrap_or((tz.hour, tz.hour));
    let sub = if offset_minutes >= 0 { pos } else { neg };
    let (h, m) = (
        offset_minutes.unsigned_abs() / 60,
        offset_minutes.unsigned_abs() % 60,
    );
    let body = sub
        .replace("HH", &alloc::format!("{h:02}"))
        .replace("mm", &alloc::format!("{m:02}"));
    tz.gmt.replace("{0}", &body)
}

/// Format both date and time, combined with the locale's date+time pattern.
#[must_use]
pub fn format_datetime(
    lang: &str,
    dt: &DateTime,
    date_style: DateStyle,
    time_style: DateStyle,
) -> String {
    let s = spec(lang);
    let date = render(s.date[date_style.idx()], dt, &s);
    let time = render(s.time[time_style.idx()], dt, &s);
    s.datetime[date_style.idx()]
        .replace("{1}", &date)
        .replace("{0}", &time)
}