#! @file zone.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains `zone`, a time zone: how far its clocks are from UTC, and when that #! changed. A zone is UTC, a fixed offset, or one of the system's database, #! which `zone::named` reads, as `zone::local` reads the system's own. #! #! The database is a directory of TZif files, as RFC 8536 describes them: the #! moments a zone's clocks changed, each with the offset kept from then on and #! what the zone calls it, as "CST" and "CDT". A file ends in a rule, as #! `CST6CDT,M3.2.0,M11.1.0`, which says how the clocks change every year after #! the last moment it lists. A zone holds both, so it answers for any moment. import std::io; module std::time; # A way a zone keeps its clocks: how far ahead of UTC they are, and where what # it calls that is among the zone's names. struct keeping { var offset: i32; # Seconds ahead of UTC, which is negative to its west. var name: u32; # Where its abbreviation begins among the names. var length: u32; # How many bytes its abbreviation is. } # When a zone's clocks change each year, as the rule ending its file says it: a # day of the year, in one of three forms, and a time of that day. struct turning { var form: u8; # 0 for `Mm.w.d`, 1 for `Jn`, and 2 for a day counted from 0. var month: u8; # Of `Mm.w.d`, the month. var week: u8; # Of `Mm.w.d`, which of the month's weeks, 5 being its last. var day: u16; # Of `Mm.w.d`, the day of the week from Sunday, and otherwise the day of the year. var time: i32; # Seconds after midnight, as the clocks read before the change. } #! A time zone: how far its clocks are from UTC at any moment, and what it #! calls its time then. #! #! It owns its tables, which are closed with it. `zone::local()` lends the #! system's own zone, which the program keeps once it is read. pub struct zone { var _moments: vector; #! When its clocks changed, in seconds since 1970, in order. var _after: vector; #! The way it kept its clocks from each of those on. var _ways: vector; #! The ways it has kept its clocks, the first being that before any change. var _names: string; #! What it calls each, one after another. var _ruled: bool; #! Whether a rule says how its clocks change after the last of those. var _summer: bool; #! Whether the rule changes the clocks for part of each year. var _usual: keeping; #! How the rule keeps its clocks most of the year. var _saving: keeping; #! How it keeps them for the rest. var _begins: turning; #! When that begins each year. var _ends: turning; #! When it ends. } # A zone with nothing in it yet. def zone::empty(): zone { return zone { _moments = vector::::new(), _after = vector::::new(), _ways = vector::::new(), _names = string::new(nothing {}) }; } # Adds a way of keeping the clocks, called what the text says. def zone::keep(&mut this, offset: i32, name: strview): keeping { val made := keeping { offset = offset, name = this._names.length as u32, length = name.length as u32 }; this._names.append(name); return made; } #! The zone of UTC, which never changes. #! @returns The zone. pub def zone::utc(): zone { return zone::fixed(nanoseconds(0)); } #! A zone a fixed length of time ahead of UTC, to the second, which never #! changes. It calls its time "UTC" where it is no time ahead, and otherwise by #! its offset, as "+05:30". #! @param offset How far ahead of UTC its clocks are, which is negative to its #! west. #! @returns The zone. pub def zone::fixed(offset: duration): zone { var made := zone::empty(); val ahead := offset._ns / 1000000000; expects(ahead > -2147483648 && ahead < 2147483647, "A zone's offset is one an `i32` of seconds holds."); var name := string::new(nothing {}); if ahead == 0 { name.append("UTC"); } else { put_offset(&mut name, ahead, true); } val way := made.keep(ahead as i32, name.span); made._ways.append(way); return made; } #! The zone of a name in the system's database, as "Asia/Tokyo" or #! "America/Chicago", read from `/usr/share/zoneinfo`. Windows keeps no such #! database, so there it is read from the directory `TZDIR` names, where the #! program has that variable, and no name is a zone where it has not. #! @param name The zone's name. One beginning with `/` or holding `..` names #! nothing, so no name reaches outside the database, and neither #! does one beginning with `\` or holding `:` on Windows. #! @returns The zone, `no_such_zone` where the database has no file of the #! name, or `unreadable_zone` where the file is not a zone's. pub def zone::named(name: strview): result { if name.length == 0 || name[0] == '/' { return error::no_such_zone; } for i in 1u..name.length { if name[i] == '.' && name[i - 1] == '.' { return error::no_such_zone; } } when os == windows { if name[0] == '\\' { return error::no_such_zone; } for i in 0u..name.length { if name[i] == ':' { return error::no_such_zone; } } val directory := database() else { return error::no_such_zone; }; val text := $"{directory}/{name}"; var at := path::parse(text.span) else (_) { return error::no_such_zone; }; return zone::read(&at); } val text := $"/usr/share/zoneinfo/{name}"; var at := path::parse(text.span) else (_) { return error::no_such_zone; }; return zone::read(&at); } #! The zone a TZif file describes, wherever the file is. #! @param at The file's path. #! @returns The zone, `no_such_zone` where the file cannot be read, or #! `unreadable_zone` where it is not a zone's. pub def zone::read(at: &path): result { var file := io::file::open(at) else (_) { return error::no_such_zone; }; val data := io::read_all(&mut file) else (_) { return error::no_such_zone; }; return zone::parse(data.span); } # The zone the program keeps as the system's own, once it has been read. var local_read: bool = false; var local_zone: zone; when os == windows { # The directory of the database of zones, as `TZDIR` names it, which Windows # reads whatever the case of its letters, or nothing where the program has # none. def database(): maybe { for each in system::environment() { if each.length <= 6 || each[5] != '=' { continue; } var same := true; for i in 0u..5u { same = same && each[i].to_upper == "TZDIR"[i]; } if same { return each.substr(6, each.length - 6); } } return nothing {}; } } #! The zone the system is set to, read from `/etc/localtime` the first time it #! is asked for, and kept for as long as the program runs. Where the system #! says none that can be read, it is UTC. #! #! Windows keeps no such file, so there it is the rule the system keeps its #! clocks by now, as `system::zone_rule` writes it, which says nothing of how #! the zone kept them in years the rule was not yet made. #! @returns The zone, which the program keeps. pub def zone::local(): &zone { if !local_read { local_read = true; local_zone = zone::utc(); when os == windows { var rule := string::new(nothing {}); if system::zone_rule(&mut rule) { var found := zone::empty(); found.rule(rule.span); if found._ruled { local_zone = move(found); } } return &local_zone; } var at := path::parse("/etc/localtime") else (_) { return &local_zone; }; var found := zone::read(&at) else (_) { return &local_zone; }; local_zone = move(found); } return &local_zone; } # A number written in so many bytes, the most significant first. def unsigned_at(data: strview, at: u64, bytes: u64): u64 { var made: u64 = 0; for i in 0u..bytes { made = (made << 8) | data[at + i] as u64; } return made; } # A number written in so many bytes, the most significant first, which is # negative where its first bit is set. def signed_at(data: strview, at: u64, bytes: u64): i64 { val raw := unsigned_at(data, at, bytes); if bytes < 8 && (raw >> (bytes * 8 - 1)) != 0 { return raw as i64 - (1 as i64 << (bytes * 8)); } return raw as i64; } #! The zone the bytes of a TZif file describe, as RFC 8536 lays them out: the #! file's second block, of 64-bit moments, and the rule after it, where it has #! them, and its first otherwise. #! @param data The bytes of the file. #! @returns The zone, or `unreadable_zone` where the bytes are not a zone's, or #! are cut short. pub def zone::parse(data: strview): result { if data.length < 44 || data.substr(0, 4) != "TZif" { return error::unreadable_zone; } # A header counts what its block holds. A file of a later version holds a # first block of 32-bit moments, for old readers, and then all of it again in # 64 bits. var head: u64 = 0; var wide: u64 = 4; if data[4] != 0 { val moments := unsigned_at(data, 32, 4); val ways := unsigned_at(data, 36, 4); val names := unsigned_at(data, 40, 4); val leaps := unsigned_at(data, 28, 4); head = 44 + moments * 5 + ways * 6 + names + leaps * 8 + unsigned_at(data, 24, 4) + unsigned_at(data, 20, 4); wide = 8; if data.length < head + 44 || data.substr(head, 4) != "TZif" { return error::unreadable_zone; } } val universal := unsigned_at(data, head + 20, 4); val standard := unsigned_at(data, head + 24, 4); val leaps := unsigned_at(data, head + 28, 4); val moments := unsigned_at(data, head + 32, 4); val ways := unsigned_at(data, head + 36, 4); val names := unsigned_at(data, head + 40, 4); val body := head + 44; val size := moments * (wide + 1) + ways * 6 + names + leaps * (wide + 4) + standard + universal; if ways == 0 || ways > 256 || data.length < body + size { return error::unreadable_zone; } var made := zone::empty(); val kinds := body + moments * wide; val kept := kinds + moments; val text := kept + ways * 6; for i in 0u..moments { made._moments.append(signed_at(data, body + i * wide, wide)); if data[kinds + i] as u64 >= ways { return error::unreadable_zone; } made._after.append(data[kinds + i]); } made._names.append(data.substr(text, names)); for i in 0u..ways { # Each is its offset, whether it is a summer's, and where its abbreviation # begins, which ends at a zero. val begins := data[kept + i * 6 + 5] as u64; if begins >= names { return error::unreadable_zone; } var length: u64 = 0; while begins + length < names && data[text + begins + length] != 0 { length++; } made._ways.append(keeping { offset = signed_at(data, kept + i * 6, 4) as i32, name = begins as u32, length = length as u32 }); } # The rule is a line of its own after the second block. val after := body + size; if wide == 8 && after < data.length && data[after] == '\n' { var end := after + 1; while end < data.length && data[end] != '\n' { end++; } made.rule(data.substr(after + 1, end - after - 1)); } return move(made); } # What the rule ending a file says, as `CST6CDT,M3.2.0,M11.1.0`: what the zone # calls its usual time and how far behind UTC that is, and where its clocks # change, what it calls the other time, how far behind that is, and when it # begins and ends each year. A rule that cannot be read is no rule. def zone::rule(&mut this, text: strview): void { var at: u64 = 0; val usual := rule_name(text, &mut at); var behind: i64 = 0; return if usual.length == 0 || !rule_time(text, &mut at, &mut behind); this._usual = this.keep((-behind) as i32, usual); this._ruled = true; return if at >= text.length; val saving := rule_name(text, &mut at); return if saving.length == 0; # The other time is an hour ahead of the usual one where the rule gives none. var other := behind - 3600; if at < text.length && text[at] != ',' { return if !rule_time(text, &mut at, &mut other); } var begins := turning {}; var ends := turning {}; return if !rule_day(text, &mut at, &mut begins) || !rule_day(text, &mut at, &mut ends); this._saving = this.keep((-other) as i32, saving); this._begins = begins; this._ends = ends; this._summer = true; } # A name of a rule: letters, or anything between `<` and `>`. def rule_name(text: strview, at: &mut u64): strview { val start: u64 = at; if at < text.length && text[at] == '<' { while at < text.length && text[at] != '>' { at++; } return "" if at >= text.length; at++; return text.substr(start + 1, at - start - 2); } while at < text.length && ((text[at] >= 'a' && text[at] <= 'z') || (text[at] >= 'A' && text[at] <= 'Z')) { at++; } return text.substr(start, at - start); } # A time of a rule, as `6`, `-5:30`, or `2:00:00`, in seconds. def rule_time(text: strview, at: &mut u64, into: &mut i64): bool { var negative := false; if at < text.length && (text[at] == '+' || text[at] == '-') { negative = text[at] == '-'; at++; } var total: i64 = 0; var scale: i64 = 3600; var parts := 0; while parts < 3 { var value: i64 = 0; val start: u64 = at; while at < text.length && text[at] >= '0' && text[at] <= '9' { value = value * 10 + (text[at] - '0') as i64; at++; } return false if at == start || value > 999; total += value * scale; scale /= 60; parts++; break if at >= text.length || text[at] != ':'; at++; } into = negative ? -total : total; return true; } # A day of a rule after its comma, as `M3.2.0`, `J60`, or `59`, and the time # after its `/`, which is two in the morning where none is written. def rule_day(text: strview, at: &mut u64, into: &mut turning): bool { return false if at >= text.length || text[at] != ','; at++; return false if at >= text.length; var numbers: i64[3]; var count: u64 = 1; into.form = 2; if text[at] == 'M' { into.form = 0; count = 3; at++; } else if text[at] == 'J' { into.form = 1; at++; } for i in 0u..count { if i != 0 { return false if at >= text.length || text[at] != '.'; at++; } val start: u64 = at; var value: i64 = 0; while at < text.length && text[at] >= '0' && text[at] <= '9' { value = value * 10 + (text[at] - '0') as i64; at++; } return false if at == start || value > 366; numbers[i] = value; } if into.form == 0 { return false if numbers[0] < 1 || numbers[0] > 12 || numbers[1] < 1 || numbers[1] > 5 || numbers[2] > 6; into.month = numbers[0] as u8; into.week = numbers[1] as u8; into.day = numbers[2] as u16; } else { return false if into.form == 1 && (numbers[0] < 1 || numbers[0] > 365); into.day = numbers[0] as u16; } var time: i64 = 7200; if at < text.length && text[at] == '/' { at++; return false if !rule_time(text, at, &mut time); } into.time = time as i32; return true; } # The second, since 1970, a change of the rule comes in a year, where the # clocks are so far ahead of UTC before it. def turning::second_in(&this, year: i64, ahead: i64): i64 { val first := days_from_civil(year, 1, 1); var day := first + this.day as i64; if this.form == 0 { # The first of the month, the first of the day of the week on or after it, # and then the week asked for, the fifth being the month's last. val begins := days_from_civil(year, this.month as i64, 1); val length := days_in(year as i32, this.month as month) as i64; val falls := ((begins + 4) % 7 + 7) % 7; day = begins + (this.day as i64 - falls + 7) % 7 + (this.week as i64 - 1) * 7; while day >= begins + length { day -= 7; } } else if this.form == 1 { # Counted from 1, with no 29th of February. day = first + this.day as i64 - 1 + (is_leap_year(year as i32) && this.day >= 60 ? 1 : 0); } return day * 86400 + this.time as i64 - ahead; } # How the rule keeps the zone's clocks at a second since 1970. def zone::ruled_at(&this, second: i64): keeping { return this._usual if !this._summer; val year := date::of_days(floored(second + this._usual.offset as i64, 86400)).year as i64; val begins := this._begins.second_in(year, this._usual.offset as i64); val ends := this._ends.second_in(year, this._saving.offset as i64); # South of the equator the other time runs over the new year. val saving := begins < ends ? second >= begins && second < ends : !(second >= ends && second < begins); return saving ? this._saving : this._usual; } # How the zone keeps its clocks at a second since 1970. def zone::way_at(&this, second: i64): keeping { val count := this._moments.length; if count == 0 || second < this._moments[0] { return this._ruled && count == 0 ? this.ruled_at(second) : this._ways[0]; } if this._ruled && second >= this._moments[count - 1] { return this.ruled_at(second); } # The last change at or before it. var low: u64 = 0; var high: u64 = count; while high - low > 1 { val middle := low + (high - low) / 2; if this._moments[middle] <= second { low = middle; } else { high = middle; } } return this._ways[this._after[low]]; } # What the zone calls a way it keeps its clocks, viewing the zone's own names. def zone::name_of(&this, way: &keeping): strview { return this._names.span.substr(way.name as u64, way.length as u64); } #! How far ahead of UTC the zone's clocks are at a moment. #! @param this The zone. #! @param moment The moment. #! @returns The offset, which is negative to the west of UTC. pub def zone::offset_at(&this, moment: timestamp): duration { return seconds(this.way_at(moment.unix).offset as i64); } #! The moment the zone's clocks show a date and a time of day. #! #! Where they go forward, the times they skip are never shown, and one of those #! is taken as the moment that long after the change. Where they go back, the #! times they repeat are shown twice, and one of those is taken at its first. #! @param this The zone. #! @param day The date its clocks show. #! @param time The time of day they show. #! @returns The moment. pub def zone::resolve(&this, day: date, time: time_of_day): timestamp { val shown := sum_of(product_of(day.days(), 86400), time.hour as i64 * 3600 + time.minute as i64 * 60 + time.second as i64); # The clocks kept one offset a day before, and one a day after, and change at # most once between. The moment is the time shown less whichever of the two # the clocks kept at it. val before := this.way_at(shown - 86400).offset as i64; val after := this.way_at(shown + 86400).offset as i64; var second := shown - before; if before != after { val early := this.way_at(shown - before).offset as i64 == before; val late := this.way_at(shown - after).offset as i64 == after; if late && (!early || shown - after < shown - before) { second = shown - after; } } return timestamp { _ns = sum_of(product_of(second, 1000000000), time.nanosecond as i64) }; } # Writes an offset from UTC as `+05:30`, with its seconds where it has any and # they are asked for. def put_offset(into: &mut string, ahead: i64, exact: bool): void { val size := ahead < 0 ? -ahead : ahead; into.push(ahead < 0 ? '-' : '+'); put_padded(into, (size / 3600) as u64, 2); into.push(':'); put_padded(into, (size / 60 % 60) as u64, 2); if exact && size % 60 != 0 { into.push(':'); put_padded(into, (size % 60) as u64, 2); } }