1// Locales: a language and region and how they write dates, times,2// numbers and prices, from CLDR 48's data (alloy-ui's decisions/F12.md,3// F12e, questions 11A to 14A), the same on every target: the tables of4// locale_data.alloy, which cldr/generate.alloy writes from the pinned5// release cldr/fetch.sh fetches. Every locale CLDR gives modern coverage6// is there, regional ones as their differences.7//8// Dates are written from components, as `Intl.DateTimeFormat`'s options9// and CLDR's skeletons are, the locale choosing the order, punctuation10// and forms (ICU's pattern generator, followed step by step), or from a11// pattern of CLDR's letters, fixed for every locale.12//13// ```alloy14// import std::time;15//16// const fr = Locale::of(&"fr-FR");17// var line = String::empty();18// const show = DateFormat { .weekday = Width::Short, .month = Width::Short, .time = true, .year = false };19// const moment: i64 = 1795199400000000000; // 2026-11-20T18:30Z20// fr.format_moment(moment, &Zone::utc(), &show, &var line);21// expect_equal(&line, &String::from(&"ven. 20 nov., 18:30"));22// line.clear();23// fr.format_money(2450, &"EUR", &var line);24// expect_equal(&line, &String::from(&"24,50\u{a0}€"));25// expect(fr.first_weekday() == Weekday::Monday && Locale::of(&"en-US").first_weekday() == Weekday::Sunday);26// expect(Locale::of(&"ar-EG").right_to_left() && Locale::of(&"he").right_to_left() && !fr.right_to_left());27// ```2829import std::string;30import std::vector;31import std::option;32import std::format;33import std::time;34import std::text;35import std::process;36import std::ffi;37import std::float_digits;38import std::math;39import std::sort;40import std::locale_data;4142extern al_sys_locale_name(buffer: &var [u8], capacity: u64) -> i64;43extern al_sys_locale_choices() -> i32;44extern al_locale_page(at: c_pointer, capacity: u32) -> u32; // locale.web.js45extern al_locale_page_week() -> u32;4647/* --- The tables --- */4849// Where each kind of field's numbers start (as cldr/generate.alloy's).50type Part = enum : u16 {51 Months = 0, // + context * 36 + width * 12 + month - 152 Days = 72, // + context * 28 + width * 7 + day (Sunday 0)53 DayPeriods = 128, // AM, PM54 DateFormats = 130, // full, long, medium, short55 TimeFormats = 134,56 DateTimeFormats = 138,57 AppendItems = 142, // + the pattern field's number58 Numbering = 160,59 Decimal = 161,60 Group = 162,61 Minus = 163,62 Plus = 164,63 DecimalPattern = 165,64 CurrencyPattern = 166,65 CurrencyAlphaPattern = 167,66 MinimumGrouping = 168,67 CurrencySpace = 169,68 CurrencyDecimal = 170,69 CurrencyGroup = 171,70 HourFormat = 176,71 GmtFormat = 177,72 GmtZeroFormat = 178,73 RegionFormat = 179,74 FieldNames = 192, // + the pattern field's number75 Skeletons = 256, // + the skeleton's number76 Currencies = 1024, // + the currency's number77 CurrencyFormats = 1536, // + currency * 3: its own pattern, decimal and group78 Metazones = 2048, // + metazone * 2 + summer79 Zones = 4096, // + zone * 2 + summer80};8182fn pooled(index: u16) -> &[u8] => &TEXT[83 TEXT_STARTS[index to u64] to u64..TEXT_STARTS[index to u64 + 1] to u6484];8586// The field's text in the table's locale, else in the nearest it87// inherits from.88fn lookup(index: u16, field: u16) -> Option<&[u8]> {89 var at = index;90 while (true) {91 var low = ENTRY_STARTS[at to u64] to u64;92 var high = ENTRY_STARTS[at to u64 + 1] to u64;93 while (low < high) {94 const middle = low + (high - low) / 2;95 const entry = ENTRIES[middle];96 const key = (entry >> 16) to u16;97 if (key == field) {98 // an empty text: the field the parent has, this locale not99 const text = &pooled((entry & 0xFFFF) to u16);100 return if (text.length() == 0) ::None else ::Some(&text);101 }102 if (key < field) {103 low = middle + 1;104 } else {105 high = middle;106 }107 }108 if (PARENTS[at to u64] == 0xFFFF) {109 return ::None;110 }111 at = PARENTS[at to u64];112 }113}114115fn field(self locale: &Locale, part: Part, offset: u64) -> &[u8] {116 if (lookup(locale.index, part to u16 + offset to u16) is ::Some |&text|) {117 return &text;118 }119 return &"";120}121122fn bytes_before(a: &[u8], b: &[u8]) -> bool {123 const shorter = if (a.length() < b.length()) a.length() else b.length();124 for ([..shorter]) |k| {125 if (a[k] != b[k]) {126 return a[k] < b[k];127 }128 }129 return a.length() < b.length();130}131132// Where the text is among sorted texts of the pool.133fn find_sorted(indices: &[u16], step: u64, text: &[u8]) -> Option<u64> {134 var low: u64 = 0;135 var high = indices.length() / step;136 while (low < high) {137 const middle = low + (high - low) / 2;138 const here = &pooled(indices[middle * step]);139 if (here == text) {140 return ::Some(middle);141 }142 if (bytes_before(&here, &text)) {143 low = middle + 1;144 } else {145 high = middle;146 }147 }148 return ::None;149}150151// The value of a region's entry (region << 8 | value).152fn region_value(entries: &[u32], region: u32) -> Option<u8> {153 var low: u64 = 0;154 var high = entries.length();155 while (low < high) {156 const middle = low + (high - low) / 2;157 const here = entries[middle] >> 8;158 if (here == region) {159 return ::Some((entries[middle] & 0xFF) to u8);160 }161 if (here < region) {162 low = middle + 1;163 } else {164 high = middle;165 }166 }167 return ::None;168}169170fn unpacked(code: u32) -> String {171 var out = String::empty();172 for ([..3]) |k| {173 const c = ((code >> ((2 - k) * 8) to u32) & 0xFF) to u8;174 if (c != 0) {175 out.push(c);176 }177 }178 return move out;179}180181// Up to three letters or digits as one number: `FR`, `001`, `EUR`.182fn packed(code: &[u8]) -> u32 {183 var n: u32 = 0;184 for (code) |c| {185 n = n << 8 | c to u32;186 }187 return n;188}189190/* --- Locales --- */191192// A locale of the tables, with the region its week and clock follow and193// the user's choices of them.194exp type Locale = struct {195 index: u16, // the tables' locale196 region: u32, // packed197 first: Weekday,198 hour: u8, // the hour's letter: `h`, `H`, `K` or `k`199};200201// A BCP 47 tag read: language, script and region, variants, and the202// Unicode extension's hour cycle (`-u-hc-h12`) and first day (`-u-fw-sun`).203type Tag = struct {204 language: String,205 script: String,206 region: String,207 variants: String, // each after its dash208 hour: u8 = 0,209 first: Option<Weekday> = ::None,210};211212const FIRST_DAYS_NAMED: [&[u8] : 7] = [&"mon", &"tue", &"wed", &"thu", &"fri", &"sat", &"sun"];213214fn read_tag(text: &[u8]) -> Tag {215 var tag = Tag {216 .language = String::empty(),217 .script = String::empty(),218 .region = String::empty(),219 .variants = String::empty()220 };221 var parts = Vector<&[u8]>::empty();222 var from: u64 = 0;223 for ([..text.length() + 1]) |k| {224 if (k == text.length() || text[k] == '-' || text[k] == '_') {225 parts.push(&text[from..k]);226 from = k + 1;227 }228 }229 var k: u64 = 0;230 if (231 parts.length() > 0232 && parts.get(0).length() >= 2233 && parts.get(0).length() <= 8234 && all_letters(&parts.get(0))235 ) {236 tag.language = lowercase(&parts.get(0));237 k = 1;238 }239 if (k < parts.length() && parts.get(k).length() == 4 && all_letters(&parts.get(k))) {240 const script = lowercase(&parts.get(k));241 tag.script.push(uppercase_byte(script.get(0)));242 tag.script.append(&script.view()[1..]);243 k += 1;244 }245 if (246 k < parts.length()247 && (248 (parts.get(k).length() == 2 && all_letters(&parts.get(k)))249 || (parts.get(k).length() == 3 && all_digits(&parts.get(k)))250 )251 ) {252 tag.region = uppercase(&parts.get(k));253 k += 1;254 }255 while (k < parts.length() && parts.get(k).length() > 1) {256 tag.variants.push('-');257 tag.variants.append(&lowercase(&parts.get(k)).view());258 k += 1;259 }260 // the Unicode extension's keys261 while (k < parts.length()) {262 if (parts.get(k) == "u" || parts.get(k) == "U") {263 k += 1;264 while (k + 1 < parts.length() && parts.get(k).length() == 2) {265 const key = lowercase(&parts.get(k));266 const value = lowercase(&parts.get(k + 1));267 if (key.view() == "hc") {268 tag.hour = match (value.view()) {269 "h11" 'K';270 "h12" 'h';271 "h23" 'H';272 "h24" 'k';273 else tag.hour;274 };275 } else if (key.view() == "fw") {276 for (FIRST_DAYS_NAMED, [..7]) |&name, d| {277 if (value.view() == name) {278 tag.first = Weekday::from(d to u8 + 1);279 }280 }281 }282 k += 2;283 }284 } else {285 k += 1;286 }287 }288 // old codes289 const renamed: &[u8] = match (tag.language.view()) {290 "iw" &"he";291 "in" &"id";292 "ji" &"yi";293 "tl" &"fil";294 "mo" &"ro";295 "sh" &"sr";296 else &"";297 };298 if (renamed.length() > 0) {299 if (tag.language.view() == "sh" && tag.script.length() == 0) {300 tag.script = String::from(&"Latn");301 }302 tag.language = String::from(&renamed);303 }304 return move tag;305}306307// The tables' locale for the tag: itself, else with its likely script,308// else with its last subtags cut off.309fn find_locale(tag: &Tag) -> Option<u16> {310 if (tag.language.length() == 0) {311 return ::None;312 }313 var full = copy tag.language;314 if (tag.script.length() > 0) {315 full.append(&f"-{tag.script}".view());316 }317 if (tag.region.length() > 0) {318 full.append(&f"-{tag.region}".view());319 }320 full.append(&tag.variants.view());321 if (tag.script.length() == 0 && tag.region.length() > 0) {322 const pair = f"{tag.language}-{tag.region}";323 if (find_sorted(&SCRIPTS, 2, &pair.view()) is ::Some |k|) {324 const scripted = f"{pooled(SCRIPTS[k * 2 + 1])}{tag.variants}";325 if (cut_to_locale(&scripted.view()) is ::Some |index|) {326 return ::Some(index);327 }328 }329 }330 return cut_to_locale(&full.view());331}332333fn cut_to_locale(text: &[u8]) -> Option<u16> {334 var cut = &text;335 while (true) {336 if (find_sorted(&LOCALES, 1, &cut) is ::Some |index|) {337 return ::Some(index to u16);338 }339 var last: u64 = 0;340 for (cut, [..cut.length()]) |c, k| {341 if (c == '-') {342 last = k;343 }344 }345 if (last == 0) {346 return ::None;347 }348 cut = &cut[..last];349 }350}351352// The locale the tables hold nearest the BCP 47 tag ("fr-CA", "zh-TW",353// "sr-Latn-ME"), "en" at worst; its week and clock follow the tag's354// region, else the language's likely one, and the extension's `hc` and355// `fw` keys (`en-GB-u-hc-h12`).356exp fn Locale::of(tag: &[u8]) -> Locale {357 const read = read_tag(&tag);358 var index: u16 = 0;359 if (find_locale(&read) is ::Some |found|) {360 index = found;361 } else if (cut_to_locale(&"en") is ::Some |english|) {362 index = english;363 }364 const region = if (read.region.length() > 0) packed(&read.region.view()) else packed(365 &pooled(REGIONS[index to u64])366 );367 var first = Weekday::Monday;368 if (read.first is ::Some |day|) {369 first = day;370 } else if (371 region_value(&FIRST_DAYS, region) is ::Some |day|372 && Weekday::from(day) is ::Some |w|373 ) {374 first = w;375 }376 var locale = Locale { .index = index, .region = region, .first = first, .hour = read.hour };377 if (locale.hour != 0) {378 return locale;379 }380 // the language's in the region, else the region's, else the locale's381 // short time format's (ICU's getAllowedHourFormats)382 const language = if (read.language.length() > 0) copy read.language else String::from(&"en");383 const pair = f"{language}-{unpacked(region)}";384 if (find_sorted(&TAG_HOURS, 2, &pair.view()) is ::Some |k|) {385 locale.hour = TAG_HOURS[k * 2 + 1] to u8;386 } else if (region_value(&HOURS, region) is ::Some |h|) {387 locale.hour = h;388 } else {389 locale.hour = 'H';390 for (locale.field(Part::TimeFormats, 3)) |c| {391 if (c == 'h' || c == 'H' || c == 'K' || c == 'k') {392 locale.hour = c;393 break;394 }395 }396 }397 return locale;398}399400// The user's locale, with their choices of the week's first day and a401// 12- or 24-hour clock: `LC_ALL`, `LC_TIME` or `LANG` on Linux and under402// WASI (`fr_FR.UTF-8` is fr-FR, `C` and `POSIX` are en), the user's403// locale, first day and time format on Windows, CFLocale's and404// `AppleICUForce24HourTime` on macOS, the page's first language and405// Intl.Locale's week on the web.406exp fn Locale::system() -> Locale {407 var buffer: [u8 : 256] = [0 : 256];408 var name = String::empty();409 var choices: u32 = 0;410 if (target() == "web-wasm32") {411 const length = al_locale_page(c_pointer::of(&buffer[..]), 256) to u64;412 if (length <= 256) {413 name = String::from(&buffer[..length]);414 }415 choices = al_locale_page_week();416 } else {417 const length = al_sys_locale_name(&var buffer, 256);418 if (length >= 0 && length as u64 <= 256) {419 name = String::from(&buffer[..length as u64]);420 }421 choices = al_sys_locale_choices() as u32;422 }423 var tag = &name.view();424 for (tag, [..tag.length()]) |c, k| {425 if (c == '.' || c == '@') {426 tag = &tag[..k];427 break;428 }429 }430 var locale = if (431 tag.length() == 0432 || tag == "C"433 || tag == "POSIX"434 ) Locale::of(&"en") else Locale::of(&tag);435 if (Weekday::from((choices & 15) to u8) is ::Some |day|) {436 locale.first = day;437 }438 if ((choices & 16) != 0 && !locale.twelve_hour()) {439 locale.hour = 'h';440 } else if ((choices & 32) != 0 && locale.twelve_hour()) {441 locale.hour = 'H';442 }443 return locale;444}445446// The tables' tag for the locale: "fr-CA", "en" for one they lack.447exp fn tag(self locale: &Locale) -> &[u8] => &pooled(LOCALES[locale.index to u64]);448449// The week's first day: Monday in France, Sunday in the United States.450exp fn first_weekday(self locale: &Locale) -> Weekday => locale.first;451452// Whether the clock has 12 hours and AM and PM.453exp fn twelve_hour(self locale: &Locale) -> bool => locale.hour == 'h' || locale.hour == 'K';454455// Whether the locale's language is written right to left (CLDR's456// character order): Arabic, Hebrew, Persian, Urdu, ...457exp fn right_to_left(self locale: &Locale) -> bool {458 for (RIGHT_TO_LEFT) |index| {459 if (index == locale.index) {460 return true;461 }462 }463 return false;464}465466/* --- Names --- */467468// How wide a name or field is written: `Friday`, `Fri`, `F`; a month by469// its number (Numeric).470exp type Width = enum {471 None,472 Wide,473 Short,474 Narrow,475 Numeric,476};477478// The month's name as written alone, in a calendar's title or a menu:479// Wide, Short or Narrow, another width giving the wide name.480exp fn month_name(self locale: &Locale, month: Month, width: Width) -> &[u8] {481 const w: u64 = match (width) {482 ::Short 1;483 ::Narrow 2;484 else 0;485 };486 return &locale.field(Part::Months, 36 + w * 12 + month to u8 to u64 - 1);487}488489// The weekday's name as written alone: Wide, Short or Narrow, another490// width giving the wide name.491exp fn weekday_name(self locale: &Locale, day: Weekday, width: Width) -> &[u8] {492 const w: u64 = match (width) {493 ::Short 1;494 ::Narrow 3;495 else 0;496 };497 return &locale.field(Part::Days, 28 + w * 7 + (day to u8 % 7) to u64);498}499500/* --- Formats --- */501502// How a zone is named after a time: `CET` or `EST` where the locale has503// such a name (else as Offset), `GMT+1` (Offset), `Paris time` (City:504// the locale's region format around the zone's city, as its name writes505// it).506exp type ZoneName = enum {507 None,508 Short,509 Offset,510 City,511};512513// What a date shows, the locale choosing the order, punctuation and514// forms: `Friday 20 November 2026`, `Fri, Nov 20, 1:30 PM`.515exp type DateFormat = struct {516 exp weekday: Width = Width::None, // Wide "Friday", Short "Fri", Narrow "F"517 exp day: bool = true,518 exp month: Width = Width::Wide, // or Numeric "11", or None519 exp year: bool = true,520 exp time: bool = false,521 exp seconds: bool = false,522 exp zone: ZoneName = ZoneName::None, // Short "CET", Offset "GMT+1", City "Paris time"523};524525// Writes the day as the format shows a date (its time and zone left out).526exp fn format_date(self locale: &Locale, date: &Date, format: &DateFormat, out: &var String) {527 var dated = copy format;528 dated.time = false;529 dated.seconds = false;530 dated.zone = ZoneName::None;531 const pattern = locale.best_pattern(&skeleton_text(&dated).view());532 const shown = Shown {533 .local = DateTime { .date = copy date, .time = TimeOfDay { .hour = 0, .minute = 0 } },534 .offset = 0,535 .summer = false,536 .moment = 0537 };538 locale.write_pattern(&pattern.view(), &shown, &Zone::utc(), &var out);539}540541// Writes the moment (nanoseconds since 1970 UTC) as the zone's clocks542// show it, in the format.543exp fn format_moment(544 self locale: &Locale,545 moment: i64,546 zone: &Zone,547 format: &DateFormat,548 out: &var String549) {550 const pattern = locale.best_pattern(&skeleton_text(&format).view());551 locale.write_pattern(&pattern.view(), &shown_at(&zone, moment), &zone, &var out);552}553554// Writes the moment on the zone's clocks in a pattern of CLDR's letters555// (`EEEE d MMMM, HH:mm`), the same order in every locale, names and556// digits the locale's: G, y, M, L, d, E, c, a, h, H, K, k, m, s, S, z,557// O, Z, X, x, v and V (VVV the zone's city), `'quoted'` text and `''`.558exp fn format_pattern(559 self locale: &Locale,560 moment: i64,561 zone: &Zone,562 pattern: &[u8],563 out: &var String564) {565 locale.write_pattern(&pattern, &shown_at(&zone, moment), &zone, &var out);566}567568// What a pattern's fields show of a moment.569type Shown = struct {570 local: DateTime,571 offset: i64,572 summer: bool,573 moment: i64,574};575576fn shown_at(zone: &Zone, moment: i64) -> Shown => Shown {577 .local = zone.local(moment),578 .offset = zone.offset_at(moment),579 .summer = zone.summer_at(moment),580 .moment = moment581};582583// The skeleton of the components, as Intl.DateTimeFormat asks ICU for584// its options: `EEEdMMMjmm`.585fn skeleton_text(format: &DateFormat) -> String {586 var out = String::empty();587 out.append(&match (format.weekday) {588 ::Wide "EEEE";589 ::Short, ::Numeric "EEE";590 ::Narrow "EEEEE";591 ::None "";592 });593 if (format.year) {594 out.push('y');595 }596 out.append(&match (format.month) {597 ::Wide "MMMM";598 ::Short "MMM";599 ::Narrow "MMMMM";600 ::Numeric "M";601 ::None "";602 });603 if (format.day) {604 out.push('d');605 }606 if (format.time || format.seconds) {607 out.append(&"jmm");608 if (format.seconds) {609 out.append(&"ss");610 }611 }612 out.append(&match (format.zone) {613 ::Short "z";614 ::Offset "O";615 ::City "VVVV";616 ::None "";617 });618 return move out;619}620621/* --- ICU's pattern generator (DateTimePatternGenerator, dtptngen.cpp) --- */622623// A pattern's fields, as ICU numbers them.624type Field = enum : u8 {625 Era = 0,626 Year = 1,627 Quarter = 2,628 Month = 3,629 WeekOfYear = 4,630 WeekOfMonth = 5,631 Weekday = 6,632 DayOfYear = 7,633 DayOfWeekInMonth = 8,634 Day = 9,635 DayPeriod = 10,636 Hour = 11,637 Minute = 12,638 Second = 13,639 Fraction = 14,640 Zone = 15,641};642643// ICU's kinds of fields: numeric ones above, text below, each letter's644// apart by DELTA.645const NUMERIC: i32 = 0x100;646const DELTA: i32 = 0x10;647const NARROW: i32 = -0x101;648const SHORTER: i32 = -0x102;649const SHORT: i32 = -0x103;650const LONG: i32 = -0x104;651const FIELD_COUNT: u64 = 16;652const STYLE_COUNT: u64 = 4;653const EXTRA_FIELD: i32 = 0x10000;654const MISSING_FIELD: i32 = 0x1000;655const DATE_MASK: u32 = 0x3FF; // era to day656const TIME_MASK: u32 = 0xFC00; // day period to zone657658// A letter of a given length and up: its field and kind (dtTypes).659type Row = struct {660 letter: u8,661 field: Field,662 kind: i32,663 least: u8,664};665666const ROWS: [Row : 84] = [667 Row { .letter = 'G', .field = Field::Era, .kind = SHORT, .least = 1 },668 Row { .letter = 'G', .field = Field::Era, .kind = LONG, .least = 4 },669 Row { .letter = 'G', .field = Field::Era, .kind = NARROW, .least = 5 },670 Row { .letter = 'y', .field = Field::Year, .kind = NUMERIC, .least = 1 },671 Row { .letter = 'Y', .field = Field::Year, .kind = NUMERIC + DELTA, .least = 1 },672 Row { .letter = 'u', .field = Field::Year, .kind = NUMERIC + 2 * DELTA, .least = 1 },673 Row { .letter = 'r', .field = Field::Year, .kind = NUMERIC + 3 * DELTA, .least = 1 },674 Row { .letter = 'U', .field = Field::Year, .kind = SHORT, .least = 1 },675 Row { .letter = 'U', .field = Field::Year, .kind = LONG, .least = 4 },676 Row { .letter = 'U', .field = Field::Year, .kind = NARROW, .least = 5 },677 Row { .letter = 'Q', .field = Field::Quarter, .kind = NUMERIC, .least = 1 },678 Row { .letter = 'Q', .field = Field::Quarter, .kind = SHORT, .least = 3 },679 Row { .letter = 'Q', .field = Field::Quarter, .kind = LONG, .least = 4 },680 Row { .letter = 'Q', .field = Field::Quarter, .kind = NARROW, .least = 5 },681 Row { .letter = 'q', .field = Field::Quarter, .kind = NUMERIC + DELTA, .least = 1 },682 Row { .letter = 'q', .field = Field::Quarter, .kind = SHORT - DELTA, .least = 3 },683 Row { .letter = 'q', .field = Field::Quarter, .kind = LONG - DELTA, .least = 4 },684 Row { .letter = 'q', .field = Field::Quarter, .kind = NARROW - DELTA, .least = 5 },685 Row { .letter = 'M', .field = Field::Month, .kind = NUMERIC, .least = 1 },686 Row { .letter = 'M', .field = Field::Month, .kind = SHORT, .least = 3 },687 Row { .letter = 'M', .field = Field::Month, .kind = LONG, .least = 4 },688 Row { .letter = 'M', .field = Field::Month, .kind = NARROW, .least = 5 },689 Row { .letter = 'L', .field = Field::Month, .kind = NUMERIC + DELTA, .least = 1 },690 Row { .letter = 'L', .field = Field::Month, .kind = SHORT - DELTA, .least = 3 },691 Row { .letter = 'L', .field = Field::Month, .kind = LONG - DELTA, .least = 4 },692 Row { .letter = 'L', .field = Field::Month, .kind = NARROW - DELTA, .least = 5 },693 Row { .letter = 'l', .field = Field::Month, .kind = NUMERIC + DELTA, .least = 1 },694 Row { .letter = 'w', .field = Field::WeekOfYear, .kind = NUMERIC, .least = 1 },695 Row { .letter = 'W', .field = Field::WeekOfMonth, .kind = NUMERIC, .least = 1 },696 Row { .letter = 'E', .field = Field::Weekday, .kind = SHORT, .least = 1 },697 Row { .letter = 'E', .field = Field::Weekday, .kind = LONG, .least = 4 },698 Row { .letter = 'E', .field = Field::Weekday, .kind = NARROW, .least = 5 },699 Row { .letter = 'E', .field = Field::Weekday, .kind = SHORTER, .least = 6 },700 Row { .letter = 'c', .field = Field::Weekday, .kind = NUMERIC + 2 * DELTA, .least = 1 },701 Row { .letter = 'c', .field = Field::Weekday, .kind = SHORT - 2 * DELTA, .least = 3 },702 Row { .letter = 'c', .field = Field::Weekday, .kind = LONG - 2 * DELTA, .least = 4 },703 Row { .letter = 'c', .field = Field::Weekday, .kind = NARROW - 2 * DELTA, .least = 5 },704 Row { .letter = 'c', .field = Field::Weekday, .kind = SHORTER - 2 * DELTA, .least = 6 },705 Row { .letter = 'e', .field = Field::Weekday, .kind = NUMERIC + DELTA, .least = 1 },706 Row { .letter = 'e', .field = Field::Weekday, .kind = SHORT - DELTA, .least = 3 },707 Row { .letter = 'e', .field = Field::Weekday, .kind = LONG - DELTA, .least = 4 },708 Row { .letter = 'e', .field = Field::Weekday, .kind = NARROW - DELTA, .least = 5 },709 Row { .letter = 'e', .field = Field::Weekday, .kind = SHORTER - DELTA, .least = 6 },710 Row { .letter = 'd', .field = Field::Day, .kind = NUMERIC, .least = 1 },711 Row { .letter = 'g', .field = Field::Day, .kind = NUMERIC + DELTA, .least = 1 },712 Row { .letter = 'D', .field = Field::DayOfYear, .kind = NUMERIC, .least = 1 },713 Row { .letter = 'F', .field = Field::DayOfWeekInMonth, .kind = NUMERIC, .least = 1 },714 Row { .letter = 'a', .field = Field::DayPeriod, .kind = SHORT, .least = 1 },715 Row { .letter = 'a', .field = Field::DayPeriod, .kind = LONG, .least = 4 },716 Row { .letter = 'a', .field = Field::DayPeriod, .kind = NARROW, .least = 5 },717 Row { .letter = 'b', .field = Field::DayPeriod, .kind = SHORT - DELTA, .least = 1 },718 Row { .letter = 'b', .field = Field::DayPeriod, .kind = LONG - DELTA, .least = 4 },719 Row { .letter = 'b', .field = Field::DayPeriod, .kind = NARROW - DELTA, .least = 5 },720 Row { .letter = 'B', .field = Field::DayPeriod, .kind = SHORT - 3 * DELTA, .least = 1 },721 Row { .letter = 'B', .field = Field::DayPeriod, .kind = LONG - 3 * DELTA, .least = 4 },722 Row { .letter = 'B', .field = Field::DayPeriod, .kind = NARROW - 3 * DELTA, .least = 5 },723 Row { .letter = 'H', .field = Field::Hour, .kind = NUMERIC + 10 * DELTA, .least = 1 },724 Row { .letter = 'k', .field = Field::Hour, .kind = NUMERIC + 11 * DELTA, .least = 1 },725 Row { .letter = 'h', .field = Field::Hour, .kind = NUMERIC, .least = 1 },726 Row { .letter = 'K', .field = Field::Hour, .kind = NUMERIC + DELTA, .least = 1 },727 Row { .letter = 'm', .field = Field::Minute, .kind = NUMERIC, .least = 1 },728 Row { .letter = 's', .field = Field::Second, .kind = NUMERIC, .least = 1 },729 Row { .letter = 'A', .field = Field::Second, .kind = NUMERIC + DELTA, .least = 1 },730 Row { .letter = 'S', .field = Field::Fraction, .kind = NUMERIC, .least = 1 },731 Row { .letter = 'v', .field = Field::Zone, .kind = SHORT - 2 * DELTA, .least = 1 },732 Row { .letter = 'v', .field = Field::Zone, .kind = LONG - 2 * DELTA, .least = 4 },733 Row { .letter = 'z', .field = Field::Zone, .kind = SHORT, .least = 1 },734 Row { .letter = 'z', .field = Field::Zone, .kind = LONG, .least = 4 },735 Row { .letter = 'Z', .field = Field::Zone, .kind = NARROW - DELTA, .least = 1 },736 Row { .letter = 'Z', .field = Field::Zone, .kind = LONG - DELTA, .least = 4 },737 Row { .letter = 'Z', .field = Field::Zone, .kind = SHORT - DELTA, .least = 5 },738 Row { .letter = 'O', .field = Field::Zone, .kind = SHORT - DELTA, .least = 1 },739 Row { .letter = 'O', .field = Field::Zone, .kind = LONG - DELTA, .least = 4 },740 Row { .letter = 'V', .field = Field::Zone, .kind = SHORT - DELTA, .least = 1 },741 Row { .letter = 'V', .field = Field::Zone, .kind = LONG - DELTA, .least = 2 },742 Row { .letter = 'V', .field = Field::Zone, .kind = LONG - 1 - DELTA, .least = 3 },743 Row { .letter = 'V', .field = Field::Zone, .kind = LONG - 2 - DELTA, .least = 4 },744 Row { .letter = 'X', .field = Field::Zone, .kind = NARROW - DELTA, .least = 1 },745 Row { .letter = 'X', .field = Field::Zone, .kind = SHORT - DELTA, .least = 2 },746 Row { .letter = 'X', .field = Field::Zone, .kind = LONG - DELTA, .least = 4 },747 Row { .letter = 'x', .field = Field::Zone, .kind = NARROW - DELTA, .least = 1 },748 Row { .letter = 'x', .field = Field::Zone, .kind = SHORT - DELTA, .least = 2 },749 Row { .letter = 'x', .field = Field::Zone, .kind = LONG - DELTA, .least = 4 },750 Row { .letter = 0, .field = Field::Zone, .kind = 0, .least = 0 },751];752753// The row of a run of one letter (FormatParser::getCanonicalIndex), None754// for a letter that is no field.755fn row_of(letter: u8, length: u64) -> Option<u64> {756 if (letter >= 128 || ROW_STARTS[letter to u64] == 0xFF) {757 return ::None;758 }759 var found = Option<u64>::None;760 var k = ROW_STARTS[letter to u64] to u64;761 while (k < ROWS.length() && ROWS[k].letter != 0) {762 if (ROWS[k].letter != letter) {763 k += 1;764 continue;765 }766 found = ::Some(k);767 if (ROWS[k + 1].letter != letter || ROWS[k + 1].least to u64 > length) {768 return ::Some(k);769 }770 k += 1;771 }772 return found;773}774775// Where each letter's rows start in ROWS, 0xFF for none.776const ROW_STARTS: [u8 : 128] = row_starts();777778fn row_starts() -> [u8 : 128] {779 var starts = [0xFF to u8 : 128];780 for (ROWS, [..ROWS.length()]) |&row, k| {781 if (row.letter != 0 && starts[row.letter to u64] == 0xFF) {782 starts[row.letter to u64] = k to u8;783 }784 }785 return starts;786}787788// A skeleton: per field the letters asked for (`original`), the row's789// letter and least length (`baseOriginal`), and the kind (`type`).790type Skeleton = struct {791 letters: [u8 : 16] = [0 : 16],792 lengths: [u8 : 16] = [0 : 16],793 base_letters: [u8 : 16] = [0 : 16],794 base_lengths: [u8 : 16] = [0 : 16],795 kinds: [i32 : 16] = [0 : 16],796};797798fn is_letter(c: u8) -> bool => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');799800// Where the pattern's item at `at` ends: a run of one letter, a quoted801// text with its quotes, or one byte.802fn item_end(pattern: &[u8], at: u64) -> u64 {803 const c = pattern[at];804 if (is_letter(c)) {805 var end = at + 1;806 while (end < pattern.length() && pattern[end] == c) {807 end += 1;808 }809 return end;810 }811 if (c == '\'') {812 if (at + 1 < pattern.length() && pattern[at + 1] == '\'') {813 return at + 2;814 }815 var end = at + 1;816 while (end < pattern.length()) {817 if (pattern[end] == '\'') {818 if (end + 1 < pattern.length() && pattern[end + 1] == '\'') {819 end += 2;820 continue;821 }822 return end + 1;823 }824 end += 1;825 }826 return end;827 }828 return at + 1;829}830831// DateTimeMatcher::set.832fn skeleton_of(pattern: &[u8]) -> Skeleton {833 var s = Skeleton {};834 var at: u64 = 0;835 while (at < pattern.length()) {836 const end = item_end(&pattern, at);837 if (is_letter(pattern[at]) && row_of(pattern[at], end - at) is ::Some |r|) {838 const row = &ROWS[r];839 const f = row.field to u8 to u64;840 const length = end - at;841 s.letters[f] = pattern[at];842 s.lengths[f] = length to u8;843 s.base_letters[f] = row.letter;844 s.base_lengths[f] = row.least;845 s.kinds[f] = row.kind + if (row.kind > 0) length to i32 else 0;846 }847 at = end;848 }849 // a 12-hour clock takes a day period, a 24-hour one none850 const hour = Field::Hour to u8 to u64;851 const period = Field::DayPeriod to u8 to u64;852 if (s.letters[hour] != 0) {853 if (s.letters[hour] == 'h' || s.letters[hour] == 'K') {854 if (s.letters[period] == 0) {855 s.letters[period] = 'a';856 s.lengths[period] = 1;857 s.base_letters[period] = 'a';858 s.base_lengths[period] = 1;859 s.kinds[period] = SHORT;860 }861 } else if (s.letters[period] != 0) {862 s.letters[period] = 0;863 s.lengths[period] = 0;864 s.base_letters[period] = 0;865 s.base_lengths[period] = 0;866 s.kinds[period] = 0;867 }868 }869 return s;870}871872// Whether the skeletons have one base (`baseOriginal`).873// (compared eight bytes at a time)874fn same_base(a: &Skeleton, b: &Skeleton) -> bool => same16(&a.base_letters, &b.base_letters)875 && same16(&a.base_lengths, &b.base_lengths);876877fn same_original(a: &Skeleton, b: &Skeleton) -> bool => same16(&a.letters, &b.letters)878 && same16(&a.lengths, &b.lengths);879880fn same16(a: &[u8 : 16], b: &[u8 : 16]) -> bool {881 const x = a as &[u64 : 2];882 const y = b as &[u64 : 2];883 return x[0] == y[0] && x[1] == y[1];884}885886fn bit(field: u64) -> u32 {887 const one: u32 = 1;888 return one << field to u32;889}890891fn mask(self s: &Skeleton) -> u32 {892 var m: u32 = 0;893 for ([..FIELD_COUNT]) |f| {894 if (s.kinds[f] != 0) {895 m |= bit(f);896 }897 }898 return m;899}900901// The distance from the request to a skeleton over the fields the mask902// keeps, with the fields missing and extra.903type Distance = struct {904 distance: i32,905 missing: u32,906 extra: u32,907};908909fn distance(request: &Skeleton, trial: &Skeleton, include: u32) -> Distance {910 var d = Distance { .distance = 0, .missing = 0, .extra = 0 };911 for ([..FIELD_COUNT]) |f| {912 const mine = if ((include & bit(f)) == 0) 0 else request.kinds[f];913 const theirs = trial.kinds[f];914 if (mine == theirs) {915 continue;916 }917 if (mine == 0) {918 d.distance += EXTRA_FIELD;919 d.extra |= bit(f);920 } else if (theirs == 0) {921 d.distance += MISSING_FIELD;922 d.missing |= bit(f);923 } else {924 d.distance += if (mine > theirs) mine - theirs else theirs - mine;925 }926 }927 return d;928}929930// A pattern the generator may pick, by its skeleton.931type Candidate = struct {932 box: u64, // box_of its skeleton933 skeleton: Skeleton,934 pattern: &[u8],935 specified: bool, // the skeleton given with the pattern936 order: u64,937};938939const CANONICAL: [&[u8] : 16] = [940 &"G",941 &"y",942 &"Q",943 &"M",944 &"w",945 &"W",946 &"E",947 &"D",948 &"F",949 &"d",950 &"a",951 &"H",952 &"m",953 &"s",954 &"S",955 &"v"956];957958// addPatternWithSkeleton, with PatternMap::add.959fn add_candidate(960 list: &var Vector<Candidate>,961 pattern: &[u8],962 given: Option<&[u8]>,963 override: bool964) {965 const skeleton = if (given is ::Some |&g|) skeleton_of(&g) else skeleton_of(&pattern);966 const specified = given is ::Some;967 for (list.view()) |&c| {968 if (same_base(&c.skeleton, &skeleton)) {969 if ((!c.specified || (specified && !override)) && !override) {970 return;971 }972 break;973 }974 }975 for (list.items()) |&var c| {976 if (same_original(&c.skeleton, &skeleton)) {977 if (!override || (specified && c.specified)) {978 return;979 }980 if (same_base(&c.skeleton, &skeleton)) {981 c.pattern = &pattern;982 c.specified = specified;983 return;984 }985 }986 }987 const order = list.length();988 list.push(Candidate {989 .box = box_of(&skeleton),990 .skeleton = skeleton,991 .pattern = &pattern,992 .specified = specified,993 .order = order994 });995}996997// The box a skeleton's base sorts in: its first letter, capitals first.998fn box_of(s: &Skeleton) -> u64 {999 for ([..FIELD_COUNT]) |f| {1000 if (s.base_lengths[f] > 0) {1001 const first = s.base_letters[f];1002 return if (first <= 'Z') (first - 'A') to u64 else 26 + (first - 'a') to u64;1003 }1004 }1005 return 52;1006}10071008// The patterns ICU's generator holds for the locale, in the order it1009// tries them: canonical items, the date and time formats, the flexible1010// formats.1011fn candidates(self locale: &Locale) -> Vector<Candidate> {1012 var list = Vector<Candidate>::empty();1013 for (CANONICAL) |&item| {1014 add_candidate(&var list, &item, ::None, false);1015 }1016 for ([..STYLE_COUNT]) |style| {1017 add_candidate(&var list, &locale.field(Part::DateFormats, style), ::None, false);1018 add_candidate(&var list, &locale.field(Part::TimeFormats, style), ::None, false);1019 }1020 // the flexible formats the locale sets, then those it inherits, each1021 // level's in its skeletons' order, as ICU loads its tables1022 var seen = Vector<bool>::filled(false, SKELETONS.length());1023 const first = Part::Skeletons to u32;1024 var at = locale.index;1025 while (true) {1026 for (ENTRIES[ENTRY_STARTS[at to u64] to u64..ENTRY_STARTS[at to u64 + 1] to u64]) |entry| {1027 const field = entry >> 16;1028 if (field < first || field >= first + SKELETONS.length() to u32) {1029 continue;1030 }1031 const k = (field - first) to u64;1032 if (seen.get(k)) {1033 continue;1034 }1035 seen.set(k, true);1036 const pattern = &pooled((entry & 0xFFFF) to u16);1037 if (pattern.length() > 0) {1038 add_candidate(&var list, &pattern, ::Some(&pooled(SKELETONS[k])), true);1039 }1040 }1041 if (PARENTS[at to u64] == 0xFFFF) {1042 break;1043 }1044 at = PARENTS[at to u64];1045 }1046 sort_by(1047 &var list.items(),1048 (a, b) => a.box < b.box || (a.box == b.box && a.order < b.order)1049 );1050 return move list;1051}10521053type Best = struct {1054 pattern: &[u8],1055 specified: Option<Skeleton>,1056 distance: Distance,1057};10581059// getBestRaw.1060fn best_raw(list: &Vector<Candidate>, request: &Skeleton, include: u32) -> Best {1061 var best = Best {1062 .pattern = &"",1063 .specified = ::None,1064 .distance = Distance { .distance = 0x7FFFFFFF, .missing = 0, .extra = 0 }1065 };1066 var best_missing: i64 = -1;1067 for (list.view()) |&c| {1068 const d = distance(&request, &c.skeleton, include);1069 if (1070 d.distance < best.distance.distance1071 || (d.distance == best.distance.distance && best_missing < d.missing to i64)1072 ) {1073 best_missing = d.missing to i64;1074 best.pattern = &c.pattern;1075 best.specified = if (c.specified) ::Some(c.skeleton) else ::None;1076 best.distance = d;1077 if (d.distance == 0) {1078 break;1079 }1080 }1081 }1082 return best;1083}10841085// adjustFieldTypes, matching the hour's length as Intl asks1086// (UDATPG_MATCH_HOUR_FIELD_LENGTH).1087fn adjust(1088 self locale: &Locale,1089 pattern: &[u8],1090 specified: &Option<Skeleton>,1091 request: &Skeleton1092) -> String {1093 var out = String::empty();1094 var at: u64 = 0;1095 while (at < pattern.length()) {1096 const end = item_end(&pattern, at);1097 const item = &pattern[at..end];1098 at = end;1099 if (!is_letter(item[0])) {1100 out.append(&item);1101 continue;1102 }1103 const r = if (row_of(item[0], item.length()) is ::Some |r|) r else {1104 out.append(&item);1105 continue;1106 };1107 const row = &ROWS[r];1108 const f = row.field;1109 const index = f to u8 to u64;1110 if (request.kinds[index] == 0) {1111 out.append(&item);1112 continue;1113 }1114 const wanted = request.letters[index];1115 var wanted_length = request.lengths[index] to u64;1116 if (wanted == 'E' && wanted_length < 3) {1117 wanted_length = 3;1118 }1119 var length = wanted_length;1120 if (f == Field::Minute || f == Field::Second) {1121 length = item.length();1122 } else if (specified is ::Some |&s| && wanted != 'c' && wanted != 'e') {1123 const pattern_numeric = row.kind > 0;1124 const skeleton_numeric = s.kinds[index] > 0;1125 if (s.lengths[index] to u64 == wanted_length || pattern_numeric != skeleton_numeric) {1126 length = item.length();1127 }1128 }1129 const keeps = f == Field::Hour1130 || f == Field::Month1131 || f == Field::Weekday1132 || (f == Field::Year && wanted != 'Y');1133 var c = if (keeps) item[0] else wanted;1134 if (c == 'E' && length < 3) {1135 c = 'e';1136 }1137 if (f == Field::Hour) {1138 const preferred = locale.hour;1139 if (wanted == preferred) {1140 c = preferred;1141 } else if (wanted == 'h' && preferred == 'K') {1142 c = 'K';1143 } else if (wanted == 'H' && preferred == 'k') {1144 c = 'k';1145 } else if (wanted == 'k' && preferred == 'H') {1146 c = 'H';1147 } else if (wanted == 'K' && preferred == 'h') {1148 c = 'h';1149 }1150 }1151 for ([..length]) |k| {1152 out.push(c);1153 }1154 }1155 return move out;1156}11571158// The pattern for the skeleton (getBestPattern): the best match, or1159// the date's and time's joined by the locale's date-time format.1160fn best_pattern(self locale: &Locale, asked: &[u8]) -> String {1161 // `j` is the locale's hour, a 12-hour one with its day period1162 var mapped = String::empty();1163 var at: u64 = 0;1164 while (at < asked.length()) {1165 if (asked[at] != 'j') {1166 mapped.push(asked[at]);1167 at += 1;1168 continue;1169 }1170 var extra: u64 = 0;1171 while (at + 1 < asked.length() && asked[at + 1] == 'j') {1172 extra += 1;1173 at += 1;1174 }1175 at += 1;1176 const hour_length = 1 + (extra & 1);1177 var period_length = if (extra < 2) 1 else 3 + (extra >> 1);1178 if (locale.hour == 'H' || locale.hour == 'k') {1179 period_length = 0;1180 }1181 for ([..period_length]) |k| {1182 mapped.push('a');1183 }1184 for ([..hour_length]) |k| {1185 mapped.push(locale.hour);1186 }1187 }1188 const request = skeleton_of(&mapped.view());1189 const list = locale.candidates();1190 const best = best_raw(&list, &request, 0xFFFFFFFF);1191 if (best.distance.missing == 0 && best.distance.extra == 0) {1192 return locale.adjust(&best.pattern, &best.specified, &request);1193 }1194 const needed = request.mask();1195 var date = locale.best_appending(&list, &request, needed & DATE_MASK);1196 var time = locale.best_appending(&list, &request, needed & TIME_MASK);1197 if (date.length() == 0) {1198 return move time;1199 }1200 if (time.length() == 0) {1201 return move date;1202 }1203 const month = request.base_lengths[Field::Month to u8 to u64];1204 const weekday = request.base_lengths[Field::Weekday to u8 to u64] > 0;1205 const style: u64 = if (month == 4) (if (weekday) 0 else 1) else if (month == 3) 2 else 3;1206 return joined(&locale.field(Part::DateTimeFormats, style), &time.view(), &date.view(), &"");1207}12081209// getBestAppending: the best pattern for the fields, then the best for1210// those it lacks, each joined by the locale's append item.1211fn best_appending(1212 self locale: &Locale,1213 list: &Vector<Candidate>,1214 request: &Skeleton,1215 fields: u321216) -> String {1217 if (fields == 0) {1218 return String::empty();1219 }1220 var best = best_raw(&list, &request, fields);1221 var result = locale.adjust(&best.pattern, &best.specified, &request);1222 var last_missing: u32 = 0;1223 while (best.distance.missing != 0) {1224 if (last_missing == best.distance.missing) {1225 break;1226 }1227 const starting = best.distance.missing;1228 best = best_raw(&list, &request, best.distance.missing);1229 const more = locale.adjust(&best.pattern, &best.specified, &request);1230 const found = starting & ~best.distance.missing;1231 var top: u64 = 0;1232 for ([..FIELD_COUNT]) |f| {1233 if ((found & bit(f)) != 0) {1234 top = f;1235 }1236 }1237 const item = &locale.field(Part::AppendItems, top);1238 if (item.length() > 0) {1239 result = joined(1240 &item,1241 &result.view(),1242 &more.view(),1243 "ed(&locale.field(Part::FieldNames, top)).view()1244 );1245 }1246 last_missing = best.distance.missing;1247 }1248 return move result;1249}12501251// The text quoted for a pattern, its quotes doubled.1252fn quoted(text: &[u8]) -> String {1253 var out = String::from(&"'");1254 for (text) |c| {1255 if (c == '\'') {1256 out.push('\'');1257 }1258 out.push(c);1259 }1260 out.push('\'');1261 return move out;1262}12631264// The format with {0}, {1} and {2} replaced.1265fn joined(format: &[u8], first: &[u8], second: &[u8], third: &[u8]) -> String {1266 var out = String::empty();1267 var at: u64 = 0;1268 while (at < format.length()) {1269 if (1270 at + 2 < format.length()1271 && format[at] == '{'1272 && format[at + 2] == '}'1273 && format[at + 1] >= '0'1274 && format[at + 1] <= '2'1275 ) {1276 const part: &[u8] = if (1277 format[at + 1] == '0'1278 ) &first else if (format[at + 1] == '1') &second else &third;1279 out.append(&part);1280 at += 3;1281 } else {1282 out.push(format[at]);1283 at += 1;1284 }1285 }1286 return move out;1287}12881289/* --- Writing a pattern (SimpleDateFormat) --- */12901291fn write_pattern(1292 self locale: &Locale,1293 pattern: &[u8],1294 shown: &Shown,1295 zone: &Zone,1296 out: &var String1297) {1298 var at: u64 = 0;1299 while (at < pattern.length()) {1300 const end = item_end(&pattern, at);1301 const item = &pattern[at..end];1302 at = end;1303 if (item[0] == '\'') {1304 if (item.length() == 2 && item[1] == '\'') {1305 out.push('\'');1306 continue;1307 }1308 // the quoted text, its doubled quotes single1309 var k: u64 = 1;1310 while (k < item.length()) {1311 if (item[k] == '\'') {1312 if (k + 1 < item.length() && item[k + 1] == '\'') {1313 out.push('\'');1314 k += 2;1315 continue;1316 }1317 break;1318 }1319 out.push(item[k]);1320 k += 1;1321 }1322 continue;1323 }1324 if (!is_letter(item[0])) {1325 out.append(&item);1326 continue;1327 }1328 locale.write_field(item[0], item.length(), &shown, &zone, &var out);1329 }1330}13311332fn write_field(1333 self locale: &Locale,1334 letter: u8,1335 length: u64,1336 shown: &Shown,1337 zone: &Zone,1338 out: &var String1339) {1340 const date = &shown.local.date;1341 const time = &shown.local.time;1342 match (letter) {1343 'G' {1344 out.append(&(if (date.year > 0) "AD" else "BC"));1345 }1346 'y', 'Y', 'u', 'r' {1347 var year = if (1348 letter == 'y'1349 && date.year <= 01350 ) 1 - date.year to i64 else date.year to i64;1351 if (letter == 'Y') {1352 year = locale.week_year(&date) to i64;1353 }1354 if (length == 2) {1355 locale.write_digits(year % 100, 2, &var out);1356 } else {1357 locale.write_digits(year, length, &var out);1358 }1359 }1360 'M', 'L' {1361 const context: u64 = if (letter == 'L') 36 else 0;1362 const m = date.month to u8 to u64 - 1;1363 if (length <= 2) {1364 locale.write_digits(m to i64 + 1, length, &var out);1365 } else {1366 const w: u64 = if (length == 3) 1 else if (length == 4) 0 else 2;1367 out.append(&locale.field(Part::Months, context + w * 12 + m));1368 }1369 }1370 'd' {1371 locale.write_digits(date.day to i64, length, &var out);1372 }1373 'D' {1374 const first = Date { .year = date.year, .month = Month::January, .day = 1 };1375 locale.write_digits(date.days() - first.days() + 1, length, &var out);1376 }1377 'E', 'e', 'c' {1378 const day = (date.weekday() to u8 % 7) to u64;1379 if (letter != 'E' && length <= 2) {1380 const local = (date.weekday() to u8 to i64 - locale.first to u8 to i64 + 7) % 7 + 1;1381 locale.write_digits(local, length, &var out);1382 } else {1383 const context: u64 = if (letter == 'c') 28 else 0;1384 const w: u64 = if (1385 length <= 31386 ) 1 else if (length == 4) 0 else if (length == 5) 3 else 2;1387 out.append(&locale.field(Part::Days, context + w * 7 + day));1388 }1389 }1390 'a', 'b', 'B' {1391 out.append(&locale.field(Part::DayPeriods, if (time.hour < 12) 0 else 1));1392 }1393 'h' {1394 const h = time.hour % 12;1395 locale.write_digits(if (h == 0) 12 else h to i64, length, &var out);1396 }1397 'H' {1398 locale.write_digits(time.hour to i64, length, &var out);1399 }1400 'K' {1401 locale.write_digits((time.hour % 12) to i64, length, &var out);1402 }1403 'k' {1404 locale.write_digits(if (time.hour == 0) 24 else time.hour to i64, length, &var out);1405 }1406 'm' {1407 locale.write_digits(time.minute to i64, length, &var out);1408 }1409 's' {1410 locale.write_digits(time.second to i64, length, &var out);1411 }1412 'S' {1413 var digits = shown.local.nanosecond to i64;1414 var places: u64 = 9;1415 while (places > length) {1416 digits /= 10;1417 places -= 1;1418 }1419 locale.write_digits(digits, length, &var out);1420 }1421 'z' {1422 if (length < 4 && locale.short_zone_name(&zone, &shown) is ::Some |&name|) {1423 out.append(&name);1424 } else {1425 locale.write_gmt(shown.offset, length < 4, &var out);1426 }1427 }1428 'O' {1429 locale.write_gmt(shown.offset, length < 4, &var out);1430 }1431 'Z' {1432 if (length == 4) {1433 locale.write_gmt(shown.offset, false, &var out);1434 } else {1435 write_iso_offset(shown.offset, if (length == 5) 3 else 2, length == 5, &var out);1436 }1437 }1438 'X', 'x' {1439 const style: u64 = if (length == 1) 1 else if (length == 2 || length == 4) 2 else 3;1440 write_iso_offset(shown.offset, style, letter == 'X', &var out);1441 }1442 'v', 'V' {1443 if (letter == 'V' && length == 2) {1444 out.append(&zone.name());1445 } else if (letter == 'V' && length == 3) {1446 out.append(&city_of(&zone.name()).view());1447 } else if (zone.name().starts_with(&"Etc/") || zone.name() == "UTC") {1448 locale.write_gmt(shown.offset, false, &var out);1449 } else {1450 out.append(1451 &joined(1452 &locale.field(Part::RegionFormat, 0),1453 &city_of(&zone.name()).view(),1454 &"",1455 &""1456 ).view()1457 );1458 }1459 }1460 else {}1461 }1462}14631464// The year the date's week counts in, the week from the locale's first1465// day and the year's first week holding as many days as its region asks.1466fn week_year(self locale: &Locale, date: &Date) -> i32 {1467 const least = if (region_value(&MINIMAL_DAYS, locale.region) is ::Some |d|) d to i64 else 1;1468 const day = date.days();1469 if (day < locale.first_week(date.year, least)) {1470 return date.year - 1;1471 }1472 if (day >= locale.first_week(date.year + 1, least)) {1473 return date.year + 1;1474 }1475 return date.year;1476}14771478// The first day of the year's first week.1479fn first_week(self locale: &Locale, year: i32, least: i64) -> i64 {1480 const january = Date { .year = year, .month = Month::January, .day = 1 };1481 const before = (january.weekday() to u8 to i64 - locale.first to u8 to i64 + 7) % 7;1482 const start = january.days() - before;1483 return if (7 - before >= least) start else start + 7;1484}14851486// The city a zone's name ends with, its underscores spaces:1487// `America/New_York` is New York.1488fn city_of(name: &[u8]) -> String {1489 var from: u64 = 0;1490 for (name, [..name.length()]) |c, k| {1491 if (c == '/') {1492 from = k + 1;1493 }1494 }1495 var out = String::empty();1496 for (name[from..]) |c| {1497 out.push(if (c == '_') ' ' else c);1498 }1499 return move out;1500}15011502// The number in the locale's digits, at least `width` of them.1503fn write_digits(self locale: &Locale, value: i64, width: u64, out: &var String) {1504 var ascii = String::empty();1505 const negative = value < 0;1506 var n = if (negative) -value else value;1507 while (n > 0 || ascii.length() == 0) {1508 ascii.push((n % 10) to u8 + '0');1509 n /= 10;1510 }1511 while (ascii.length() < width) {1512 ascii.push('0');1513 }1514 if (negative) {1515 out.append(&locale.field(Part::Minus, 0));1516 }1517 const digits = &locale.digits();1518 var k = ascii.length();1519 while (k > 0) {1520 k -= 1;1521 write_digit(&digits, ascii.get(k) - '0', &var out);1522 }1523}15241525// The ten digits of the locale's numbering system, one after another.1526fn digits(self locale: &Locale) -> &[u8] {1527 const system = &locale.field(Part::Numbering, 0);1528 if (system == "latn") {1529 return &"0123456789";1530 }1531 for ([..NUMBERING.length() / 2]) |k| {1532 if (pooled(NUMBERING[k * 2]) == system) {1533 return &pooled(NUMBERING[k * 2 + 1]);1534 }1535 }1536 return &"0123456789";1537}15381539fn write_digit(digits: &[u8], digit: u8, out: &var String) {1540 const size = digits.length() / 10;1541 const from = digit to u64 * size;1542 out.append(&digits[from..from + size]);1543}15441545/* --- Zones' names --- */15461547// The zone's number in the tables: its name, else the name it is an1548// alias of.1549fn zone_index(name: &[u8]) -> Option<u64> {1550 if (find_sorted(&ZONES, 1, &name) is ::Some |z|) {1551 return ::Some(z);1552 }1553 if (find_sorted(&ZONE_ALIASES, 2, &name) is ::Some |k|) {1554 return ::Some(ZONE_ALIASES[k * 2 + 1] to u64);1555 }1556 return ::None;1557}15581559// The zone's short name at the moment (`EST`, `CET`): its own, else its1560// metazone's then, where the locale has one.1561fn short_zone_name(self locale: &Locale, zone: &Zone, shown: &Shown) -> Option<&[u8]> {1562 const z = if (zone_index(&zone.name()) is ::Some |z|) z else {1563 return ::None;1564 };1565 const summer: u64 = if (shown.summer) 1 else 0;1566 if (lookup(locale.index, Part::Zones to u16 + (z * 2 + summer) to u16) is ::Some |&name|) {1567 return ::Some(&name);1568 }1569 const minutes = floor_minutes(shown.moment);1570 for ([PERIOD_STARTS[z] to u64..PERIOD_STARTS[z + 1] to u64]) |p| {1571 if (PERIOD_FROM[p] to i64 <= minutes && minutes < PERIOD_TO[p] to i64) {1572 const m = PERIOD_METAZONES[p] to u64;1573 return lookup(locale.index, Part::Metazones to u16 + (m * 2 + summer) to u16);1574 }1575 }1576 return ::None;1577}15781579fn floor_minutes(moment: i64) -> i64 {1580 const per: i64 = 60000000000;1581 const q = moment / per;1582 return if (moment % per != 0 && moment < 0) q - 1 else q;1583}15841585// The localized GMT format: `GMT+1` short, `GMT+01:00` long, `GMT` at 0.1586fn write_gmt(self locale: &Locale, offset: i64, short: bool, out: &var String) {1587 // zero is the locale's `GMT`, `GMT+0` short as V8 writes it1588 if (offset == 0 && !short) {1589 out.append(&locale.field(Part::GmtZeroFormat, 0));1590 return;1591 }1592 const formats = &locale.field(Part::HourFormat, 0);1593 const split = if (formats.find_byte(';', 0) is ::Some |s|) s else formats.length();1594 const both = if (offset >= 0) &formats[..split] else &formats[1595 min(split + 1, formats.length())..1596 ];1597 const size = if (offset > 0) offset else -offset;1598 const hours = size / 3600;1599 const minutes = size / 60 % 60;1600 const seconds = size % 60;1601 // the pattern cut after its hours, or given seconds (ICU's1602 // truncateOffsetPattern and expandOffsetPattern)1603 const mm = if (both.find(&"mm", 0) is ::Some |m|) m else both.length();1604 var hh = mm;1605 for (both[..mm], [..mm]) |c, k| {1606 if (c == 'H') {1607 hh = k;1608 }1609 }1610 var pattern = String::empty();1611 if (seconds != 0) {1612 const separator_from = if (hh < mm) hh + 1 else mm;1613 pattern.append(&both[..min(mm + 2, both.length())]);1614 pattern.append(&both[separator_from..mm]);1615 pattern.append(&"ss");1616 pattern.append(&both[min(mm + 2, both.length())..]);1617 } else if (minutes != 0 || !short) {1618 pattern.append(&both);1619 } else {1620 pattern.append(&both[..min(hh + 1, both.length())]);1621 }1622 var offset_text = String::empty();1623 const digits = &locale.digits();1624 var at: u64 = 0;1625 const p = &pattern.view();1626 while (at < p.length()) {1627 const c = p[at];1628 var end = at + 1;1629 while (end < p.length() && p[end] == c && (c == 'H' || c == 'm' || c == 's')) {1630 end += 1;1631 }1632 const value: i64 = if (c == 'H') hours else if (c == 'm') minutes else seconds;1633 if (c == 'H' || c == 'm' || c == 's') {1634 const width: u64 = if (c == 'H' && short) 1 else 2;1635 var ascii = f"{value}";1636 while (ascii.length() < width) {1637 ascii = f"0{ascii}";1638 }1639 for (ascii.view()) |d| {1640 write_digit(&digits, d - '0', &var offset_text);1641 }1642 } else {1643 offset_text.push(c);1644 }1645 at = end;1646 }1647 out.append(&joined(&locale.field(Part::GmtFormat, 0), &offset_text.view(), &"", &"").view());1648}16491650// ISO 8601's offset: `+01` (style 1, minutes when there are), `+0100`1651// (2), `+01:00` (3), `Z` for 0 when `zulu`.1652fn write_iso_offset(offset: i64, style: u64, zulu: bool, out: &var String) {1653 if (offset == 0 && zulu) {1654 out.push('Z');1655 return;1656 }1657 out.push(if (offset < 0) '-' else '+');1658 const size = if (offset < 0) -offset else offset;1659 const hours = size / 3600;1660 const minutes = size / 60 % 60;1661 out.append(&f"{hours:02}".view());1662 if (style == 1 && minutes == 0) {1663 return;1664 }1665 if (style == 3) {1666 out.push(':');1667 }1668 out.append(&f"{minutes:02}".view());1669}16701671/* --- Numbers and prices --- */16721673// Writes the number rounded to `fraction` decimals, half away from1674// zero, in the locale's digits and symbols, grouped as it groups:1675// `1 234,5` in French, `1,234.5` in English, `12,34,567` in Hindi.1676//1677// ```alloy1678// var out = String::empty();1679// Locale::of(&"en").format_number(1234.5, 1, &var out);1680// expect_equal(&out, &String::from(&"1,234.5"));1681// out.clear();1682// Locale::of(&"de").format_number(-0.125, 2, &var out);1683// expect_equal(&out, &String::from(&"-0,13"));1684// ```1685exp fn format_number(self locale: &Locale, value: f64, fraction: u8, out: &var String) {1686 if (value != value) {1687 out.append(&"NaN");1688 return;1689 }1690 const negative = value < 0.0 || (value == 0.0 && 1.0 / value < 0.0);1691 const size = if (negative) -value else value;1692 if (is_infinite(size)) {1693 if (negative) {1694 out.append(&locale.field(Part::Minus, 0));1695 }1696 out.append(&"∞");1697 return;1698 }1699 // the shortest digits that read back as the value, rounded1700 var digits = Vector<u8>::empty();1701 var point: i64 = 0; // digits before the decimal point1702 if (size != 0.0) {1703 const decimal = shortest(size);1704 digits.append(&f"{decimal.digits}".view());1705 point = decimal.exponent + digits.length() to i64;1706 }1707 const kept = point + fraction to i64;1708 if (kept < 0) {1709 digits.clear();1710 } else if (kept < digits.length() to i64) {1711 const round_up = digits.get(kept to u64) >= '5';1712 digits.truncate(kept to u64);1713 var carry = round_up;1714 var k = digits.length();1715 while (carry && k > 0) {1716 k -= 1;1717 if (digits.get(k) == '9') {1718 digits.items()[k] = '0';1719 } else {1720 digits.items()[k] += 1;1721 carry = false;1722 }1723 }1724 if (carry) {1725 digits.insert(0, '1');1726 point += 1;1727 }1728 }1729 // the integer and fraction digits, padded1730 var whole = String::empty();1731 var decimals = String::empty();1732 for ([..max(point, 0) to u64]) |k| {1733 whole.push(if (k < digits.length()) digits.get(k) else '0');1734 }1735 if (whole.length() == 0) {1736 whole.push('0');1737 }1738 for ([..fraction to u64]) |k| {1739 const at = point + k to i64;1740 decimals.push(if (at >= 0 && at < digits.length() to i64) digits.get(at to u64) else '0');1741 }1742 const amount = Amount {1743 .whole = &whole.view(),1744 .decimals = &decimals.view(),1745 .decimal = &locale.field(Part::Decimal, 0),1746 .group = &locale.field(Part::Group, 0)1747 };1748 locale.write_amount(&locale.field(Part::DecimalPattern, 0), negative, &amount, &"", &var out);1749}17501751// Writes the price, an integer of the currency's minor unit (cents for1752// EUR and USD, yen for JPY), with its symbol in the locale's currency1753// format: 2450 EUR is `24,50 €` in French, `€24.50` in English.1754//1755// ```alloy1756// var out = String::empty();1757// Locale::of(&"ja").format_money(2450, &"JPY", &var out);1758// expect_equal(&out, &String::from(&"¥2,450"));1759// out.clear();1760// Locale::of(&"en-US").format_money(-2450, &"CHF", &var out);1761// expect_equal(&out, &String::from(&"-CHF\u{a0}24.50"));1762// ```1763exp fn format_money(self locale: &Locale, amount: i64, currency: &[u8], out: &var String) {1764 var code: [u8 : 3] = [0, 0, 0];1765 var symbol = ¤cy;1766 var places: u64 = 2;1767 var own = Option<u64>::None; // the currency with a format of its own1768 if (currency.length() == 3) {1769 for ([..3]) |k| {1770 code[k] = uppercase_byte(currency[k]);1771 }1772 const wanted = packed(&code[..]);1773 var low: u64 = 0;1774 var high = CURRENCIES.length();1775 while (low < high) {1776 const middle = low + (high - low) / 2;1777 if (CURRENCIES[middle] == wanted) {1778 places = CURRENCY_DIGITS[middle] to u64;1779 own = ::Some(middle);1780 symbol = &code[..];1781 if (lookup(locale.index, Part::Currencies to u16 + middle to u16) is ::Some |&s|) {1782 symbol = &s;1783 }1784 break;1785 }1786 if (CURRENCIES[middle] < wanted) {1787 low = middle + 1;1788 } else {1789 high = middle;1790 }1791 }1792 }1793 const negative = amount < 0;1794 const size = if (negative) (-(amount + 1)) as u64 + 1 else amount as u64;1795 var scale: u64 = 1;1796 for ([..places]) |k| {1797 scale *= 10;1798 }1799 const whole = f"{size / scale}";1800 var decimals = f"{size % scale}";1801 while (decimals.length() < places) {1802 decimals = f"0{decimals}";1803 }1804 if (places == 0) {1805 decimals.clear();1806 }1807 // the currency's own format, else that of the region's currency (as1808 // ICU's DecimalFormatSymbols takes it), else the locale's1809 var formatted = Option<u64>::None;1810 if (own is ::Some |k| && locale.has_own_format(k)) {1811 formatted = ::Some(k);1812 } else if (1813 region_value(®ION_CURRENCIES, locale.region) is ::Some |k|1814 && locale.has_own_format(k to u64)1815 ) {1816 formatted = ::Some(k to u64);1817 }1818 var pattern = &locale.field(Part::CurrencyPattern, 0);1819 var decimal = &locale.money_symbol(Part::CurrencyDecimal, Part::Decimal);1820 var group = &locale.money_symbol(Part::CurrencyGroup, Part::Group);1821 if (formatted is ::Some |k|) {1822 const at = Part::CurrencyFormats to u16 + (k * 3) to u16;1823 if (lookup(locale.index, at) is ::Some |&p|) {1824 pattern = &p;1825 }1826 if (lookup(locale.index, at + 1) is ::Some |&d|) {1827 decimal = &d;1828 }1829 if (lookup(locale.index, at + 2) is ::Some |&g|) {1830 group = &g;1831 }1832 }1833 const amount_text = Amount {1834 .whole = &whole.view(),1835 .decimals = &decimals.view(),1836 .decimal = &decimal,1837 .group = &group1838 };1839 locale.write_amount(&pattern, negative, &amount_text, &symbol, &var out);1840}18411842fn has_own_format(self locale: &Locale, currency: u64) -> bool {1843 const at = Part::CurrencyFormats to u16 + (currency * 3) to u16;1844 return lookup(locale.index, at) is ::Some1845 || lookup(locale.index, at + 1) is ::Some1846 || lookup(locale.index, at + 2) is ::Some;1847}18481849// A price's separator, else the number's.1850fn money_symbol(self locale: &Locale, money: Part, number: Part) -> &[u8] {1851 if (lookup(locale.index, money to u16) is ::Some |&s|) {1852 return &s;1853 }1854 return &locale.field(number, 0);1855}18561857// An amount's digits and the separators it is written with.1858type Amount = struct {1859 whole: &[u8],1860 decimals: &[u8],1861 decimal: &[u8],1862 group: &[u8],1863};18641865// Writes the digits in the pattern (`#,##0.00 ¤;-#,##0.00 ¤`): its1866// prefix and suffix, the negative one or the minus sign before the1867// positive, the integer grouped by its sizes and the locale's least1868// grouping, the currency's symbol for `¤`, spaced from the digits where1869// the symbol ends in a letter.1870fn write_amount(1871 self locale: &Locale,1872 patterns: &[u8],1873 negative: bool,1874 amount: &Amount,1875 symbol: &[u8],1876 out: &var String1877) {1878 const whole = &amount.whole;1879 const decimals = &amount.decimals;1880 const split = if (patterns.find_byte(';', 0) is ::Some |s|) s else patterns.length();1881 const positive = &patterns[..split];1882 var pattern = &positive;1883 var minus_before = negative;1884 if (negative && split < patterns.length()) {1885 pattern = &patterns[split + 1..];1886 minus_before = false;1887 }1888 // prefix, number, suffix1889 var start = pattern.length();1890 var end: u64 = 0;1891 for (pattern, [..pattern.length()]) |c, k| {1892 if (c == '#' || c == '0' || c == ',' || c == '.') {1893 if (k < start) {1894 start = k;1895 }1896 end = k + 1;1897 }1898 }1899 if (start > end) {1900 start = 0;1901 end = 0;1902 }1903 const prefix = &pattern[..start];1904 const suffix = &pattern[end..];1905 // grouping sizes from the positive pattern's integer part1906 const number = &positive[1907 if (positive.find_byte('#', 0) is ::Some |h|) min(h, positive.length()) else 0..1908 ];1909 const integer_end = if (number.find_byte('.', 0) is ::Some |p|) p else number.length();1910 var commas = Vector<u64>::empty();1911 var digits_end = integer_end;1912 for (number[..integer_end], [..integer_end]) |c, k| {1913 if (c == ',') {1914 commas.push(k);1915 }1916 if (1917 c != '#'1918 && c != '0'1919 && c != ','1920 && k < digits_end1921 && k > 01922 && digits_end == integer_end1923 ) {1924 digits_end = k;1925 }1926 }1927 var primary: u64 = 0;1928 var secondary: u64 = 0;1929 if (commas.length() > 0) {1930 primary = digits_end - commas.last() - 1;1931 secondary = if (1932 commas.length() > 11933 ) commas.last() - commas.get(commas.length() - 2) - 1 else primary;1934 }1935 const least_text = &locale.field(Part::MinimumGrouping, 0);1936 const least = if (least_text.parse_integer() is ::Some |n|) n to u64 else 1;1937 var body = String::empty();1938 const digits = &locale.digits();1939 const group = &amount.group;1940 const decimal = &amount.decimal;1941 const grouped = primary > 0 && whole.length() >= primary + least;1942 for (whole, [..whole.length()]) |d, k| {1943 write_digit(&digits, d - '0', &var body);1944 const after = whole.length() - k - 1; // digits after this one1945 if (grouped && after > 0 && after >= primary && (after - primary) % secondary == 0) {1946 body.append(&group);1947 }1948 }1949 if (decimals.length() > 0) {1950 body.append(&decimal);1951 for (decimals) |d| {1952 write_digit(&digits, d - '0', &var body);1953 }1954 }1955 const space = &locale.field(Part::CurrencySpace, 0);1956 if (minus_before) {1957 out.append(&locale.field(Part::Minus, 0));1958 }1959 write_affix(&prefix, &symbol, &locale.field(Part::Minus, 0), &var out);1960 if (prefix.ends_with(&"¤") && symbol.length() > 0 && !is_symbol_or_space(last_char(&symbol))) {1961 out.append(&space);1962 }1963 out.append(&body.view());1964 if (1965 suffix.starts_with(&"¤")1966 && symbol.length() > 01967 && !is_symbol_or_space(first_char(&symbol))1968 ) {1969 out.append(&space);1970 }1971 write_affix(&suffix, &symbol, &locale.field(Part::Minus, 0), &var out);1972}19731974// An affix with `¤` the symbol and `-` the locale's minus sign.1975fn write_affix(affix: &[u8], symbol: &[u8], minus: &[u8], out: &var String) {1976 var at: u64 = 0;1977 while (at < affix.length()) {1978 if (affix[at..].starts_with(&"¤")) {1979 out.append(&symbol);1980 at += 2;1981 } else if (affix[at] == '-') {1982 out.append(&minus);1983 at += 1;1984 } else {1985 out.push(affix[at]);1986 at += 1;1987 }1988 }1989}19901991fn first_char(text: &[u8]) -> u32 {1992 var end: u64 = 1;1993 while (end < text.length() && (text[end] & 0xC0) == 0x80) {1994 end += 1;1995 }1996 return decode(&text[..end]);1997}19981999fn last_char(text: &[u8]) -> u32 {2000 var start = text.length() - 1;2001 while (start > 0 && (text[start] & 0xC0) == 0x80) {2002 start -= 1;2003 }2004 return decode(&text[start..]);2005}20062007fn decode(bytes: &[u8]) -> u32 {2008 const lead = bytes[0] to u32;2009 if (lead < 0x80) {2010 return lead;2011 }2012 var c = if (lead >= 0xF0) lead & 7 else if (lead >= 0xE0) lead & 15 else lead & 31;2013 for (bytes[1..]) |b| {2014 c = c << 6 | (b & 63) to u32;2015 }2016 return c;2017}20182019// Whether a currency symbol's character is a symbol (General_Category S)2020// or a space (Z), which currency spacing leaves alone: `$`, `€`, `₹`,2021// `¥`, but not `F` of `CHF` nor `.` of `руб.`.2022fn is_symbol_or_space(c: u32) -> bool {2023 if (c < 0x80) {2024 return c == '$'2025 || c == '+'2026 || c == '<'2027 || c == '='2028 || c == '>'2029 || c == '^'2030 || c == '`'2031 || c == '|'2032 || c == '~'2033 || c == ' ';2034 }2035 return (c >= 0xA2 && c <= 0xA9)2036 || c == 0xAC2037 || (c >= 0xAE && c <= 0xB1)2038 || c == 0xB42039 || c == 0xB82040 || c == 0xD72041 || c == 0xF72042 || c == 0xA02043 || c == 0x58F2044 || c == 0x60B2045 || (c >= 0x7FE && c <= 0x7FF)2046 || c == 0x9F22047 || c == 0x9F32048 || c == 0x9FB2049 || c == 0xAF12050 || c == 0xBF92051 || c == 0xE3F2052 || c == 0x17DB2053 || (c >= 0x2000 && c <= 0x200A)2054 || c == 0x202F2055 || c == 0x205F2056 || (c >= 0x20A0 && c <= 0x20CF)2057 || c == 0x30002058 || c == 0xA8382059 || c == 0xFDFC2060 || c == 0xFE692061 || c == 0xFF042062 || (c >= 0xFFE0 && c <= 0xFFE6);2063}20642065/* --- Text --- */20662067fn all_letters(text: &[u8]) -> bool {2068 for (text) |c| {2069 if (!is_letter(c)) {2070 return false;2071 }2072 }2073 return true;2074}20752076fn all_digits(text: &[u8]) -> bool {2077 for (text) |c| {2078 if (c < '0' || c > '9') {2079 return false;2080 }2081 }2082 return true;2083}20842085fn lowercase(text: &[u8]) -> String {2086 var out = String::empty();2087 for (text) |c| {2088 out.push(if (c >= 'A' && c <= 'Z') c + 32 else c);2089 }2090 return move out;2091}20922093fn uppercase(text: &[u8]) -> String {2094 var out = String::empty();2095 for (text) |c| {2096 out.push(uppercase_byte(c));2097 }2098 return move out;2099}21002101fn uppercase_byte(c: u8) -> u8 => if (c >= 'a' && c <= 'z') c - 32 else c;21022103/* --- Reading what the locale writes (alloy-ui's decisions/F13.md, F13b) --- */21042105// The number the text writes in the locale, the inverse of2106// `format_number` made forgiving: the locale's digits or ASCII ones, its2107// minus sign or `-`, its group sign between digits of the whole part (any2108// space where that sign is a space), and its decimal sign, or a point2109// where the point groups nothing. None when the text writes no number.2110//2111// ```alloy2112// expect(Locale::of(&"fr").parse_number(&"-1 234,5") == ::Some(-1234.5 to f64));2113// expect(Locale::of(&"en-US").parse_number(&"1,234.5") == ::Some(1234.5 to f64));2114// expect(Locale::of(&"de").parse_number(&"2,5") == ::Some(2.5 to f64));2115// expect(Locale::of(&"fr").parse_number(&"2.5") == ::Some(2.5 to f64));2116// expect(Locale::of(&"ar-EG").parse_number(&"١٢٣٫٥") == ::Some(123.5 to f64));2117// expect(Locale::of(&"en").parse_number(&"12a") is ::None);2118// ```2119exp fn parse_number(self locale: &Locale, text: &[u8]) -> Option<f64> {2120 const plain = locale.plain(&text);2121 const t = &plain.view();2122 const decimal = unmarked(&locale.field(Part::Decimal, 0));2123 const group = unmarked(&locale.field(Part::Group, 0));2124 const spaced = group.length() > 0 && is_space(first_char(&group.view()));2125 var at: u64 = 0;2126 var ascii = String::empty();2127 const minus = unmarked(&locale.field(Part::Minus, 0));2128 if (minus.length() > 0 && t.starts_with(&minus.view())) {2129 ascii.push('-');2130 at = minus.length();2131 } else if (t.starts_with(&"-") || t.starts_with(&"\u{2212}")) {2132 ascii.push('-');2133 at = if (t[0] == '-') 1 else 3;2134 } else if (t.starts_with(&"+")) {2135 at = 1;2136 }2137 var digits: u64 = 0;2138 var point = false;2139 var after_point: u64 = 0;2140 while (at < t.length()) {2141 const c = t[at];2142 if (c >= '0' && c <= '9') {2143 ascii.push(c);2144 digits += 1;2145 if (point) {2146 after_point += 1;2147 }2148 at += 1;2149 continue;2150 }2151 if (point) {2152 return ::None;2153 }2154 if (decimal.length() > 0 && t[at..].starts_with(&decimal.view())) {2155 ascii.push('.');2156 point = true;2157 at += decimal.length();2158 continue;2159 }2160 // a group sign, or a space standing for one, between digits2161 var skip: u64 = 0;2162 if (group.length() > 0 && t[at..].starts_with(&group.view())) {2163 skip = group.length();2164 } else if (spaced && is_space(first_char(&t[at..]))) {2165 skip = char_length(c);2166 } else if (c == '\'' && group.view() == "\u{2019}") {2167 skip = 1;2168 } else if (t[at..].starts_with(&"\u{2019}") && group.view() == "'") {2169 skip = 3;2170 }2171 if (skip > 0 && digits > 0 && at + skip < t.length() && is_ascii_digit(t[at + skip])) {2172 at += skip;2173 continue;2174 }2175 // a point grouping nothing is a decimal point2176 if (c == '.' && group.view() != ".") {2177 ascii.push('.');2178 point = true;2179 at += 1;2180 continue;2181 }2182 return ::None;2183 }2184 if (digits == 0 || (point && after_point == 0)) {2185 return ::None;2186 }2187 return read_decimal(&ascii.view());2188}21892190// The day the text writes in the locale's short date, its parts in the2191// locale's order and separated by any of `/ . -`, spaces or what the2192// locale writes between them, its digits or ASCII ones; or written as ISO2193// 8601 (`2026-11-21`), unless the locale writes the year, then the day,2194// then the month (Kyrgyz's `2026-21-11`). A year of two digits falls between 802195// years before this one and 20 after, as ICU places it.2196//2197// ```alloy2198// const day = ::Some(Date::of(2026, Month::November, 21));2199// expect(Locale::of(&"en-GB").parse_date(&"21/11/2026") == day);2200// expect(Locale::of(&"en-US").parse_date(&"11/21/2026") == day);2201// expect(Locale::of(&"de").parse_date(&"21.11.26") == day);2202// expect(Locale::of(&"ja").parse_date(&"2026/11/21") == day);2203// expect(Locale::of(&"en-US").parse_date(&"2026-11-21") == day);2204// expect(Locale::of(&"en-GB").parse_date(&"31/02/2026") is ::None);2205// ```2206exp fn parse_date(self locale: &Locale, text: &[u8]) -> Option<Date> {2207 const pattern = locale.best_pattern(&"yMd");2208 var order: [u8 : 3] = [0, 0, 0];2209 var found: u64 = 0;2210 const literals = literal_text(&pattern.view());2211 var at: u64 = 0;2212 while (at < pattern.length()) {2213 const c = pattern.get(at);2214 if (c == '\'') {2215 at += 1;2216 while (at < pattern.length() && pattern.get(at) != '\'') {2217 at += 1;2218 }2219 at += 1;2220 continue;2221 }2222 if (is_letter(c)) {2223 const field: u8 = if (c == 'L') 'M' else c;2224 var seen = false;2225 for (order[..found]) |f| {2226 seen = seen || f == field;2227 }2228 if (!seen && found < 3 && (field == 'y' || field == 'M' || field == 'd')) {2229 order[found] = field;2230 found += 1;2231 }2232 }2233 at += 1;2234 }2235 if (order[0] != 'y' || order[1] != 'd') {2236 if (Date::parse_iso(&text.trim()) is ::Some |d|) {2237 return ::Some(d);2238 }2239 }2240 if (found != 3) {2241 return ::None;2242 }2243 var numbers: [u64 : 3] = [0, 0, 0];2244 var widths: [u64 : 3] = [0, 0, 0];2245 if (!locale.numbers_in(&text, &literals.view(), &var numbers, &var widths)) {2246 return ::None;2247 }2248 // a year written first where the locale writes it last2249 if (widths[0] == 4 && order[0] != 'y') {2250 order = ['y', 'M', 'd'];2251 }2252 var year: i64 = 0;2253 var month: u64 = 0;2254 var day: u64 = 0;2255 for (order, [..3 to u64]) |field, k| {2256 if (field == 'y') {2257 year = numbers[k] to i64;2258 if (widths[k] <= 2) {2259 const now = Date::today().year to i64;2260 year += now / 100 * 100;2261 if (year >= now + 20) {2262 year -= 100;2263 } else if (year < now - 80) {2264 year += 100;2265 }2266 }2267 } else if (field == 'M') {2268 month = numbers[k];2269 } else {2270 day = numbers[k];2271 }2272 }2273 if (month < 1 || month > 12 || day < 1 || day > 31 || year < 1 || year > 9999) {2274 return ::None;2275 }2276 if (Month::from(month to u8) is ::Some |m|) {2277 return Date::try_of(year to i32, m, day to u8);2278 }2279 return ::None;2280}22812282// The time of day the text writes: on a 24-hour clock (`14:30`, `14`,2283// `14.30`), or a 12-hour one with the locale's day period or am and pm in2284// any case, dots and spaces aside (`2:30 pm`, `2 P.M.`, `午後2:30`); its2285// digits or ASCII ones. Seconds may follow, and are dropped.2286//2287// ```alloy2288// const at = ::Some(TimeOfDay::of(14, 30));2289// expect(Locale::of(&"en-GB").parse_time(&"14:30") == at);2290// expect(Locale::of(&"en-US").parse_time(&"2:30 PM") == at);2291// expect(Locale::of(&"en-US").parse_time(&"2:30p.m.") == at);2292// expect(Locale::of(&"ja").parse_time(&"午後2:30") == at);2293// expect(Locale::of(&"fr").parse_time(&"14") == ::Some(TimeOfDay::of(14, 0)));2294// expect(Locale::of(&"en").parse_time(&"12:00 am") == ::Some(TimeOfDay::of(0, 0)));2295// expect(Locale::of(&"en").parse_time(&"25:00") is ::None);2296// ```2297exp fn parse_time(self locale: &Locale, text: &[u8]) -> Option<TimeOfDay> {2298 const plain = locale.plain(&text);2299 const t = &plain.view();2300 const pattern = locale.best_pattern(&"jmm");2301 const literals = literal_text(&pattern.view());2302 const am = folded(&locale.field(Part::DayPeriods, 0));2303 const pm = folded(&locale.field(Part::DayPeriods, 1));2304 var period = Option<bool>::None; // whether after noon2305 var numbers: [u64 : 3] = [0, 0, 0];2306 var widths: [u64 : 3] = [0, 0, 0];2307 var count: u64 = 0;2308 var at: u64 = 0;2309 while (at < t.length()) {2310 var end = at;2311 const digit = is_ascii_digit(t[at]);2312 while (end < t.length() && is_ascii_digit(t[end]) == digit) {2313 end += 1;2314 }2315 const piece = &t[at..end];2316 at = end;2317 if (digit) {2318 if (count == 3 || piece.length() > 4) {2319 return ::None;2320 }2321 numbers[count] = if (piece.parse_integer() is ::Some |n|) n to u64 else 0;2322 widths[count] = piece.length();2323 count += 1;2324 continue;2325 }2326 const word = folded(&piece);2327 if (word.length() == 0 || literals.view().contains(&word.view())) {2328 continue;2329 }2330 if (period is ::None && (word.view() == pm.view() || word.view() == "pm")) {2331 period = ::Some(true);2332 } else if (period is ::None && (word.view() == am.view() || word.view() == "am")) {2333 period = ::Some(false);2334 } else {2335 return ::None;2336 }2337 }2338 // `1430` or `930` written without a separator2339 if (count == 1 && widths[0] >= 3) {2340 numbers[1] = numbers[0] % 100;2341 numbers[0] = numbers[0] / 100;2342 count = 2;2343 }2344 if (count == 0) {2345 return ::None;2346 }2347 var hour = numbers[0];2348 if (period is ::Some |after_noon|) {2349 if (hour > 12) {2350 return ::None;2351 }2352 hour = hour % 12 + if (after_noon) 12 else 0;2353 }2354 if (hour > 23 || numbers[1] > 59 || numbers[2] > 59) {2355 return ::None;2356 }2357 return ::Some(TimeOfDay::of(hour to u8, numbers[1] to u8));2358}23592360// The text with the locale's digits made ASCII ones, the marks setting2361// text's direction left out, and the spaces at either end.2362fn plain(self locale: &Locale, text: &[u8]) -> String {2363 const digits = &locale.digits();2364 const size = digits.length() / 10;2365 var out = String::empty();2366 var at: u64 = 0;2367 while (at < text.length()) {2368 var digit = Option<u8>::None;2369 if (size > 1) {2370 for ([..10 to u64]) |k| {2371 if (text[at..].starts_with(&digits[k * size..(k + 1) * size])) {2372 digit = ::Some(k to u8);2373 }2374 }2375 }2376 if (digit is ::Some |d|) {2377 out.push('0' + d);2378 at += size;2379 continue;2380 }2381 const length = char_length(text[at]);2382 if (!is_mark(first_char(&text[at..]))) {2383 out.append(&text[at..min(at + length, text.length())]);2384 }2385 at += length;2386 }2387 // the spaces at either end, no-break ones too2388 var start: u64 = 0;2389 var end = out.length();2390 while (start < end && is_space(first_char(&out.view()[start..]))) {2391 start += char_length(out.get(start));2392 }2393 while (end > start && is_space(last_char(&out.view()[start..end]))) {2394 end -= 1;2395 while (end > start && (out.get(end) & 0xC0) == 0x80) {2396 end -= 1;2397 }2398 }2399 return String::from(&out.view()[start..end]);2400}24012402// The three numbers of a date the text writes, their digits' counts too,2403// whatever is between them a separator: `/ . - ,`, a space or what the2404// locale writes between its fields; whether it writes three and only.2405fn numbers_in(2406 self locale: &Locale,2407 text: &[u8],2408 literals: &[u8],2409 numbers: &var [u64 : 3],2410 widths: &var [u64 : 3]2411) -> bool {2412 const plain = locale.plain(&text);2413 const t = &plain.view();2414 var count: u64 = 0;2415 var at: u64 = 0;2416 while (at < t.length()) {2417 if (is_ascii_digit(t[at])) {2418 var end = at;2419 while (end < t.length() && is_ascii_digit(t[end])) {2420 end += 1;2421 }2422 if (count == 3 || end - at > 4) {2423 return false;2424 }2425 numbers[count] = if (t[at..end].parse_integer() is ::Some |n|) n to u64 else 0;2426 widths[count] = end - at;2427 count += 1;2428 at = end;2429 continue;2430 }2431 const length = char_length(t[at]);2432 const piece = &t[at..min(at + length, t.length())];2433 const c = first_char(&piece);2434 if (!(is_space(c) || (&"/.-,").contains(&piece) || literals.contains(&piece))) {2435 return false;2436 }2437 at += length;2438 }2439 return count == 3;2440}24412442// The text in ASCII's lower case, its dots, colons and spaces left out:2443// "P.M." and "p. m." are "pm".2444fn folded(text: &[u8]) -> String {2445 var out = String::empty();2446 var at: u64 = 0;2447 while (at < text.length()) {2448 const length = char_length(text[at]);2449 const piece = &text[at..min(at + length, text.length())];2450 const c = first_char(&piece);2451 if (!(is_space(c) || is_mark(c) || c == '.' || c == ':')) {2452 if (c >= 'A' && c <= 'Z') {2453 out.push((c + 32) to u8);2454 } else {2455 out.append(&piece);2456 }2457 }2458 at += length;2459 }2460 return move out;2461}24622463// What a pattern writes as it is: its quoted text and what is not a2464// field's letter.2465fn literal_text(pattern: &[u8]) -> String {2466 var out = String::empty();2467 var quoted = false;2468 for (pattern) |c| {2469 if (c == '\'') {2470 quoted = !quoted;2471 } else if (quoted || !is_letter(c)) {2472 out.push(c);2473 }2474 }2475 return move out;2476}24772478// The text without the marks setting text's direction.2479fn unmarked(text: &[u8]) -> String {2480 var out = String::empty();2481 var at: u64 = 0;2482 while (at < text.length()) {2483 const length = char_length(text[at]);2484 const piece = &text[at..min(at + length, text.length())];2485 if (!is_mark(first_char(&piece))) {2486 out.append(&piece);2487 }2488 at += length;2489 }2490 return move out;2491}24922493fn char_length(lead: u8) -> u64 => if (lead < 0xC0) 1 else if (lead < 0xE0) 2 else if (2494 lead < 0xF02495) 3 else 4;24962497fn is_ascii_digit(c: u8) -> bool => c >= '0' && c <= '9';24982499// Left-to-right and right-to-left marks, and Arabic's letter mark.2500fn is_mark(c: u32) -> bool => c == 0x200E || c == 0x200F || c == 0x61C;25012502// A space, a no-break one, a narrow or a thin one.2503fn is_space(c: u32) -> bool => c == ' '2504 || c == '\t'2505 || c == 0xA02506 || c == 0x202F2507 || c == 0x20092508 || c == 0x2007;25092510/* --- F12e as built --- */25112512// **F12e as built** (2026-10-16; alloy-ui's decisions/F12.md, "Dates in the2513// world", questions 11A-14A):2514// - The data: CLDR 48.0 (the release in the distrobox's node, ICU 78.2),2515// fetched by `cldr/fetch.sh` from cldr-json's pinned, checksummed zip2516// into the cache, and written into `locale_data.alloy` by2517// `cldr/generate.alloy`: the 429 locales of modern coverage and the2518// root, each the entries that differ from its parent's (an empty one2519// marking a field the parent has and it lacks), over one pool of2520// 61 KB of text; parents, likely regions and scripts, region2521// currencies and digits, first days and minimal days of the week, hour2522// cycles by region and tag, numbering systems, 420 zones and the2523// history of their metazones, and since question 28A (2026-10-16)2524// which locales are written right to left (CLDR's layout,2525// `cldr-misc-full`), which `right_to_left()` reads. `// locale tags:`2526// lines list the tags for tests.2527// - `Locale::of` reads a BCP 47 tag (any case, `_` too, old codes such as2528// `iw`, `-u-hc-` and `-u-fw-`) to the nearest locale the tables have,2529// adding the likely script (`zh-TW` is `zh-Hant-TW`) and region.2530// `Locale::system()`: `LC_ALL`, `LC_TIME`, `LANG` on Linux and under2531// WASI (`.UTF-8` and `@euro` dropped, `C` and `POSIX` `en`);2532// `GetUserDefaultLocaleName` with `LOCALE_IFIRSTDAYOFWEEK` and2533// `LOCALE_STIMEFORMAT` on Windows; `CFLocaleCopyCurrent`, the current2534// calendar's first weekday and `AppleICUForce24HourTime` or2535// `AppleICUForce12HourTime` on macOS, through `Library` (built, not yet2536// run there); `navigator.languages` and `Intl.Locale`'s week on the web2537// (`locale.web.js`).2538// - Names: `month_name` and `weekday_name` give the standalone forms in2539// the design's widths, Wide, Short and Narrow; CLDR's short weekdays2540// ("Mo"), F12e's `Width::Shortest` until question 30B dropped it, are2541// left to patterns (`EEEEEE`).2542// - Formats follow ICU's DateTimePatternGenerator step by step: the2543// skeleton the components make (`j` the locale's hour), its candidates2544// (canonical items, date and time formats, the flexible formats of the2545// locale and its parents), the nearest by ICU's distance, fields2546// adjusted to the request's lengths, missing ones appended through the2547// locale's append items, a date and a time joined by the date-time2548// format the month's width picks (`atTime` where there is one). The2549// writer takes CLDR's letters, eras to zones: zone names from the zone2550// or its metazone at the moment, else the localized GMT format; cities2551// from the zone's name in English (question 31). The pattern is found2552// on every call (question 25).2553// - Numbers: the shortest digits that read back, rounded half away from2554// zero to the fraction, grouped by the pattern's sizes and the2555// locale's minimum grouping, in its digits and symbols; prices in the2556// currency's minor unit, its digits and symbol, the currency's own2557// format where a locale has one (ICU's DecimalFormatSymbols), spaced2558// from the number by CLDR's currency spacing.2559// - Tests: `tests/driver/locale_intl.sh` compares with node's2560// `Intl.DateTimeFormat` and `Intl.NumberFormat` every locale of the2561// tables ICU has (424 of 430), every combination of the components at2562// three moments, eight of them at forty moments in twelve zones,2563// sixteen numbers and six amounts in twelve currencies: about 840,0002564// cases, all the same (U+202F read as V8's space in dates,2565// question 32; the dates of ten Chinese and Cantonese locales and2566// `fr-ML` left out, cldr-json and ICU 78.2's own tables differing2567// there). `tests/driver/locale_system.sh` reads tags and the system's2568// locale natively, interpreted, under wasmtime and in node.2569// - Size: a program writing a date with names and a price carries the2570// tables and the generator, about 224 KB natively and 227 KB of wasm2571// more than one writing neither (question 26).25722573/* --- F13b as built --- */25742575// **F13b as built** (2026-10-17; alloy-ui's decisions/F13.md, question 8A):2576// - `parse_number`, `parse_date` and `parse_time` read what a person2577// types where the locale's way is expected, for pkg::alloy::ui's2578// `Parse::number`, `date` and `time`. Each first makes the text plain:2579// the locale's digits as ASCII ones, direction marks dropped, the2580// spaces at either end (no-break ones too) trimmed.2581// - Numbers: the locale's minus, `-`, `−` or `+`; its decimal sign; its2582// group sign between digits of the whole part, any space where that2583// sign is a space, and an ASCII apostrophe for U+2019 and the other way2584// (de-CH writes either), the groups' sizes unchecked; a point grouping2585// nothing is a decimal point where the decimal sign is a comma (`2.5`2586// in French). Read by `read_decimal`, as Ryu's digits are written.2587// - Dates: the order of the year, month and day in the locale's short2588// date (`best_pattern("yMd")`), the parts separated by `/ . -`, spaces2589// or the pattern's own literals; a four-digit year first read as ISO's2590// order; ISO 8601 itself unless the locale writes the year, the day and2591// then the month (Kyrgyz), where its own way wins. Two-digit years as2592// ICU places them, 80 years back to 20 ahead; days checked against the2593// month.2594// - Times: hours alone, `h:mm`, `h.mm`, `h mm` or `14 h 30` (the2595// pattern's quoted literals), seconds dropped; a day period from the2596// locale's own names, or am and pm, before or after, in any case with2597// dots and spaces aside (`午後2:30`, `PM 2:30`, `2 p.m.`); 12 am is2598// midnight.2599// - Tests: `tests/run/locale_parsing.alloy`, a table across scripts and2600// writing orders, natively too; `tests/driver/locale_parse.sh` reads2601// back forty short dates, forty times and ten numbers per locale that2602// node's `Intl` wrote, in locale_intl.sh's sample, and with2603// ALLOY_FULL_LOCALES=1 in all 424 locales ICU has (38,160 cases), all2604// read back.