1// Time: a monotonic clock for measuring, the wall clock, sleeping, and2// the calendar: days of the proleptic Gregorian calendar, times of day3// and the system's offset from UTC; time zones by name from the4// platform's database, dates and times on a zone's clocks, and ISO 8601,5// RFC 3339 and HTTP dates (F12e, notes at the end).6//7// The externs are the runtime's (alloyc/src/support/system.c); the8// interpreter reads the same clocks, and on the web the page's time zone9// comes through std::web.10//11// ```alloy12// const day = Date::of(2026, Month::October, 15);13// expect(day.weekday() == Weekday::Thursday);14// expect_equal(&f"{day.add_days(17)}", &String::from(&"2026-11-01"));15// expect(Date::of(2026, Month::January, 31).add_months(1) == Date::of(2026, Month::February, 28));16// ```1718import std::string;19import std::format;20import std::option;21import std::number;22import std::math;23import std::process;24import std::web;25import std::vector;26import std::io;27import std::text;28import std::ffi;2930extern al_sys_monotonic() -> u64;31extern al_sys_wall() -> i64;32extern al_sys_sleep(nanoseconds: u64);33extern al_sys_local_offset(seconds: i64) -> i64;34extern al_sys_zone_name(buffer: &var [u8], capacity: u64) -> i64;35extern al_sys_zone_known(name: c_string) -> i32;36extern al_sys_zone_offsets(name: c_string, seconds: i64, out: &var [i64]) -> i32;37extern al_time_zone_known(name: c_pointer, length: u32) -> u32; // time.web.js38extern al_time_zone_offsets(name: c_pointer, length: u32, seconds: i64, out: c_pointer);39extern al_time_page_zone(at: c_pointer, capacity: u32) -> u32;4041// A span of time, in nanoseconds.42exp type Duration : Format = struct {43 exp nanoseconds: u6444};4546exp fn Duration::from_nanoseconds(nanoseconds: u64) -> Duration {47 return Duration { .nanoseconds = nanoseconds };48}4950exp fn Duration::from_microseconds(microseconds: u64) -> Duration {51 return Duration { .nanoseconds = microseconds * 1000 };52}5354exp fn Duration::from_milliseconds(milliseconds: u64) -> Duration {55 return Duration { .nanoseconds = milliseconds * 1000000 };56}5758// The seconds rounded to the nearest nanosecond; a negative or NaN count59// is zero.60exp fn Duration::from_seconds(seconds: f64) -> Duration {61 if (!(seconds > 0.0)) {62 return Duration { .nanoseconds = 0 };63 }64 return Duration { .nanoseconds = (seconds * 1000000000.0 + 0.5) to u64 };65}6667exp fn seconds(self d: &Duration) -> f64 {68 return (d.nanoseconds to f64) / 1000000000.0;69}7071exp fn milliseconds(self d: &Duration) -> f64 {72 return (d.nanoseconds to f64) / 1000000.0;73}7475// The duration in seconds: `0.016667s`.76exp fn format(self d: &Duration, out: &var String) {77 out.write_fixed(d.seconds(), 6);78 out.push('s');79}8081// A moment on the monotonic clock, which never goes back: for frame times82// and measurements.83exp type Instant = struct {84 nanoseconds: u6485};8687exp fn Instant::now() -> Instant {88 return Instant { .nanoseconds = al_sys_monotonic() };89}9091// The time since this moment.92exp fn elapsed(self start: &Instant) -> Duration {93 return Instant::now().since(&start);94}9596// The time from the earlier moment to this one; zero when it is later.97exp fn since(self later: &Instant, earlier: &Instant) -> Duration {98 if (later.nanoseconds < earlier.nanoseconds) {99 return Duration { .nanoseconds = 0 };100 }101 return Duration { .nanoseconds = later.nanoseconds - earlier.nanoseconds };102}103104// Nanoseconds since 1970-01-01 UTC on the wall clock, which may jump when105// the system's time is set.106exp fn wall_clock() -> i64 {107 return al_sys_wall();108}109110// Waits at least the duration.111exp fn sleep(duration: Duration) {112 al_sys_sleep(duration.nanoseconds);113}114115// Waits until the wall clock reaches the moment (nanoseconds since 1970116// UTC, as `wall_clock` gives), looking at it again at least every 5117// seconds, so a moment passed while the machine slept or the system's118// time was set ends the wait at most that late.119//120// ```alloy121// const moment = wall_clock() + 20000000; // 20 ms from now122// sleep_until(moment);123// expect(wall_clock() >= moment);124// ```125exp fn sleep_until(moment: i64) {126 while (true) {127 const now = wall_clock();128 if (now >= moment) {129 return;130 }131 sleep(Duration::from_nanoseconds(min((moment - now) to u64, 5000000000)));132 }133}134135/* --- The calendar --- */136137exp type Month = enum : u8 {138 January = 1,139 February = 2,140 March = 3,141 April = 4,142 May = 5,143 June = 6,144 July = 7,145 August = 8,146 September = 9,147 October = 10,148 November = 11,149 December = 12,150};151152// The days of the week in ISO 8601's order and numbers, Monday first.153exp type Weekday = enum : u8 {154 Monday = 1,155 Tuesday = 2,156 Wednesday = 3,157 Thursday = 4,158 Friday = 5,159 Saturday = 6,160 Sunday = 7,161};162163// The day `days` after this one, going round the week.164exp fn add(self w: &Weekday, days: i64) -> Weekday {165 const n = floor_mod(w to u8 to i64 - 1 + days, 7);166 if (Weekday::from(n to u8 + 1) is ::Some |day|) {167 return day;168 }169 panic "std::time: no such weekday";170}171172// A day of the proleptic Gregorian calendar, the one in use today taken173// back before 1582; year 0 is 1 BC.174exp type Date : Format = struct {175 exp year: i32,176 exp month: Month,177 exp day: u8,178};179180// The day; faults on a day the month does not have, such as 30 February.181exp fn Date::of(year: i32, month: Month, day: u8) -> Date {182 if (Date::try_of(year, month, day) is ::Some |date|) {183 return date;184 }185 panic "std::time: no such day in the month";186}187188// The day, or None when the month does not have it.189exp fn Date::try_of(year: i32, month: Month, day: u8) -> Option<Date> {190 if (day < 1 || day > days_in_month(year, month)) {191 return ::None;192 }193 return ::Some(Date { .year = year, .month = month, .day = day });194}195196// The day `days` after 1970-01-01, before it when negative (Howard197// Hinnant's civil_from_days).198exp fn Date::from_days(days: i64) -> Date {199 const z = days + 719468;200 const era = floor_div(z, 146097);201 const of_era = z - era * 146097;202 const year_of_era = (203 of_era - of_era / 1460 + of_era / 36524 - of_era / 146096204 ) / 365;205 const of_year = of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);206 const shifted = (5 * of_year + 2) / 153; // from March207 const day = of_year - (153 * shifted + 2) / 5 + 1;208 const month = if (shifted < 10) shifted + 3 else shifted - 9;209 const year = year_of_era + era * 400 + if (month <= 2) 1 else 0;210 return Date { .year = year to i32, .month = month_of(month), .day = day to u8 };211}212213// Today in the system's time zone.214exp fn Date::today() -> Date {215 const now = wall_clock();216 const seconds = floor_div(now, 1000000000) + local_offset(now);217 return Date::from_days(floor_div(seconds, 86400));218}219220// The days since 1970-01-01, negative before it (Howard Hinnant's221// days_from_civil).222exp fn days(self d: &Date) -> i64 {223 const month = d.month to u8 to i64;224 const year = d.year to i64 - if (month <= 2) 1 else 0;225 const era = floor_div(year, 400);226 const year_of_era = year - era * 400;227 const of_year = (153 * (if (month > 2) month - 3 else month + 9) + 2) / 5 + d.day to i64 - 1;228 const of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + of_year;229 return era * 146097 + of_era - 719468;230}231232exp fn weekday(self d: &Date) -> Weekday => Weekday::Thursday.add(d.days()); // 1970-01-01's233234exp fn add_days(self d: &Date, days: i64) -> Date => Date::from_days(d.days() + days);235236// The same day `months` later, or earlier when negative, kept within the237// month: 31 January and a month is the last of February.238exp fn add_months(self d: &Date, months: i64) -> Date {239 const count = d.year to i64 * 12 + (d.month to u8 to i64 - 1) + months;240 const year = floor_div(count, 12) to i32;241 const month = month_of(floor_mod(count, 12) + 1);242 return Date { .year = year, .month = month, .day = min(d.day, days_in_month(year, month)) };243}244245exp fn compare(self d: &Date, other: &Date) -> Ordering {246 if (d.year != other.year) {247 return if (d.year < other.year) Ordering::Less else Ordering::Greater;248 }249 const a = d.month to u8 to u32 * 32 + d.day to u32;250 const b = other.month to u8 to u32 * 32 + other.day to u32;251 return if (a < b) Ordering::Less else if (a > b) Ordering::Greater else Ordering::Equal;252}253254// Whether the day comes before the other.255exp fn before(self d: &Date, other: &Date) -> bool => d.compare(&other) is ::Less;256257// Whether the day comes after the other.258exp fn after(self d: &Date, other: &Date) -> bool => d.compare(&other) is ::Greater;259260exp fn is_leap_year(year: i32) -> bool => year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);261262exp fn days_in_month(year: i32, month: Month) -> u8 => match (month) {263 ::February if (is_leap_year(year)) 29 else 28;264 ::April, ::June, ::September, ::November 30;265 else 31;266};267268// The day as ISO 8601 writes it: `2026-10-15`, `-0001-03-01`, `+10000-01-01`.269exp fn format(self d: &Date, out: &var String) {270 if (d.year < 0) {271 out.push('-');272 } else if (d.year > 9999) {273 out.push('+');274 }275 const year = if (d.year < 0) -(d.year to i64) else d.year to i64;276 const month = d.month to u8;277 out.append(&f"{year:04}-{month:02}-{d.day:02}".view());278}279280// A time of day, to the second.281exp type TimeOfDay : Format = struct {282 exp hour: u8,283 exp minute: u8,284 exp second: u8 = 0,285};286287// The time; faults past 23:59.288exp fn TimeOfDay::of(hour: u8, minute: u8) -> TimeOfDay {289 if (hour > 23 || minute > 59) {290 panic "std::time: no such time of day";291 }292 return TimeOfDay { .hour = hour, .minute = minute };293}294295// The seconds since midnight.296exp fn seconds(self t: &TimeOfDay) -> u32 {297 return t.hour to u32 * 3600 + t.minute to u32 * 60 + t.second to u32;298}299300exp fn compare(self t: &TimeOfDay, other: &TimeOfDay) -> Ordering {301 const a = t.seconds();302 const b = other.seconds();303 return if (a < b) Ordering::Less else if (a > b) Ordering::Greater else Ordering::Equal;304}305306// The time on a 24-hour clock: `14:30`, or `14:30:15` with seconds.307exp fn format(self t: &TimeOfDay, out: &var String) {308 out.append(&f"{t.hour:02}:{t.minute:02}".view());309 if (t.second != 0) {310 out.append(&f":{t.second:02}".view());311 }312}313314// Seconds east of UTC in the system's time zone at the moment, in315// nanoseconds since 1970-01-01 UTC as `wall_clock` gives them: 7200 in316// Paris in summer, -18000 in New York in winter, 0 where the system has317// no time zone (WASI).318exp fn local_offset(at: i64) -> i64 {319 const seconds = floor_div(at, 1000000000);320 if (target() == "web-wasm32") {321 return page_offset(seconds);322 }323 return al_sys_local_offset(seconds);324}325326fn month_of(n: i64) -> Month {327 if (Month::from(n to u8) is ::Some |month|) {328 return month;329 }330 panic "std::time: no such month";331}332333fn floor_div(a: i64, b: i64) -> i64 {334 const q = a / b;335 return if (a % b != 0 && (a < 0) != (b < 0)) q - 1 else q;336}337338fn floor_mod(a: i64, b: i64) -> i64 => a - floor_div(a, b) * b;339340/* --- Dates with times, and time zones (alloy-ui's decisions/F12.md, F12e) --- */341342// A date and a time of day, on no zone's clocks in particular.343exp type DateTime : Format = struct {344 exp date: Date,345 exp time: TimeOfDay,346 exp nanosecond: u32 = 0,347};348349exp fn compare(self t: &DateTime, other: &DateTime) -> Ordering {350 const by_date = t.date.compare(&other.date);351 if (!(by_date is ::Equal)) {352 return by_date;353 }354 const by_time = t.time.compare(&other.time);355 if (!(by_time is ::Equal)) {356 return by_time;357 }358 const a = t.nanosecond;359 const b = other.nanosecond;360 return if (a < b) Ordering::Less else if (a > b) Ordering::Greater else Ordering::Equal;361}362363// The date and time as ISO 8601 writes them: `2026-11-20T19:30`,364// `2026-11-20T19:30:05.25`.365exp fn format(self t: &DateTime, out: &var String) {366 out.write(&t.date);367 out.push('T');368 if (t.nanosecond == 0) {369 out.write(&t.time);370 return;371 }372 out.append(&f"{t.time.hour:02}:{t.time.minute:02}:{t.time.second:02}".view());373 write_fraction(t.nanosecond, &var out);374}375376// A local time may be skipped by a change to summer time, or happen twice.377exp type Resolved = enum {378 Exact: i64,379 Skipped: i64, // the moment the clocks jumped over it: 02:30 on a spring night is 03:00380 Twice: [i64 : 2], // the earlier and the later381};382383// A time zone: its name and the offsets from UTC its clocks keep, from384// the platform's database (`Zone::named`) or a TZif file the program385// carries (`Zone::from_tzif`).386//387// ```alloy388// const utc = Zone::utc();389// const moment: i64 = 1795199400000000000; // 2026-11-20 18:30 UTC390// expect_equal(&f"{utc.local(moment)}", &String::from(&"2026-11-20T18:30"));391// expect(utc.moment(&utc.local(moment)) == Resolved::Exact(moment));392// ```393exp type Zone = struct {394 name: String,395 rules: Rules,396};397398// Where a zone's offsets come from: a table read from TZif, or the399// platform asked by name (Windows' ICU, the page's Intl).400type Rules = enum {401 Table: ZoneTable,402 Platform,403};404405// TZif's changes of offset and the POSIX rule after the last.406type ZoneTable = struct {407 moments: Vector<i64>, // in seconds since 1970 UTC408 kinds: Vector<u8>, // the local time type from each moment on409 types: Vector<LocalType>,410 rule: Option<Rule>,411};412413type LocalType = struct {414 offset: i64, // seconds east of UTC415 summer: bool,416};417418// A POSIX TZ rule (`CET-1CEST,M3.5.0,M10.5.0/3`): the standard offset,419// and summer time's between two days of each year.420type Rule = struct {421 standard: i64,422 summer: Option<Summer>,423};424425type Summer = struct {426 offset: i64,427 start: RuleDay,428 start_time: i64, // seconds from the day's midnight, in standard time429 end: RuleDay,430 end_time: i64, // in summer time431};432433type RuleDay = enum {434 Julian: i64, // `Jn`: 1 to 365, 29 February never counted435 Ordinal: i64, // `n`: 0 to 365, counting it436 Week: [u8 : 3], // `Mm.w.d`: month, week (5 the last), weekday (0 Sunday)437};438439exp fn Zone::utc() -> Zone => Zone {440 .name = String::from(&"UTC"),441 .rules = Rules::Table(fixed_table(0))442};443444// The zone the platform's database knows by the name ("Europe/Paris"):445// TZif files in /usr/share/zoneinfo on Linux and macOS, ICU's in446// icu.dll on Windows (10 1903 and later), the page's Intl on the web.447// UTC is known everywhere, WASI knowing nothing else.448exp fn Zone::named(name: &[u8]) -> Option<Zone> {449 if (name == "UTC" || name == "Etc/UTC") {450 return ::Some(Zone { .name = String::from(&name), .rules = Rules::Table(fixed_table(0)) });451 }452 if (!is_zone_name(&name)) {453 return ::None;454 }455 if (target() == "web-wasm32") {456 if (al_time_zone_known(c_pointer::of(&name), name.length() to u32) == 0) {457 return ::None;458 }459 return ::Some(Zone { .name = String::from(&name), .rules = Rules::Platform });460 }461 if (target() == "windows-x86_64") {462 const terminated = move zone_terminated(&name);463 if (al_sys_zone_known(&terminated) == 0) {464 return ::None;465 }466 return ::Some(Zone { .name = String::from(&name), .rules = Rules::Platform });467 }468 if (target() == "wasi-wasm32") {469 return ::None;470 }471 if (read_file(&f"/usr/share/zoneinfo/{name}".view()) is ::Some |&bytes|) {472 return Zone::from_tzif(&name, &bytes);473 }474 return ::None;475}476477// The system's zone, as local_offset follows it: `TZ` (a name, a path478// or a POSIX rule), else /etc/localtime and the name its link gives479// (Linux, macOS); Windows' zone by its IANA name; the page's on the web;480// UTC when there is none, as under WASI.481exp fn Zone::system() -> Zone {482 if (target() == "wasi-wasm32") {483 return Zone::utc();484 }485 var buffer: [u8 : 256] = [0 : 256];486 var configured = String::empty();487 if (target() == "web-wasm32") {488 const length = al_time_page_zone(c_pointer::of(&buffer[..]), 256) to u64;489 if (length <= 256) {490 configured = String::from(&buffer[..length]);491 }492 } else {493 const length = al_sys_zone_name(&var buffer, 256);494 if (length >= 0 && length as u64 <= 256) {495 configured = String::from(&buffer[..length as u64]);496 }497 }498 var text = &configured.view();499 if (text.starts_with(&":")) {500 text = &text[1..];501 }502 if (text.length() == 0) {503 return Zone::utc();504 }505 if (text[0] == '/' || text[0] == '.') {506 const path = if (text[0] == '.') f"/etc/{text}" else String::from(&text);507 var name = if (508 path.view().find(&"zoneinfo/", 0) is ::Some |at|509 ) String::from(&path.view()[at + 9..]) else String::from(&"localtime");510 if (path.view() == "/etc/localtime") {511 name = String::from(&"localtime");512 }513 if (514 read_file(&path.view()) is ::Some |&bytes|515 && Zone::from_tzif(&name.view(), &bytes) is ::Some |move zone|516 ) {517 return move zone;518 }519 return Zone::utc();520 }521 if (Zone::named(&text) is ::Some |move zone|) {522 return move zone;523 }524 if (target() != "windows-x86_64" && read_rule(&text) is ::Some |move rule|) {525 var table = fixed_table(rule.standard);526 table.rule = ::Some(move rule);527 return Zone { .name = String::from(&text), .rules = Rules::Table(move table) };528 }529 return Zone::utc();530}531532// The zone a TZif file describes (RFC 8536, versions 1 to 4), named as533// given: a zone the program carries (`#read_file`), the only kind WASI534// has. Leap seconds are not counted.535exp fn Zone::from_tzif(name: &[u8], bytes: &[u8]) -> Option<Zone> {536 if (read_tzif(&bytes) is ::Some |move table|) {537 return ::Some(Zone { .name = String::from(&name), .rules = Rules::Table(move table) });538 }539 return ::None;540}541542exp fn name(self zone: &Zone) -> &[u8] => &zone.name.view();543544// Seconds east of UTC on the zone's clocks at the moment (nanoseconds545// since 1970 UTC, as `wall_clock` gives).546exp fn offset_at(547 self zone: &Zone,548 moment: i64549) -> i64 => zone.local_type(floor_div(moment, 1000000000)).offset;550551// Whether the zone keeps summer time at the moment (std::locale's zone552// names).553pub fn summer_at(554 self zone: &Zone,555 moment: i64556) -> bool => zone.local_type(floor_div(moment, 1000000000)).summer;557558// The moment on the zone's clocks.559exp fn local(self zone: &Zone, moment: i64) -> DateTime {560 const seconds = floor_div(moment, 1000000000) + zone.offset_at(moment);561 return DateTime {562 .date = Date::from_days(floor_div(seconds, 86400)),563 .time = time_of_seconds(floor_mod(seconds, 86400)),564 .nanosecond = floor_mod(moment, 1000000000) to u32565 };566}567568// The moment the zone's clocks show the local time: exact, skipped by a569// change of offset (the moment of the change), or shown twice.570exp fn moment(self zone: &Zone, local: &DateTime) -> Resolved {571 const wall = local.date.days() * 86400 + local.time.seconds() to i64;572 const nanosecond = local.nanosecond to i64;573 const before = zone.local_type(wall - 86400).offset;574 const after = zone.local_type(wall + 86400).offset;575 const early = wall - max(before, after);576 const late = wall - min(before, after);577 const early_holds = zone.local_type(early).offset == max(before, after);578 const late_holds = zone.local_type(late).offset == min(before, after);579 if (early_holds && late_holds && early != late) {580 return Resolved::Twice([early * 1000000000 + nanosecond, late * 1000000000 + nanosecond]);581 }582 if (early_holds) {583 return Resolved::Exact(early * 1000000000 + nanosecond);584 }585 if (late_holds) {586 return Resolved::Exact(late * 1000000000 + nanosecond);587 }588 // the first second after `early` on another offset589 const from = zone.local_type(early).offset;590 var low = early;591 var high = late;592 while (high - low > 1) {593 const middle = low + (high - low) / 2;594 if (zone.local_type(middle).offset == from) {595 low = middle;596 } else {597 high = middle;598 }599 }600 return Resolved::Skipped(high * 1000000000);601}602603fn local_type(self zone: &Zone, seconds: i64) -> LocalType {604 if (zone.rules is ::Table |&table|) {605 return table.type_at(seconds);606 }607 var out: [i64 : 2] = [0, 0];608 if (target() == "web-wasm32") {609 al_time_zone_offsets(610 c_pointer::of(&zone.name.view()),611 zone.name.length() to u32,612 seconds,613 c_pointer::of(&out[..])614 );615 } else if (target() == "windows-x86_64") {616 const terminated = move zone_terminated(&zone.name.view());617 al_sys_zone_offsets(&terminated, seconds, &var out);618 }619 return LocalType { .offset = out[0], .summer = out[1] != 0 };620}621622fn fixed_table(offset: i64) -> ZoneTable => ZoneTable {623 .moments = Vector<i64>::empty(),624 .kinds = Vector<u8>::empty(),625 .types = Vector<LocalType>::from(&[LocalType { .offset = offset, .summer = false }]),626 .rule = ::None627};628629fn type_at(self table: &ZoneTable, seconds: i64) -> LocalType {630 const count = table.moments.length();631 if (count == 0 || seconds >= table.moments.get(count - 1)) {632 if (table.rule is ::Some |&rule|) {633 return rule.type_at(seconds);634 }635 }636 if (count == 0 || seconds < table.moments.get(0)) {637 return table.types.get(0);638 }639 // the last change at or before the moment640 var low: u64 = 0;641 var high = count;642 while (high - low > 1) {643 const middle = low + (high - low) / 2;644 if (table.moments.get(middle) <= seconds) {645 low = middle;646 } else {647 high = middle;648 }649 }650 return table.types.get(table.kinds.get(low) to u64);651}652653fn type_at(self rule: &Rule, seconds: i64) -> LocalType {654 if (rule.summer is ::Some |&summer|) {655 const year = Date::from_days(floor_div(seconds + rule.standard, 86400)).year;656 const start = summer.start.day_in(year) * 86400 + summer.start_time - rule.standard;657 const end = summer.end.day_in(year) * 86400 + summer.end_time - summer.offset;658 const inside = if (start <= end) seconds >= start659 && seconds < end else seconds >= start660 || seconds < end;661 if (inside) {662 return LocalType { .offset = summer.offset, .summer = true };663 }664 }665 return LocalType { .offset = rule.standard, .summer = false };666}667668// The days since 1970 of the rule's day in the year.669fn day_in(self day: &RuleDay, year: i32) -> i64 {670 const first = Date { .year = year, .month = Month::January, .day = 1 } .days();671 return match (day) {672 ::Julian |n| first + n - 1 + if (is_leap_year(year) && n >= 60) 1 else 0;673 ::Ordinal |n| first + n;674 ::Week |w| {675 const month = month_of(w[0] to i64);676 const start = Date { .year = year, .month = month, .day = 1 };677 const sunday_first = start.weekday() to u8 % 7;678 var d = 1 + (w[2] + 7 - sunday_first) % 7 + (w[1] - 1) * 7;679 while (d > days_in_month(year, month)) {680 d -= 7;681 }682 yield start.days() + d to i64 - 1;683 }684 };685}686687// What a zone name may hold: letters, digits and `/_+-.`, no `..` and688// not from the root.689fn is_zone_name(name: &[u8]) -> bool {690 if (name.length() == 0 || name.length() > 128 || name[0] == '/' || name.contains(&"..")) {691 return false;692 }693 for (name) |c| {694 const fits = is_ascii_letter(c)695 || is_ascii_digit(c)696 || c == '/'697 || c == '_'698 || c == '+'699 || c == '-'700 || c == '.';701 if (!fits) {702 return false;703 }704 }705 return true;706}707708fn zone_terminated(text: &[u8]) -> *[u8] {709 var out: *var [u8] = new [0 : text.length() + 1];710 out[..text.length()] = text;711 return move out;712}713714/* TZif (RFC 8536) */715716type Counts = struct {717 utc: u64,718 standard: u64,719 leaps: u64,720 times: u64,721 types: u64,722 characters: u64,723};724725fn counts_at(bytes: &[u8], at: u64) -> Counts => Counts {726 .utc = big_endian(&bytes, at + 20, 4),727 .standard = big_endian(&bytes, at + 24, 4),728 .leaps = big_endian(&bytes, at + 28, 4),729 .times = big_endian(&bytes, at + 32, 4),730 .types = big_endian(&bytes, at + 36, 4),731 .characters = big_endian(&bytes, at + 40, 4)732};733734// The bytes of the data block after the header, with times of the width.735fn block(self c: &Counts, width: u64) -> u64 {736 return c.times * (737 width + 1738 ) + c.types * 6 + c.characters + c.leaps * (width + 4) + c.standard + c.utc;739}740741fn read_tzif(bytes: &[u8]) -> Option<ZoneTable> {742 if (bytes.length() < 44 || !bytes.starts_with(&"TZif")) {743 return ::None;744 }745 const version = bytes[4];746 var counts = counts_at(&bytes, 0);747 var at: u64 = 44;748 var width: u64 = 4;749 if (version >= '2') {750 at += counts.block(4);751 if (at + 44 > bytes.length() || !bytes[at..].starts_with(&"TZif")) {752 return ::None;753 }754 counts = counts_at(&bytes, at);755 at += 44;756 width = 8;757 }758 if (counts.types == 0 || at + counts.block(width) > bytes.length()) {759 return ::None;760 }761 var table = ZoneTable {762 .moments = Vector<i64>::with_capacity(counts.times),763 .kinds = Vector<u8>::with_capacity(counts.times),764 .types = Vector<LocalType>::with_capacity(counts.types),765 .rule = ::None766 };767 for ([..counts.times]) |k| {768 const n = big_endian(&bytes, at + k * width, width);769 table.moments.push(if (width == 4) n to u32 as i32 to i64 else n as i64);770 }771 at += counts.times * width;772 for ([..counts.times]) |k| {773 if (bytes[at + k] to u64 >= counts.types) {774 return ::None;775 }776 table.kinds.push(bytes[at + k]);777 }778 at += counts.times;779 for ([..counts.types]) |k| {780 const offset = big_endian(&bytes, at + k * 6, 4) to u32 as i32 to i64;781 table.types.push(LocalType { .offset = offset, .summer = bytes[at + k * 6 + 4] != 0 });782 }783 at += counts.types * 6 + counts.characters + counts.leaps * (784 width + 4785 ) + counts.standard + counts.utc;786 // the footer's POSIX rule, for the moments after the last change787 if (version >= '2' && at < bytes.length() && bytes[at] == '\n') {788 if (bytes.find_byte('\n', at + 1) is ::Some |end| && end > at + 1) {789 table.rule = read_rule(&bytes[at + 1..end]);790 }791 }792 return ::Some(move table);793}794795fn big_endian(bytes: &[u8], at: u64, width: u64) -> u64 {796 var n: u64 = 0;797 for ([at..at + width]) |k| {798 n = n << 8 | bytes[k] to u64;799 }800 return n;801}802803/* POSIX TZ rules */804805fn read_rule(text: &[u8]) -> Option<Rule> {806 var at: u64 = 0;807 if (!skip_rule_name(&text, &var at)) {808 return ::None;809 }810 const west = if (rule_time(&text, &var at) is ::Some |t|) t else {811 return ::None;812 };813 var rule = Rule { .standard = -west, .summer = ::None };814 if (at == text.length()) {815 return ::Some(rule);816 }817 if (!skip_rule_name(&text, &var at)) {818 return ::None;819 }820 var summer = Summer {821 .offset = rule.standard + 3600,822 .start = RuleDay::Week([3, 2, 0]),823 .start_time = 7200,824 .end = RuleDay::Week([11, 1, 0]),825 .end_time = 7200826 };827 if (at < text.length() && text[at] != ',') {828 summer.offset = if (rule_time(&text, &var at) is ::Some |t|) -t else {829 return ::None;830 };831 }832 if (at < text.length()) {833 if (text[at] != ',') {834 return ::None;835 }836 at += 1;837 summer.start = if (rule_day(&text, &var at) is ::Some |d|) d else {838 return ::None;839 };840 if (at < text.length() && text[at] == '/') {841 at += 1;842 summer.start_time = if (rule_time(&text, &var at) is ::Some |t|) t else {843 return ::None;844 };845 }846 if (at >= text.length() || text[at] != ',') {847 return ::None;848 }849 at += 1;850 summer.end = if (rule_day(&text, &var at) is ::Some |d|) d else {851 return ::None;852 };853 if (at < text.length() && text[at] == '/') {854 at += 1;855 summer.end_time = if (rule_time(&text, &var at) is ::Some |t|) t else {856 return ::None;857 };858 }859 }860 if (at != text.length()) {861 return ::None;862 }863 rule.summer = ::Some(summer);864 return ::Some(rule);865}866867// A zone abbreviation, three letters or more or `<+0330>`.868fn skip_rule_name(text: &[u8], at: &var u64) -> bool {869 if (at < text.length() && text[at] == '<') {870 if (text.find_byte('>', at) is ::Some |end|) {871 const named = end > at + 1;872 at = end + 1;873 return named;874 }875 return false;876 }877 const start = at;878 while (at < text.length() && is_ascii_letter(text[at])) {879 at += 1;880 }881 return at - start >= 3;882}883884// `[+-]hh[:mm[:ss]]`, hours up to 167, in seconds.885fn rule_time(text: &[u8], at: &var u64) -> Option<i64> {886 var sign: i64 = 1;887 if (at < text.length() && (text[at] == '+' || text[at] == '-')) {888 sign = if (text[at] == '-') -1 else 1;889 at += 1;890 }891 var seconds = if (read_number(&text, &var at, 3) is ::Some |h| && h <= 167) h * 3600 else {892 return ::None;893 };894 var scale: i64 = 60;895 while (scale >= 1 && at < text.length() && text[at] == ':') {896 at += 1;897 seconds += if (read_number(&text, &var at, 2) is ::Some |n| && n <= 59) n * scale else {898 return ::None;899 };900 scale /= 60;901 }902 return ::Some(sign * seconds);903}904905fn rule_day(text: &[u8], at: &var u64) -> Option<RuleDay> {906 if (at < text.length() && text[at] == 'J') {907 at += 1;908 if (read_number(&text, &var at, 3) is ::Some |n| && n >= 1 && n <= 365) {909 return ::Some(RuleDay::Julian(n));910 }911 return ::None;912 }913 if (at < text.length() && text[at] == 'M') {914 at += 1;915 var parts: [u8 : 3] = [0, 0, 0];916 for ([..3]) |k| {917 if (k > 0) {918 if (at >= text.length() || text[at] != '.') {919 return ::None;920 }921 at += 1;922 }923 parts[k] = if (read_number(&text, &var at, 2) is ::Some |n| && n <= 12) n to u8 else {924 return ::None;925 };926 }927 if (parts[0] < 1 || parts[1] < 1 || parts[1] > 5 || parts[2] > 6) {928 return ::None;929 }930 return ::Some(RuleDay::Week(parts));931 }932 if (read_number(&text, &var at, 3) is ::Some |n| && n <= 365) {933 return ::Some(RuleDay::Ordinal(n));934 }935 return ::None;936}937938// One to `most` decimal digits.939fn read_number(text: &[u8], at: &var u64, most: u64) -> Option<i64> {940 var n: i64 = 0;941 var count: u64 = 0;942 while (count < most && at < text.length() && is_ascii_digit(text[at])) {943 n = n * 10 + (text[at] - '0') to i64;944 at += 1;945 count += 1;946 }947 return if (count == 0) ::None else ::Some(n);948}949950/* --- ISO 8601, RFC 3339 and HTTP dates --- */951952// The day `2026-11-20` names, with a sign and five digits or more for953// years past 9999 or before 0 as `format` writes them (`-0001-03-01`).954//955// ```alloy956// expect(Date::parse_iso(&"2026-11-20") == ::Some(Date::of(2026, Month::November, 20)));957// expect(Date::parse_iso(&"2026-02-30") is ::None);958// ```959exp fn Date::parse_iso(text: &[u8]) -> Option<Date> {960 var at: u64 = 0;961 if (iso_date(&text, &var at) is ::Some |d| && at == text.length()) {962 return ::Some(d);963 }964 return ::None;965}966967// The date and time `2026-11-20T19:30` names, seconds and their fraction968// optional (`19:30:05.25`), with no zone.969exp fn DateTime::parse_iso(text: &[u8]) -> Option<DateTime> {970 var at: u64 = 0;971 const date = if (iso_date(&text, &var at) is ::Some |d|) d else {972 return ::None;973 };974 if (at >= text.length() || (text[at] != 'T' && text[at] != 't')) {975 return ::None;976 }977 at += 1;978 if (iso_time(&text, &var at, false) is ::Some |t| && at == text.length()) {979 return ::Some(DateTime { .date = date, .time = t.time, .nanosecond = t.nanosecond });980 }981 return ::None;982}983984// The duration ISO 8601 writes `PT1H30M`: weeks (`P2W`), or days and a985// time of hours, minutes and seconds, the last of them with a fraction986// (`PT0.5S`). Years and months, which have no fixed length, are refused.987//988// ```alloy989// expect(Duration::parse_iso(&"PT1H30M") == ::Some(Duration::from_seconds(5400.0)));990// expect(Duration::parse_iso(&"P1DT0.25S") == ::Some(Duration::from_seconds(86400.25)));991// expect(Duration::parse_iso(&"P1M") is ::None);992// ```993exp fn Duration::parse_iso(text: &[u8]) -> Option<Duration> {994 if (text.length() < 2 || text[0] != 'P') {995 return ::None;996 }997 var at: u64 = 1;998 var total: u64 = 0;999 var in_time = false;1000 var units: u64 = 0;1001 var last_scale: u64 = 0xFFFFFFFFFFFFFFFF;1002 var fractional = false;1003 while (at < text.length()) {1004 if (text[at] == 'T') {1005 if (in_time) {1006 return ::None;1007 }1008 in_time = true;1009 at += 1;1010 if (at == text.length()) {1011 return ::None;1012 }1013 continue;1014 }1015 if (fractional) {1016 return ::None; // only the last unit has a fraction1017 }1018 var whole: u64 = 0;1019 var digits: u64 = 0;1020 while (at < text.length() && is_ascii_digit(text[at])) {1021 if (digits >= 12) {1022 return ::None;1023 }1024 whole = whole * 10 + (text[at] - '0') to u64;1025 at += 1;1026 digits += 1;1027 }1028 var fraction: u64 = 0; // nanoseconds of a unit, in billionths1029 if (at < text.length() && (text[at] == '.' || text[at] == ',')) {1030 at += 1;1031 var scale: u64 = 100000000;1032 var fraction_digits: u64 = 0;1033 while (at < text.length() && is_ascii_digit(text[at])) {1034 fraction += (text[at] - '0') to u64 * scale;1035 scale /= 10;1036 at += 1;1037 fraction_digits += 1;1038 }1039 if (fraction_digits == 0) {1040 return ::None;1041 }1042 fractional = true;1043 }1044 if (digits == 0 || at >= text.length()) {1045 return ::None;1046 }1047 const unit = text[at];1048 at += 1;1049 const scale: u64 = if (1050 !in_time1051 && unit == 'W'1052 ) 604800 else if (1053 !in_time1054 && unit == 'D'1055 ) 86400 else if (1056 in_time1057 && unit == 'H'1058 ) 3600 else if (in_time && unit == 'M') 60 else if (in_time && unit == 'S') 1 else {1059 return ::None;1060 };1061 if (scale >= last_scale) {1062 return ::None;1063 }1064 last_scale = scale;1065 total += whole * scale * 1000000000 + fraction / 1000000000 * scale * 1000000000 + fraction % 1000000000 * scale;1066 units += 1;1067 }1068 if (units == 0) {1069 return ::None;1070 }1071 return ::Some(Duration { .nanoseconds = total });1072}10731074// The moment an RFC 3339 time names: `2026-11-20T19:30:00+01:00`,1075// `2026-11-20T18:30:00.5Z`. A leap second (`23:59:60`) is the second1076// after it.1077//1078// ```alloy1079// const moment: i64 = 1795199400000000000;1080// expect(parse_rfc3339(&"2026-11-20T19:30:00+01:00") == ::Some(moment));1081// var text = String::empty();1082// format_rfc3339(moment, 3600, &var text);1083// expect_equal(&text, &String::from(&"2026-11-20T19:30:00+01:00"));1084// ```1085exp fn parse_rfc3339(text: &[u8]) -> Option<i64> {1086 var at: u64 = 0;1087 const date = if (1088 iso_date(&text, &var at) is ::Some |d|1089 && d.year >= 01090 && d.year <= 99991091 ) d else {1092 return ::None;1093 };1094 if (at >= text.length() || (text[at] != 'T' && text[at] != 't')) {1095 return ::None;1096 }1097 at += 1;1098 const time = if (iso_time(&text, &var at, true) is ::Some |t|) t else {1099 return ::None;1100 };1101 if (at >= text.length()) {1102 return ::None;1103 }1104 var offset: i64 = 0;1105 if (text[at] == 'Z' || text[at] == 'z') {1106 at += 1;1107 } else if (text[at] == '+' || text[at] == '-') {1108 const sign: i64 = if (text[at] == '-') -1 else 1;1109 at += 1;1110 const hours = if (exact_digits(&text, &var at, 2) is ::Some |h| && h <= 23) h else {1111 return ::None;1112 };1113 if (at >= text.length() || text[at] != ':') {1114 return ::None;1115 }1116 at += 1;1117 const minutes = if (exact_digits(&text, &var at, 2) is ::Some |m| && m <= 59) m else {1118 return ::None;1119 };1120 offset = sign * (hours * 3600 + minutes * 60);1121 } else {1122 return ::None;1123 }1124 if (at != text.length()) {1125 return ::None;1126 }1127 return moment_of(date.days() * 86400 + time.seconds - offset, time.nanosecond to i64);1128}11291130// Writes the moment as RFC 3339 does on clocks at the offset (seconds1131// east, whole minutes of it): `2026-11-20T19:30:00+01:00`, `Z` for UTC,1132// a fraction only when there is one.1133exp fn format_rfc3339(moment: i64, offset: i64, out: &var String) {1134 const minutes = floor_div(offset, 60);1135 const seconds = floor_div(moment, 1000000000) + minutes * 60;1136 const date = Date::from_days(floor_div(seconds, 86400));1137 const time = time_of_seconds(floor_mod(seconds, 86400));1138 const nanosecond = floor_mod(moment, 1000000000) to u32;1139 out.write(&date);1140 out.append(&f"T{time.hour:02}:{time.minute:02}:{time.second:02}".view());1141 write_fraction(nanosecond, &var out);1142 if (minutes == 0) {1143 out.push('Z');1144 return;1145 }1146 out.push(if (minutes < 0) '-' else '+');1147 const size = if (minutes < 0) -minutes else minutes;1148 out.append(&f"{size / 60:02}:{size % 60:02}".view());1149}11501151// The moment an HTTP date names (RFC 9110, 5.6.7), as `Retry-After`,1152// `Last-Modified` and `Expires` carry them: `Fri, 20 Nov 2026 18:30:001153// GMT`, or the obsolete `Friday, 20-Nov-26 18:30:00 GMT` and `Fri Nov 201154// 18:30:00 2026`.1155//1156// ```alloy1157// const moment: i64 = 1795199400000000000;1158// expect(parse_http_date(&"Fri, 20 Nov 2026 18:30:00 GMT") == ::Some(moment));1159// expect(parse_http_date(&"Fri Nov 20 18:30:00 2026") == ::Some(moment));1160// ```1161exp fn parse_http_date(text: &[u8]) -> Option<i64> {1162 var at: u64 = 0;1163 while (at < text.length() && is_ascii_letter(text[at])) {1164 at += 1;1165 }1166 const day_name = &text[..at];1167 var day: i64 = 0;1168 var month_number: i64 = 0;1169 var year: i64 = 0;1170 const asctime = !(at < text.length() && text[at] == ',');1171 if (!asctime) {1172 at += 1;1173 if (!skip_byte(&text, &var at, ' ')) {1174 return ::None;1175 }1176 day = if (exact_digits(&text, &var at, 2) is ::Some |d|) d else {1177 return ::None;1178 };1179 if (at < text.length() && text[at] == '-' && http_weekday(&day_name, true)) {1180 // RFC 850: `20-Nov-26`1181 at += 1;1182 month_number = http_month(&text, &var at);1183 if (!skip_byte(&text, &var at, '-')) {1184 return ::None;1185 }1186 const short = if (exact_digits(&text, &var at, 2) is ::Some |y|) y else {1187 return ::None;1188 };1189 // the most recent year with those digits that is not more1190 // than 50 years from now1191 const now = Date::from_days(floor_div(1192 floor_div(wall_clock(), 1000000000),1193 864001194 )).year to i64;1195 year = now - floor_mod(now, 100) + short;1196 if (year > now + 50) {1197 year -= 100;1198 }1199 } else {1200 if (!http_weekday(&day_name, false) || !skip_byte(&text, &var at, ' ')) {1201 return ::None;1202 }1203 month_number = http_month(&text, &var at);1204 if (!skip_byte(&text, &var at, ' ')) {1205 return ::None;1206 }1207 year = if (exact_digits(&text, &var at, 4) is ::Some |y|) y else {1208 return ::None;1209 };1210 }1211 if (!skip_byte(&text, &var at, ' ')) {1212 return ::None;1213 }1214 } else {1215 // asctime: `Fri Nov 20 18:30:00 2026`, a day below 10 after a space1216 if (!http_weekday(&day_name, false) || !skip_byte(&text, &var at, ' ')) {1217 return ::None;1218 }1219 month_number = http_month(&text, &var at);1220 if (!skip_byte(&text, &var at, ' ')) {1221 return ::None;1222 }1223 if (at < text.length() && text[at] == ' ') {1224 at += 1;1225 day = if (exact_digits(&text, &var at, 1) is ::Some |d|) d else {1226 return ::None;1227 };1228 } else {1229 day = if (exact_digits(&text, &var at, 2) is ::Some |d|) d else {1230 return ::None;1231 };1232 }1233 if (!skip_byte(&text, &var at, ' ')) {1234 return ::None;1235 }1236 }1237 var parts: [i64 : 3] = [0, 0, 0];1238 for ([..3]) |k| {1239 if (k > 0 && !skip_byte(&text, &var at, ':')) {1240 return ::None;1241 }1242 parts[k] = if (exact_digits(&text, &var at, 2) is ::Some |n|) n else {1243 return ::None;1244 };1245 }1246 if (asctime) {1247 if (!skip_byte(&text, &var at, ' ')) {1248 return ::None;1249 }1250 year = if (exact_digits(&text, &var at, 4) is ::Some |y|) y else {1251 return ::None;1252 };1253 } else if (!(text[at..] == " GMT")) {1254 return ::None;1255 } else {1256 at += 4;1257 }1258 if (1259 at != text.length()1260 || month_number == 01261 || parts[0] > 231262 || parts[1] > 591263 || parts[2] > 601264 ) {1265 return ::None;1266 }1267 const month = month_of(month_number);1268 const date = if (1269 Date::try_of(year to i32, month, day to u8) is ::Some |d|1270 && day <= 311271 ) d else {1272 return ::None;1273 };1274 return moment_of(date.days() * 86400 + parts[0] * 3600 + parts[1] * 60 + parts[2], 0);1275}12761277const HTTP_DAYS: [&[u8] : 7] = [&"Mon", &"Tue", &"Wed", &"Thu", &"Fri", &"Sat", &"Sun"];1278const HTTP_LONG_DAYS: [&[u8] : 7] = [1279 &"Monday",1280 &"Tuesday",1281 &"Wednesday",1282 &"Thursday",1283 &"Friday",1284 &"Saturday",1285 &"Sunday"1286];1287const HTTP_MONTHS: [&[u8] : 12] = [1288 &"Jan",1289 &"Feb",1290 &"Mar",1291 &"Apr",1292 &"May",1293 &"Jun",1294 &"Jul",1295 &"Aug",1296 &"Sep",1297 &"Oct",1298 &"Nov",1299 &"Dec"1300];13011302fn http_weekday(name: &[u8], long: bool) -> bool {1303 const names = if (long) &HTTP_LONG_DAYS else &HTTP_DAYS;1304 for ([..7]) |k| {1305 if (name == names[k]) {1306 return true;1307 }1308 }1309 return false;1310}13111312// The month's number, 0 when the three letters are not one.1313fn http_month(text: &[u8], at: &var u64) -> i64 {1314 if (at + 3 > text.length()) {1315 return 0;1316 }1317 for ([..12]) |k| {1318 if (text[at..at + 3] == HTTP_MONTHS[k]) {1319 at += 3;1320 return k to i64 + 1;1321 }1322 }1323 return 0;1324}13251326fn skip_byte(text: &[u8], at: &var u64, byte: u8) -> bool {1327 if (at < text.length() && text[at] == byte) {1328 at += 1;1329 return true;1330 }1331 return false;1332}13331334// Exactly `count` decimal digits.1335fn exact_digits(text: &[u8], at: &var u64, count: u64) -> Option<i64> {1336 if (at + count > text.length()) {1337 return ::None;1338 }1339 var n: i64 = 0;1340 for ([at..at + count]) |k| {1341 if (!is_ascii_digit(text[k])) {1342 return ::None;1343 }1344 n = n * 10 + (text[k] - '0') to i64;1345 }1346 at += count;1347 return ::Some(n);1348}13491350// `YYYY-MM-DD`, or `±YYYYY-MM-DD` with the sign and five digits or more.1351fn iso_date(text: &[u8], at: &var u64) -> Option<Date> {1352 var sign: i64 = 1;1353 var signed = false;1354 if (at < text.length() && (text[at] == '+' || text[at] == '-')) {1355 sign = if (text[at] == '-') -1 else 1;1356 signed = true;1357 at += 1;1358 }1359 var year: i64 = 0;1360 var digits: u64 = 0;1361 while (at < text.length() && is_ascii_digit(text[at]) && digits < 9) {1362 year = year * 10 + (text[at] - '0') to i64;1363 at += 1;1364 digits += 1;1365 }1366 if (digits < 4 || (digits > 4 && !signed)) {1367 return ::None;1368 }1369 if (!skip_byte(&text, &var at, '-')) {1370 return ::None;1371 }1372 const month = if (exact_digits(&text, &var at, 2) is ::Some |m| && m >= 1 && m <= 12) m else {1373 return ::None;1374 };1375 if (!skip_byte(&text, &var at, '-')) {1376 return ::None;1377 }1378 const day = if (exact_digits(&text, &var at, 2) is ::Some |d| && d >= 1 && d <= 31) d else {1379 return ::None;1380 };1381 return Date::try_of((sign * year) to i32, month_of(month), day to u8);1382}13831384type ReadTime = struct {1385 time: TimeOfDay,1386 seconds: i64, // from midnight, a leap second counted as the next1387 nanosecond: u32,1388};13891390// `hh:mm[:ss[.fraction]]`, seconds required by RFC 3339, which allows a1391// leap second.1392fn iso_time(text: &[u8], at: &var u64, rfc3339: bool) -> Option<ReadTime> {1393 const hour = if (exact_digits(&text, &var at, 2) is ::Some |h| && h <= 23) h else {1394 return ::None;1395 };1396 if (!skip_byte(&text, &var at, ':')) {1397 return ::None;1398 }1399 const minute = if (exact_digits(&text, &var at, 2) is ::Some |m| && m <= 59) m else {1400 return ::None;1401 };1402 var second: i64 = 0;1403 var nanosecond: u32 = 0;1404 if (skip_byte(&text, &var at, ':')) {1405 second = if (1406 exact_digits(&text, &var at, 2) is ::Some |s|1407 && s <= (if (rfc3339) 60 else 59)1408 ) s else {1409 return ::None;1410 };1411 if (at < text.length() && (text[at] == '.' || (text[at] == ',' && !rfc3339))) {1412 at += 1;1413 var scale: u32 = 100000000;1414 var digits: u64 = 0;1415 while (at < text.length() && is_ascii_digit(text[at])) {1416 nanosecond += (text[at] - '0') to u32 * scale;1417 scale /= 10;1418 at += 1;1419 digits += 1;1420 }1421 if (digits == 0) {1422 return ::None;1423 }1424 }1425 } else if (rfc3339) {1426 return ::None;1427 }1428 const time = TimeOfDay {1429 .hour = hour to u8,1430 .minute = minute to u8,1431 .second = min(second, 59) to u81432 };1433 return ::Some(ReadTime {1434 .time = time,1435 .seconds = hour * 3600 + minute * 60 + second,1436 .nanosecond = nanosecond1437 });1438}14391440// `.25` for a quarter second: the fraction's digits, trailing zeros left1441// out; nothing for none.1442fn write_fraction(nanosecond: u32, out: &var String) {1443 if (nanosecond == 0) {1444 return;1445 }1446 out.append(&f".{nanosecond:09}".view());1447 while (out.view()[out.length() - 1] == '0') {1448 out.truncate(out.length() - 1);1449 }1450}14511452// The moment in nanoseconds, None past what an i64 holds (1677 to 2262).1453fn moment_of(seconds: i64, nanosecond: i64) -> Option<i64> {1454 if (seconds < -9223372035 || seconds > 9223372035) {1455 return ::None;1456 }1457 return ::Some(seconds * 1000000000 + nanosecond);1458}14591460fn time_of_seconds(seconds: i64) -> TimeOfDay => TimeOfDay {1461 .hour = (seconds / 3600) to u8,1462 .minute = (seconds / 60 % 60) to u8,1463 .second = (seconds % 60) to u81464};14651466fn is_ascii_digit(c: u8) -> bool => c >= '0' && c <= '9';14671468fn is_ascii_letter(c: u8) -> bool => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');14691470/* --- F12e as built --- */14711472// **F12e as built** (2026-10-16; alloy-ui's decisions/F12.md, "Dates in the1473// world", question 10A):1474// - `DateTime` (written in ISO 8601), `Resolved` and `Zone` as designed;1475// `summer_at` says whether a moment is in summer time. A zone holds1476// its name and either a table of transitions with the POSIX rule after1477// them (`ZoneTable`) or the platform's answer per moment.1478// - The database: TZif versions 1 to 4 read from `/usr/share/zoneinfo`1479// on Linux and macOS, the footer's POSIX `TZ` rule (`M`, `J` and day1480// forms, quoted names) for moments after the last transition; ICU in1481// `icu.dll` on Windows through `al_sys_zone_known` and1482// `al_sys_zone_offsets` (`ucal_open`, `ucal_setMillis`, `ucal_get` of1483// the zone and summer offsets), None for every name when it is missing;1484// on the web `time.web.js` asks `Intl.DateTimeFormat` with1485// `timeZoneName: "longOffset"`, summer time being more than the1486// smaller of January's and July's offsets; under WASI only `UTC`,1487// `Etc/UTC` and `from_tzif`. The interpreter reads the files as native1488// code does.1489// - `Zone::system()`: `TZ` (a name, a path after `:`, or a POSIX rule),1490// else `/etc/localtime`'s link (Linux, macOS), ICU's canonical name for1491// `GetDynamicTimeZoneInformation`'s zone on Windows, the page's zone on1492// the web, UTC under WASI or when nothing is known.1493// - `moment` finds a local time's moment from the offsets a day either1494// side: one fitting is Exact, two Twice, none Skipped at the change,1495// found by halving.1496// - Texts: `Date::parse_iso`, `DateTime::parse_iso` (seconds and a1497// fraction optional), `Duration::parse_iso` (weeks, days, hours,1498// minutes and seconds; years and months refused, having no fixed1499// length), `parse_rfc3339` (`Z` or an offset, `T` and `Z` in either1500// case, years 0 to 9999, a leap second taken as the next second), `format_rfc3339` (the1501// offset rounded down to minutes, `Z` for none, the fraction trimmed),1502// `parse_http_date` (IMF-fixdate, RFC 850 with its year within 50 of1503// now, asctime). A moment past what i64 nanoseconds hold is None.1504// - Tests: `tests/driver/zones.sh` checks every zone of the distrobox's1505// zoneinfo, 548 of them, against `zdump -V` from 1900 to 2100 (130,3081506// transitions and the moments either side); `tests/run/time_texts`1507// the valid and invalid texts; `tests/driver/time_zone.sh`1508// `Zone::system` under each form of `TZ`, natively, interpreted, under1509// wasmtime and in node. Windows' ICU is built and runs by hand.1510// - Size: hello world reaching `Zone::system`, `local` and `format` is1511// 34 KB larger natively, 33 KB of wasm (the TZif and rule readers).