Debian Codegraph @

time/chrono/timescale.ha

raw
1 // SPDX-License-Identifier: MPL-2.0
2 // (c) Hare authors <https://harelang.org>
3
4 // TODO: consider: export const TSC_UTC = &utc; etc.
5
6 use time;
7
8 // Represents a scale of time; a time standard. See [[convert]].
9 export type timescale = struct {
10 name: str,
11 abbr: str,
12 convto: *tsconverter,
13 convfrom: *tsconverter,
14 };
15
16 export type tsconverter = fn(ts: *timescale, i: time::instant) ([]time::instant | void | nomem);
17
18 // Timescale mismatch.
19 export type tscmismatch = !(*timescale, *timescale);
20
21 fn check_timescales(a: *timescale, b: *timescale) (void | tscmismatch) = {
22 if (a != b) {
23 return (a, b): tscmismatch;
24 };
25 };
26
27 // Converts a [[moment]] from one [[timescale]] to the next exhaustively.
28 // The final conversion result is returned. For each considered pair of
29 // timescales, if neither implements conversion from the first to the second, a
30 // two-step intermediary [[tai]] conversion will occur. If given zero
31 // timescales, the given moment is returned. The caller must free the result.
32 export fn convert(m: moment, tscs: *timescale...) ([]moment | nomem) = {
33 // TODO: consider returning just 2-tuple of (earliest, latest) moments.
34
35 let ok = false;
36 let t = *(&m: *time::instant);
37 let ms: []moment = [m];
38 defer if (!ok) free(ms);
39 let tmps: []moment = [];
40 defer if (!ok) free(tmps);
41
42 for (let j = 0z; j < len(tscs); j += 1) {
43 let a = if (j == 0) m.tsc else tscs[j - 1];
44 let b = tscs[j];
45
46 for (let k = 0z; k < len(ms); k += 1) {
47 const m = ms[k];
48
49 // try .convto
50 match (a.convto(b, to_instant(m))) {
51 case let convs: []time::instant =>
52 for (let c .. convs) {
53 append(tmps, new(b, c))?;
54 };
55 continue;
56 case void => void;
57 };
58
59 // try .convfrom
60 match (b.convfrom(a, to_instant(m))) {
61 case let convs: []time::instant =>
62 for (let c .. convs) {
63 append(tmps, new(b, c))?;
64 };
65 continue;
66 case void => void;
67 };
68
69 // default to TAI intermediary
70 const convs = a.convto(&tai, to_instant(m)) as []time::instant;
71 for (let c .. convs) {
72 const convs = b.convfrom(&tai, c) as []time::instant;
73 for (let c .. convs) {
74 append(tmps, new(b, c))?;
75 };
76 continue;
77 };
78 };
79
80 // TODO: sort and deduplicate 'ms' here
81 free(ms);
82 ms = tmps;
83 tmps = [];
84 };
85
86 ok = true;
87 return ms;
88 };
89
90
91 // International Atomic Time
92 //
93 // The realisation of proper time on Earth's geoid.
94 // Continuous (no leap seconds).
95 export const tai: timescale = timescale {
96 name = "International Atomic Time",
97 abbr = "TAI",
98 convto = &tai_conv,
99 convfrom = &tai_conv,
100 };
101
102 fn tai_conv(ts: *timescale, i: time::instant) ([]time::instant | void | nomem) = {
103 if (ts == &tai) {
104 return alloc([i]...)?;
105 };
106 };
107
108
109 // Coordinated Universal Time
110 //
111 // Used as the basis of civil timekeeping.
112 // Based on TAI; time-dependent offset.
113 // Discontinuous (has leap seconds).
114 //
115 // During a program's initialization, this timescale initializes by loading its
116 // UTC/TAI leapsecond data from [[UTC_LEAPSECS_PATH]]; otherwise, fails
117 // silently. If failed, any attempt to consult UTC leapsec data (e.g. calling
118 // [[convert]] on UTC) causes an abort. This includes [[time::date::in]].
119 export const utc: timescale = timescale {
120 name = "Coordinated Universal Time",
121 abbr = "UTC",
122 convto = &utc_convto,
123 convfrom = &utc_convfrom,
124 };
125 // TODO: find better way to handle utc initialization cases.
126
127 fn utc_convto(ts: *timescale, i: time::instant) ([]time::instant | void | nomem) = {
128 let ok = false;
129 let ret: []time::instant = [];
130 defer if (!ok) free(ret);
131
132 if (ts == &utc) {
133 append(ret, i)?;
134 ok = true;
135 return ret;
136 } else if (ts == &tai) {
137 match (utc_status) {
138 case let loaded: bool =>
139 if (!loaded) {
140 match (utc_init_leapsecs()) {
141 case void =>
142 utc_status = true;
143 case =>
144 abort("UTC timescale init error");
145 };
146 };
147 case utciniterror =>
148 abort("UTC timescale init error");
149 };
150
151 const firstleap = utc_leapsecs[0]; // TODO: no leapsecs loaded
152 if (time::compare(i, time::new(firstleap.0)) < 0) {
153 append(ret, time::instant {
154 sec = i.sec + firstleap.1,
155 nsec = i.nsec,
156 })?;
157 ok = true;
158 return ret;
159 };
160
161 for (let idx = len(utc_leapsecs) - 1; idx >= 0 ; idx -= 1) {
162 const leap = utc_leapsecs[idx];
163 const leapsecond = time::new(leap.0);
164 const leapoffset = leap.1;
165 const diff = time::diff(leapsecond, i);
166
167 const prevleapoffset =
168 if (idx == 0) 0i64 else utc_leapsecs[idx - 1].1;
169 const offsetdiff =
170 (leapoffset - prevleapoffset) * time::SECOND;
171
172 // case of positive leap second (UTC repeats a second)
173 if (offsetdiff >= 0) {
174 if (diff >= 0) {
175 append(ret, time::instant {
176 sec = i.sec + leapoffset,
177 nsec = i.nsec,
178 })?;
179 ok = true;
180 return ret;
181 };
182
183 if (diff >= -offsetdiff && diff < 0) {
184 append(ret, [
185 time::instant {
186 sec = i.sec + prevleapoffset,
187 nsec = i.nsec,
188 },
189 time::instant {
190 sec = i.sec + leapoffset,
191 nsec = i.nsec,
192 },
193 ]...)?;
194 ok = true;
195 return ret;
196 };
197
198 continue;
199 };
200
201 // case of negative leap second (UTC skips a second)
202 if (offsetdiff < 0) {
203 if (diff >= 0) {
204 append(ret, time::instant {
205 sec = i.sec + leapoffset,
206 nsec = i.nsec,
207 })?;
208 ok = true;
209 return ret;
210 };
211
212 if (diff >= offsetdiff && diff < 0) {
213 ok = true;
214 return ret;
215 };
216
217 continue;
218 };
219 };
220 };
221
222 ok = true;
223 };
224
225 fn utc_convfrom(ts: *timescale, i: time::instant) ([]time::instant | void | nomem) = {
226 let ok = false;
227 let ret: []time::instant = [];
228 defer if (!ok) free(ret);
229 if (ts == &utc) {
230 append(ret, i)?;
231 ok = true;
232 return ret;
233 } else if (ts == &tai) {
234 match (utc_status) {
235 case let loaded: bool =>
236 if (!loaded) {
237 match (utc_init_leapsecs()) {
238 case void =>
239 utc_status = true;
240 case =>
241 abort("UTC timescale init error");
242 };
243 };
244 case utciniterror =>
245 abort("UTC timescale init error");
246 };
247
248 const firstleap = utc_leapsecs[0]; // TODO: no leapsecs loaded
249 if (time::compare(i, time::new(firstleap.0 + firstleap.1)) < 0) {
250 append(ret, time::instant {
251 sec = i.sec - firstleap.1,
252 nsec = i.nsec,
253 })?;
254 ok = true;
255 return ret;
256 };
257
258 for (let idx = len(utc_leapsecs) - 1; idx >= 0 ; idx -= 1) {
259 const leap = utc_leapsecs[idx];
260 const leapsecond = time::new(leap.0 + leap.1);
261 const leapoffset = leap.1;
262 const diff = time::diff(leapsecond, i);
263
264 const prevleapoffset =
265 if (idx == 0) 10i64 else utc_leapsecs[idx - 1].1;
266 const offsetdiff
267 = (leapoffset - prevleapoffset) * time::SECOND;
268
269 // case of positive leap second (UTC repeats a second)
270 if (offsetdiff >= 0) {
271 if (diff >= -offsetdiff) {
272 append(ret, time::instant {
273 sec = i.sec - leapoffset,
274 nsec = i.nsec,
275 })?;
276 ok = true;
277 return ret;
278 };
279
280 continue;
281 };
282
283 // case of negative leap second (UTC skips a second)
284 if (offsetdiff < 0) {
285 if (diff >= 0) {
286 append(ret, time::instant {
287 sec = i.sec - leapoffset,
288 nsec = i.nsec,
289 })?;
290 ok = true;
291 return ret;
292 };
293
294 continue;
295 };
296 };
297 };
298
299 ok = true;
300 };
301
302
303 // Global Positioning System Time
304 //
305 // Used for GPS coordination.
306 // Based on TAI; constant -19 second offset.
307 // Continuous (no leap seconds).
308 export const gps: timescale = timescale {
309 name = "Global Positioning System Time",
310 abbr = "GPS",
311 convto = &gps_convto,
312 convfrom = &gps_convfrom,
313 };
314
315 // The constant offset between GPS-Time (Global Positioning System Time) and TAI
316 // (International Atomic Time). Used by [[gps]].
317 def GPS_OFFSET: time::duration = -19 * time::SECOND;
318
319 fn gps_convto(ts: *timescale, i: time::instant) ([]time::instant | void | nomem) = {
320 if (ts == &gps) {
321 return alloc([i]...)?;
322 } else if (ts == &tai) {
323 return alloc([time::add(i, -GPS_OFFSET)]...)?;
324 };
325 };
326
327 fn gps_convfrom(ts: *timescale, i: time::instant) ([]time::instant | void | nomem) = {
328 if (ts == &gps) {
329 return alloc([i]...)?;
330 } else if (ts == &tai) {
331 return alloc([time::add(i, GPS_OFFSET)]...)?;
332 };
333 };
334
335
336 // Terrestrial Time
337 //
338 // Used for astronomical timekeeping.
339 // Based on TAI; constant +32.184 offset.
340 // Continuous (no leap seconds).
341 export const tt: timescale = timescale {
342 name = "Terrestrial Time",
343 abbr = "TT",
344 convto = &tt_convto,
345 convfrom = &tt_convfrom,
346 };
347
348 // The constant offset between TT (Terrestrial Time) and TAI (International
349 // Atomic Time). Used by [[tt]].
350 def TT_OFFSET: time::duration = 32184 * time::MILLISECOND; // 32.184 seconds
351
352 fn tt_convto(ts: *timescale, i: time::instant) ([]time::instant | void | nomem) = {
353 if (ts == &tt) {
354 return alloc([i]...)?;
355 } else if (ts == &tai) {
356 return alloc([time::add(i, -TT_OFFSET)]...)?;
357 };
358 };
359
360
361 fn tt_convfrom(ts: *timescale, i: time::instant) ([]time::instant | void | nomem) = {
362 if (ts == &tt) {
363 return alloc([i]...)?;
364 } else if (ts == &tai) {
365 return alloc([time::add(i, TT_OFFSET)]...)?;
366 };
367 };
368
369 // Arthur David Olson had expressed support for Martian time in his timezone
370 // database project <https://data.iana.org/time-zones/theory.html>:
371 //
372 // > The tz database does not currently support Mars time, but it is documented
373 // > here in the hopes that support will be added eventually.
374
375 // Coordinated Mars Time
376 //
377 // Used for timekeeping on Mars.
378 // Based on TT; constant factor.
379 // Continuous (no leap seconds).
380 export const mtc: timescale = timescale {
381 name = "Coordinated Mars Time",
382 abbr = "MTC",
383 convto = &mtc_convto,
384 convfrom = &mtc_convfrom,
385 };
386
387 // Factor f, where Martian-time * f == Earth-time.
388 def FACTOR_TERRESTRIAL_MARTIAN: f64 = 1.0274912517;
389
390 // [[time::duration]] in Earth-time between the Unix epoch of 1970 Jan 1st
391 // midnight, and the Earth-Mars convergence date of 2000 Jan 6th midnight.
392 def DELTA_UNIXEPOCH_JANSIX: time::duration = 10962 * 24 * time::HOUR;
393
394 // [[time::duration]] in Mars-time between the Mars Sol Date epoch corresponding
395 // to the Gregorian Earth date 1873 Dec 29th, and the Earth-Mars convergence
396 // date of 2000 Jan 6.
397 def DELTA_MARSEPOCH_JANSIX: time::duration = 44796 * 24 * time::HOUR;
398
399 // [[time::duration]] in Mars-time between the midnights of 2000 Jan 6th on
400 // Earth and Mars. Earth's midnight occurred first.
401 def DELTA_JANSIX_ADJUSTMENT: time::duration = 82944 * time::MILLISECOND;
402
403 fn mtc_convto(ts: *timescale, i: time::instant) ([]time::instant | void | nomem) = {
404 if (ts == &mtc) {
405 return alloc([i]...)?;
406 } else if (ts == &tai) {
407 // Change epoch from that of the Mars Sol Date
408 // to the Earth-Mars convergence date 2000 Jan 6th.
409 let i = time::add(i, -DELTA_MARSEPOCH_JANSIX);
410
411 // Slightly adjust epoch for the actual Martian midnight.
412 // Earth's midnight occurred before Mars'.
413 i = time::add(i, DELTA_JANSIX_ADJUSTMENT);
414
415 // Scale from Mars-time to Earth-time.
416 i = time::mult(i, FACTOR_TERRESTRIAL_MARTIAN);
417
418 // Change epoch to the Unix epoch 1970 Jan 1st (Terrestrial Time).
419 i = time::add(i, DELTA_UNIXEPOCH_JANSIX);
420
421 // Get the TAI time.
422 // assertion since TT and TAI are continuous.
423 return alloc([(tt.convto(&tai, i) as []time::instant)[0]]...)?;
424 };
425 };
426
427 fn mtc_convfrom(ts: *timescale, i: time::instant) ([]time::instant | void | nomem) = {
428 if (ts == &mtc) {
429 return alloc([i]...)?;
430 } else if (ts == &tai) {
431 // Get the "Terrestrial Time".
432 // assertion since TT and TAI are continuous.
433 let i = (tt.convfrom(&tai, i) as []time::instant)[0];
434
435 // Change epoch from the Unix epoch 1970 Jan 1st (Terrestrial Time)
436 // to the Earth-Mars convergence date 2000 Jan 6th midnight.
437 i = time::add(i, -DELTA_UNIXEPOCH_JANSIX);
438
439 // Scale from Earth-time to Mars-time.
440 i = time::mult(i, 1.0 / FACTOR_TERRESTRIAL_MARTIAN);
441
442 // Slightly adjust epoch for the actual Martian midnight.
443 // Earth's midnight occurred before Mars'.
444 i = time::add(i, -DELTA_JANSIX_ADJUSTMENT);
445
446 // Change epoch to that of the Mars Sol Date.
447 return alloc([time::add(i, DELTA_MARSEPOCH_JANSIX)]...)?;
448 };
449 };
450
451
452 @test fn utc_convto_tai() void = {
453 // TODO: skip test if no leapsec data available (!utc_isinitialized)
454 // TODO: test negative leapsecs somehow
455 let testcases: [](
456 (i64, i64), // give
457 (void | [0](i64, i64) | [1](i64, i64) | [2](i64, i64)) // expect
458 ) = [
459 ((- 1000i64, 0i64), [(- 990i64, 0i64)]),
460 (( 0i64, 0i64), [( 10i64, 0i64)]),
461 (( 1000i64, 0i64), [( 1010i64, 0i64)]),
462 // 1970 Jan 01
463 (( 63071998i64, 0i64), [( 63072008i64, 0i64)]),
464 (( 63071998i64, 500000000i64), [( 63072008i64, 500000000i64)]),
465 (( 63071999i64, 0i64), [( 63072009i64, 0i64)]),
466 (( 63071999i64, 500000000i64), [( 63072009i64, 500000000i64)]),
467 (( 63072000i64, 0i64), [( 63072010i64, 0i64)]),
468 (( 63072000i64, 500000000i64), [( 63072010i64, 500000000i64)]),
469 (( 63072001i64, 0i64), [( 63072011i64, 0i64)]),
470 (( 63072001i64, 500000000i64), [( 63072011i64, 500000000i64)]),
471 (( 63072002i64, 0i64), [( 63072012i64, 0i64)]),
472 // 1981 Jul 01
473 (( 362793598i64, 0i64), [( 362793617i64, 0i64)]),
474 (( 362793598i64, 500000000i64), [( 362793617i64, 500000000i64)]),
475 (( 362793599i64, 0i64), [
476 ( 362793618i64, 0i64),
477 ( 362793619i64, 0i64),
478 ]),
479 (( 362793599i64, 500000000i64), [
480 ( 362793618i64, 500000000i64),
481 ( 362793619i64, 500000000i64),
482 ]),
483 (( 362793600i64, 0i64), [( 362793620i64, 0i64)]),
484 (( 362793600i64, 500000000i64), [( 362793620i64, 500000000i64)]),
485 (( 362793601i64, 0i64), [( 362793621i64, 0i64)]),
486 (( 362793601i64, 500000000i64), [( 362793621i64, 500000000i64)]),
487 (( 362793602i64, 0i64), [( 362793622i64, 0i64)]),
488 // 2017 Jan 01
489 (( 1483228798i64, 0i64), [( 1483228834i64, 0i64)]),
490 (( 1483228798i64, 500000000i64), [( 1483228834i64, 500000000i64)]),
491 (( 1483228799i64, 0i64), [
492 ( 1483228835i64, 0i64),
493 ( 1483228836i64, 0i64),
494 ]),
495 (( 1483228799i64, 500000000i64), [
496 ( 1483228835i64, 500000000i64),
497 ( 1483228836i64, 500000000i64),
498 ]),
499 (( 1483228800i64, 0i64), [( 1483228837i64, 0i64)]),
500 (( 1483228800i64, 500000000i64), [( 1483228837i64, 500000000i64)]),
501 (( 1483228801i64, 0i64), [( 1483228838i64, 0i64)]),
502 (( 1483228801i64, 500000000i64), [( 1483228838i64, 500000000i64)]),
503 (( 1483228802i64, 0i64), [( 1483228839i64, 0i64)]),
504 ];
505
506 for (let testcase .. testcases) {
507 let params = testcase.0;
508 let param = time::instant{ sec = params.0, nsec = params.1 };
509 let expect = testcase.1;
510 let actual = utc_convto(&tai, param);
511
512 match (expect) {
513 case void =>
514 assert(actual is void);
515
516 case [0](i64, i64) =>
517 assert(actual is []time::instant);
518 const actual = actual as []time::instant;
519 assert(len(actual) == 0);
520
521 case let insts: [1](i64, i64) =>
522 assert(actual is []time::instant);
523 const actual = actual as []time::instant;
524 assert(len(actual) == 1);
525 assert(0 == time::compare(
526 actual[0],
527 time::instant{
528 sec = insts[0].0,
529 nsec = insts[0].1,
530 },
531 ));
532
533 case let insts: [2](i64, i64) =>
534 assert(actual is []time::instant);
535 const actual = actual as []time::instant;
536 assert(len(actual) == 2);
537 assert(0 == time::compare(
538 actual[0],
539 time::instant{
540 sec = insts[0].0,
541 nsec = insts[0].1,
542 },
543 ));
544 assert(0 == time::compare(
545 actual[1],
546 time::instant{
547 sec = insts[1].0,
548 nsec = insts[1].1,
549 },
550 ));
551 };
552 if (actual is []time::instant) {
553 free(actual as []time::instant);
554 };
555
556 };
557 };
558
559 @test fn utc_convfrom_tai() void = {
560 // TODO: skip test if no leapsec data available (!utc_isinitialized)
561 // TODO: test negative leapsecs somehow
562 let testcases: [](
563 (i64, i64), // give
564 (void | [0](i64, i64) | [1](i64, i64) | [2](i64, i64)) // expect
565 ) = [
566 ((- 990i64, 0i64), [(- 1000i64, 0i64)]),
567 (( 10i64, 0i64), [( 0i64, 0i64)]),
568 (( 1010i64, 0i64), [( 1000i64, 0i64)]),
569 // 1970 Jan 01
570 (( 63072008i64, 0i64), [( 63071998i64, 0i64)]),
571 (( 63072008i64, 500000000i64), [( 63071998i64, 500000000i64)]),
572 (( 63072009i64, 0i64), [( 63071999i64, 0i64)]),
573 (( 63072009i64, 500000000i64), [( 63071999i64, 500000000i64)]),
574 (( 63072010i64, 0i64), [( 63072000i64, 0i64)]),
575 (( 63072010i64, 500000000i64), [( 63072000i64, 500000000i64)]),
576 (( 63072011i64, 0i64), [( 63072001i64, 0i64)]),
577 (( 63072011i64, 500000000i64), [( 63072001i64, 500000000i64)]),
578 (( 63072012i64, 0i64), [( 63072002i64, 0i64)]),
579 // 1981 Jul 01
580 (( 362793617i64, 0i64), [( 362793598i64, 0i64)]),
581 (( 362793617i64, 500000000i64), [( 362793598i64, 500000000i64)]),
582 (( 362793618i64, 0i64), [( 362793599i64, 0i64)]),
583 (( 362793618i64, 500000000i64), [( 362793599i64, 500000000i64)]),
584 (( 362793619i64, 0i64), [( 362793599i64, 0i64)]),
585 (( 362793619i64, 500000000i64), [( 362793599i64, 500000000i64)]),
586 (( 362793620i64, 0i64), [( 362793600i64, 0i64)]),
587 (( 362793620i64, 500000000i64), [( 362793600i64, 500000000i64)]),
588 (( 362793621i64, 0i64), [( 362793601i64, 0i64)]),
589 (( 362793621i64, 500000000i64), [( 362793601i64, 500000000i64)]),
590 (( 362793622i64, 0i64), [( 362793602i64, 0i64)]),
591 // 2017 Jan 01
592 (( 1483228834i64, 0i64), [( 1483228798i64, 0i64)]),
593 (( 1483228834i64, 500000000i64), [( 1483228798i64, 500000000i64)]),
594 (( 1483228835i64, 0i64), [( 1483228799i64, 0i64)]),
595 (( 1483228835i64, 500000000i64), [( 1483228799i64, 500000000i64)]),
596 (( 1483228836i64, 0i64), [( 1483228799i64, 0i64)]),
597 (( 1483228836i64, 500000000i64), [( 1483228799i64, 500000000i64)]),
598 (( 1483228837i64, 0i64), [( 1483228800i64, 0i64)]),
599 (( 1483228837i64, 500000000i64), [( 1483228800i64, 500000000i64)]),
600 (( 1483228838i64, 0i64), [( 1483228801i64, 0i64)]),
601 (( 1483228838i64, 500000000i64), [( 1483228801i64, 500000000i64)]),
602 (( 1483228839i64, 0i64), [( 1483228802i64, 0i64)]),
603 ];
604
605 for (let testcase .. testcases) {
606 let params = testcase.0;
607 let param = time::instant{ sec = params.0, nsec = params.1 };
608 let expect = testcase.1;
609 let actual = utc_convfrom(&tai, param);
610
611 match (expect) {
612 case void =>
613 assert(actual is void);
614
615 case [0](i64, i64) =>
616 assert(actual is []time::instant);
617 const actual = actual as []time::instant;
618 assert(len(actual) == 0);
619
620 case let insts: [1](i64, i64) =>
621 assert(actual is []time::instant);
622 const actual = actual as []time::instant;
623 assert(len(actual) == 1);
624 assert(0 == time::compare(
625 actual[0],
626 time::instant{
627 sec = insts[0].0,
628 nsec = insts[0].1,
629 },
630 ));
631
632 case let insts: [2](i64, i64) =>
633 assert(actual is []time::instant);
634 const actual = actual as []time::instant;
635 assert(len(actual) == 2);
636 assert(0 == time::compare(
637 actual[0],
638 time::instant{
639 sec = insts[0].0,
640 nsec = insts[0].1,
641 },
642 ));
643 assert(0 == time::compare(
644 actual[1],
645 time::instant{
646 sec = insts[1].0,
647 nsec = insts[1].1,
648 },
649 ));
650 };
651 if (actual is []time::instant) {
652 free(actual as []time::instant);
653 };
654 };
655 };