Debian Codegraph @

time/date/timezone.ha

raw
1 // SPDX-License-Identifier: MPL-2.0
2 // (c) Hare authors <https://harelang.org>
3
4 use os;
5 use path;
6 use sort;
7 use strings;
8 use time;
9 use time::chrono;
10
11 // The duration of a day on Earth, in terrestrial (SI) seconds.
12 export def EARTH_DAY: time::duration = 86400 * time::SECOND;
13
14 // The duration of a solar day on Mars, in Martian seconds.
15 export def MARS_SOL_MARTIAN: time::duration = 86400 * time::SECOND;
16 // TODO: remove
17
18 // The duration of a solar day on Mars, in terrestrial (SI) seconds.
19 export def MARS_SOL_TERRESTRIAL: time::duration = 88775244147000 * time::NANOSECOND;
20 // TODO: remove
21
22 // The locality of a [[date]]. Contains information about how to calculate a
23 // moment's observed chronological values.
24 export type locality = *timezone;
25
26 // A timezone; a political or otherwise theoretical region with a ruleset
27 // regarding offsets for calculating localized date/time.
28 export type timezone = struct {
29 // The base timescale (e.g. time::chrono::utc).
30 tsc: *chrono::timescale,
31
32 // The textual identifier (e.g. "Europe/Amsterdam").
33 name: str,
34
35 // The duration of a day in this timezone (e.g. 24 * time::HOUR).
36 daylength: time::duration,
37
38 // The possible zonephases a locality with this timezone can observe
39 // (e.g. CET, CEST, ...).
40 phases: []zonephase,
41
42 // The transitions between this timezone's zonephases.
43 transitions: []zonetransition,
44
45 // The function to calculate the correct [[zonephase]] to observe.
46 // If null, defaults to an internal function.
47 lookupzone: nullable *zonelookuper,
48
49 // Used for extending calculations beyond the last known transition.
50 // See [[petz]].
51 petz: petz,
52 };
53
54 // A [[timezone]] state, with an offset for calculating localized date/time.
55 export type zonephase = struct {
56 // The offset from the normal timezone (e.g. 2 * time::HOUR).
57 zoff: time::duration,
58
59 // The full descriptive name (e.g. "Central European Summer Time").
60 name: str,
61
62 // The abbreviated name (e.g. "CEST").
63 abbr: str,
64
65 // Indicator of Daylight Saving Time.
66 dst: bool, // true
67 };
68
69 // A [[timezone]] transition between two [[zonephase]]s.
70 export type zonetransition = struct {
71 when: time::instant,
72 zoneindex: size,
73 };
74
75 // Determines the correct [[zonephase]] to observe for a given [[date]].
76 export type zonelookuper = fn(loc: locality, d: *date) *zonephase;
77
78 // Frees a [[timezone]]. A [[locality]] argument can be passed.
79 export fn timezone_free(tz: *timezone) void = {
80 free(tz.name);
81 for (let zonephase &.. tz.phases) {
82 zone_finish(zonephase);
83 };
84 free(tz.phases);
85 free(tz.transitions);
86 petz_finish(&tz.petz);
87 free(tz);
88 };
89
90 // Frees resources associated with a [[zonephase]].
91 export fn zone_finish(z: *zonephase) void = {
92 free(z.name);
93 free(z.abbr);
94 };
95
96 // Calculates and returns a [[date]]'s observed [[zonephase]].
97 fn lookupzone(loc: locality, d: *date) *zonephase = {
98 if (len(loc.phases) == 0) {
99 abort("Timezone has no zonephases");
100 };
101
102 if (len(loc.phases) == 1) {
103 return &loc.phases[0];
104 };
105
106 let t = to_instant(*d);
107 let trs = loc.transitions[..];
108
109 if (len(trs) == 0 || time::compare(t, trs[0].when) == -1) {
110 // tzfile(5) suggests we use "time type 0" for instants before
111 // the first transition.
112 return &loc.phases[0];
113 };
114
115 // index of transition which t is equal to or greater than.
116 const idx = -1 + sort::rbisect(
117 trs, size(zonetransition), &t, &cmpinstants,
118 );
119
120 let z = &loc.phases[trs[idx].zoneindex];
121
122 // if we've reached the end of the locality's transitions,
123 // try its POSIX "extending" TZ string.
124 if (idx == len(trs) - 1) {
125 z = lookupzone_posix(loc, d);
126 };
127
128 return z;
129 };
130
131 fn cmpinstants(a: const *opaque, b: const *opaque) int = {
132 let a = a: *zonetransition;
133 let b = b: *time::instant;
134 return time::compare(a.when, *b): int;
135 };
136
137 // Creates a [[timezone]] with a single [[zonephase]]. Useful for fixed offsets.
138 // The caller must free the return value with [[timezone_free]]. An example,
139 // replicate the civil time Hawaii timezone on Earth:
140 //
141 // let hawaii = chrono::fixedzone(
142 // &chrono::utc,
143 // "Custom/Hawaiian_Reef",
144 // chrono::EARTH_DAY,
145 // chrono::zonephase {
146 // zoff = -10 * time::HOUR,
147 // abbr = "HARE",
148 // dst = false,
149 // ...
150 // },
151 // );
152 //
153 export fn fixedzone(
154 tsc: *chrono::timescale,
155 name: str,
156 daylen: time::duration,
157 z: zonephase,
158 ) (*timezone | nomem) = {
159 let ok = false;
160 let name = strings::dup(name)?;
161 defer if (!ok) free(name);
162 let phases = alloc([z])?;
163 defer if (!ok) free(phases);
164
165 let zone = alloc(timezone {
166 name = name,
167 tsc = tsc,
168 daylength = daylen,
169 phases = phases,
170 transitions = [],
171 lookupzone = null,
172 petz = PETZ_EMPTY,
173 })?;
174 ok = true;
175 return zone;
176 };
177
178 // The local [[locality]]; the system or environment configured [[timezone]].
179 //
180 // This is set during the program's initialization. In order of preference, the
181 // TZ environment variable is used, if set; the file at [[LOCALTIME_PATH]], if
182 // present; or, as a last resort, [[UTC]] is used as a default.
183 export const LOCAL: locality = &TZ_UTC;
184
185 @init fn init_tz_local() void = {
186 let path = match (os::getenv("TZ")) {
187 case let s: str =>
188 // remove POSIX prefix ':'
189 let s =
190 if (strings::hasprefix(s, ":"))
191 strings::trimprefix(s, ":")
192 else
193 s;
194
195 yield match (path::init(s)) {
196 case => return;
197 case let p: path::buffer =>
198 yield path::string(&p);
199 };
200
201 case void =>
202 let s = match (os::realpath(LOCALTIME_PATH)) {
203 case => return;
204 case let s: str =>
205 yield s;
206 };
207
208 let p = match (path::init(s)) {
209 case => return;
210 case let p: path::buffer =>
211 yield p;
212 };
213
214 yield match (path::trimprefix(&p, TZDB_PATH)) {
215 case => return;
216 case let s: str =>
217 yield s;
218 };
219 };
220
221 match (tzdb(path)) {
222 case => void;
223 case let loc: locality =>
224 LOCAL = loc;
225 };
226 };
227
228 @fini fn free_tz_local() void = {
229 if (LOCAL != UTC) {
230 timezone_free(LOCAL);
231 };
232 };
233
234 // The UTC (Coordinated Universal Time) "Zulu" [[timezone]] as a [[locality]].
235 // Uses the [[time::chrono::utc]] timescale.
236 export const UTC: locality = &TZ_UTC;
237
238 const TZ_UTC: timezone = timezone {
239 name = "UTC",
240 tsc = &chrono::utc,
241 daylength = EARTH_DAY,
242 phases = [
243 zonephase {
244 zoff = 0 * time::SECOND,
245 name = "Universal Coordinated Time",
246 abbr = "UTC",
247 dst = false,
248 },
249 ],
250 transitions = [],
251 lookupzone = null,
252 petz = PETZ_EMPTY,
253 };
254
255 // The TAI (International Atomic Time) "Zulu" [[timezone]] as a [[locality]].
256 // Uses the [[time::chrono::tai]] timescale.
257 export const TAI: locality = &TZ_TAI;
258
259 const TZ_TAI: timezone = timezone {
260 name = "TAI",
261 tsc = &chrono::tai,
262 daylength = EARTH_DAY,
263 phases = [
264 zonephase {
265 zoff = 0 * time::SECOND,
266 name = "International Atomic Time",
267 abbr = "TAI",
268 dst = false,
269 },
270 ],
271 transitions = [],
272 lookupzone = null,
273 petz = PETZ_EMPTY,
274 };
275
276 // The GPS (Global Positioning System) "Zulu" [[timezone]] as a [[locality]].
277 // Uses the [[time::chrono::gps]] timescale.
278 export const GPS: locality = &TZ_GPS;
279
280 const TZ_GPS: timezone = timezone {
281 name = "GPS",
282 tsc = &chrono::gps,
283 daylength = EARTH_DAY,
284 phases = [
285 zonephase {
286 zoff = 0 * time::SECOND,
287 name = "Global Positioning System",
288 abbr = "GPS",
289 dst = false,
290 },
291 ],
292 transitions = [],
293 lookupzone = null,
294 petz = PETZ_EMPTY,
295 };
296
297 // The TT (Terrestrial Time) "Zulu" [[timezone]] as a [[locality]].
298 // Uses the [[time::chrono::tt]] timescale.
299 export const TT: locality = &TZ_TT;
300
301 const TZ_TT: timezone = timezone {
302 name = "TT",
303 tsc = &chrono::tt,
304 daylength = EARTH_DAY,
305 phases = [
306 zonephase {
307 zoff = 0 * time::SECOND,
308 name = "Terrestrial Time",
309 abbr = "TT",
310 dst = false,
311 },
312 ],
313 transitions = [],
314 lookupzone = null,
315 petz = PETZ_EMPTY,
316 };
317
318 // The MTC (Coordinated Mars Time) "Zulu" [[timezone]] as a [[locality]].
319 // Uses the [[time::chrono::mtc]] timescale.
320 export const MTC: locality = &TZ_MTC;
321
322 const TZ_MTC: timezone = timezone {
323 name = "MTC",
324 tsc = &chrono::mtc,
325 daylength = MARS_SOL_MARTIAN,
326 phases = [
327 zonephase {
328 zoff = 0 * time::SECOND,
329 name = "Coordinated Mars Time",
330 abbr = "MTC",
331 dst = false,
332 },
333 ],
334 transitions = [],
335 lookupzone = null,
336 petz = PETZ_EMPTY,
337 };