tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

504 lignes · 10669 octetsBrut · Historique
1/// Time, as an effect (ADR 0036): timestamps, durations, UTC dates and
2/// RFC 3339.
3///
4/// let t = time.now() // a Timestamp
5/// show(t) // "2026-10-13T09:30:00.250Z"
6/// time.parse("2026-10-13T11:30:00+02:00") // Ok(the same instant)
7///
8/// `now` and `monotonic` read the `clock` effect. The runtime handles it
9/// around `main`, each test and each actor: `now_unix_ns` is the system's
10/// real-time clock; `monotonic_ns` is the scheduler's clock, which is
11/// virtual until the program opens a socket (ADR 0004, Revision 3), so a
12/// program without sockets measures what `process.sleep` waited, the same
13/// on every run. A test can fix the time instead:
14///
15/// time.with_fixed_clock(time.from_unix_ns(0), fn() { time.now() })
16///
17/// A handler does not follow `process.spawn`: a new actor always gets the
18/// system's clock. UTC only: there are no time zones here.
19
20import std/bytes
21import std/string
22
23/// Clocks.
24pub effect clock
25{
26 /// Nanoseconds since 1970-01-01T00:00:00Z (the system's clock: it can
27 /// jump backwards when the system's time is set).
28 fn now_unix_ns :: -> Int
29 /// Nanoseconds since an arbitrary origin, never going backwards: for
30 /// measuring durations.
31 fn monotonic_ns :: -> Int
32}
33
34/// An instant: nanoseconds since 1970-01-01T00:00:00Z (before it when
35/// negative). Shown in RFC 3339.
36@derive Eq Ord Hash
37pub opaque type Timestamp { Timestamp(Int) }
38
39/// A span of time, in nanoseconds (negative when going back).
40@derive Eq Ord Hash
41pub opaque type Duration { Duration(Int) }
42
43/// The current time.
44pub fn now :: -> Timestamp / <clock>
45{
46 Timestamp(now_unix_ns ())
47}
48
49/// The time on the monotonic clock: compare two to measure a duration.
50pub fn monotonic :: -> Duration / <clock>
51{
52 Duration(monotonic_ns ())
53}
54
55/// The instant `ns` nanoseconds after the Unix epoch.
56pub fn from_unix_ns :: ns: Int -> Timestamp
57{
58 Timestamp(ns)
59}
60
61/// The instant `ms` milliseconds after the Unix epoch.
62pub fn from_unix_ms :: ms: Int -> Timestamp
63{
64 Timestamp(ms * 1000000)
65}
66
67/// Nanoseconds since the Unix epoch.
68pub fn unix_ns :: t: Timestamp -> Int
69{
70 match t { Timestamp(ns) -> ns }
71}
72
73/// Milliseconds since the Unix epoch, rounded down.
74pub fn unix_ms :: t: Timestamp -> Int
75{
76 floor_div (unix_ns t) 1000000
77}
78
79pub fn nanoseconds :: n: Int -> Duration
80{
81 Duration(n)
82}
83pub fn milliseconds :: n: Int -> Duration
84{
85 Duration(n * 1000000)
86}
87pub fn seconds :: n: Int -> Duration
88{
89 Duration(n * 1000000000)
90}
91pub fn minutes :: n: Int -> Duration
92{
93 Duration(n * 60000000000)
94}
95
96/// The duration in nanoseconds.
97pub fn in_nanoseconds :: d: Duration -> Int
98{
99 match d { Duration(ns) -> ns }
100}
101
102/// The duration in milliseconds, rounded down.
103pub fn in_milliseconds :: d: Duration -> Int
104{
105 floor_div (in_nanoseconds d) 1000000
106}
107
108/// `t` moved by `d`.
109pub fn add :: t: Timestamp d: Duration -> Timestamp
110{
111 Timestamp(unix_ns t + in_nanoseconds d)
112}
113
114/// The time from `earlier` to `later` (negative if `later` is before).
115pub fn since :: later: Timestamp earlier: Timestamp -> Duration
116{
117 Duration(unix_ns later - unix_ns earlier)
118}
119
120/// The time from monotonic reading `start` to `end`.
121pub fn elapsed :: end: Duration start: Duration -> Duration
122{
123 Duration(in_nanoseconds end - in_nanoseconds start)
124}
125
126/// Run `action` with `now()` always `at`, and `monotonic()` always 0.
127pub fn with_fixed_clock ::
128 at: Timestamp
129 action: fn() -> a / <clock | e>
130 -> a / <e>
131{
132 handle
133 {
134 action ()
135 }
136 with
137 { now_unix_ns -> unix_ns at, monotonic_ns -> 0 }
138}
139
140// ---- UTC calendar ------------------------------------------------------------------
141
142/// A date and time in UTC.
143@derive Eq Debug
144pub type DateTime
145{ DateTime(
146 year: Int
147 , month: Int
148 , day: Int
149 , hour: Int
150 , minute: Int
151 , second: Int
152 , nanosecond: Int
153 )
154}
155
156/// `t`'s date and time in UTC.
157pub fn to_utc :: t: Timestamp -> DateTime
158{
159 let ns = unix_ns t
160 let days = floor_div ns 86400000000000
161 let in_day = ns - days * 86400000000000
162 let (year, month, day) = civil_from_days days
163 let secs = in_day / 1000000000
164 DateTime( year
165 , month
166 , day
167 , secs / 3600
168 , secs / 60 % 60
169 , secs % 60
170 , in_day % 1000000000
171 )
172}
173
174/// The instant of a UTC date and time; `None` if a field is out of range
175/// (February 30, hour 24, second 60...).
176pub fn from_utc :: dt: DateTime -> Option<Timestamp>
177{
178 match dt
179 { DateTime
180 ( y
181 , mo
182 , d
183 , h
184 , mi
185 , s
186 , ns
187 ) -> if mo < 1 || mo > 12 || d < 1 || d > days_in_month y mo || h < 0
188 || h > 23
189 || mi < 0
190 || mi > 59
191 || s < 0
192 || s > 59
193 || ns < 0
194 || ns > 999999999
195 {
196 None
197 }
198 else
199 {
200 Some( Timestamp( ((days_from_civil y mo d * 24 + h) * 60 + mi)
201 * 60000000000
202 + s * 1000000000
203 + ns
204 )
205 )
206 }
207 }
208}
209
210/// Days since 1970-01-01 of a proleptic Gregorian date (Howard Hinnant's
211/// `days_from_civil`).
212fn days_from_civil :: y0: Int m: Int d: Int -> Int
213{
214 let y = if m <= 2 { y0 - 1 } else { y0 }
215 let era = floor_div y 400
216 let yoe = y - era * 400
217 let mp = if m > 2 { m - 3 } else { m + 9 }
218 let doy = (153 * mp + 2) / 5 + d - 1
219 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy
220 era * 146097 + doe - 719468
221}
222
223/// The date of a day number since 1970-01-01 (Hinnant's `civil_from_days`).
224fn civil_from_days :: z0: Int -> (Int, Int, Int)
225{
226 let z = z0 + 719468
227 let era = floor_div z 146097
228 let doe = z - era * 146097
229 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365
230 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100)
231 let mp = (5 * doy + 2) / 153
232 let d = doy - (153 * mp + 2) / 5 + 1
233 let m = if mp < 10 { mp + 3 } else { mp - 9 }
234 let y = yoe + era * 400
235 (if m <= 2 { y + 1 } else { y }, m, d)
236}
237
238fn is_leap :: y: Int -> Bool
239{
240 y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)
241}
242
243fn days_in_month :: y: Int m: Int -> Int
244{
245 match m
246 { 2 -> if is_leap y { 29 } else { 28 }, 4 | 6 | 9 | 11 -> 30, _ -> 31 }
247}
248
249/// `a / b` rounded towards minus infinity (`/` truncates), for `b > 0`.
250fn floor_div :: a: Int b: Int -> Int
251{
252 let q = a / b
253 if a % b < 0
254 {
255 q - 1
256 }
257 else
258 {
259 q
260 }
261}
262
263// ---- RFC 3339 ----------------------------------------------------------------------
264
265/// `t` in RFC 3339, in UTC: `2026-10-13T09:30:00Z`, with 3, 6 or 9
266/// fraction digits when they aren't zero. Years outside 0–9999 use the
267/// expanded form (`+10000-01-01T00:00:00Z`).
268pub fn format :: t: Timestamp -> String
269{
270 match to_utc t
271 { DateTime
272 ( y
273 , mo
274 , d
275 , h
276 , mi
277 , s
278 , ns
279 ) -> "{year y}-{pad mo 2}-{pad d 2}T{pad h 2}:{pad mi 2}:{pad s 2}{fraction ns}Z"
280 }
281}
282
283fn year :: y: Int -> String
284{
285 if y >= 0 && y <= 9999
286 {
287 pad y 4
288 }
289 else if y < 0
290 {
291 "-{pad (-y) 5}"
292 }
293 else
294 {
295 "+{pad y 5}"
296 }
297}
298
299fn fraction :: ns: Int -> String
300{
301 if ns == 0
302 {
303 ""
304 }
305 else if ns % 1000000 == 0
306 {
307 ".{pad (ns / 1000000) 3}"
308 }
309 else if ns % 1000 == 0
310 {
311 ".{pad (ns / 1000) 6}"
312 }
313 else
314 {
315 ".{pad ns 9}"
316 }
317}
318
319/// `n` (not negative) with zeros in front, to `width` digits at least.
320fn pad :: n: Int width: Int -> String
321{
322 let digits = show n
323 "{string.repeat "0" (width - string.length digits)}{digits}"
324}
325
326/// An RFC 3339 date and time, converted to UTC: `2026-10-13T11:30:00+02:00`.
327/// Accepts `T`, `t` or a space between date and time, 1 to 9 fraction
328/// digits (more are cut), and `Z`, `z` or `±HH:MM`. Years have 4 digits;
329/// a leap second (`:60`) is refused.
330pub fn parse :: text: String -> Result<Timestamp, String>
331{
332 let b = bytes.from_string text
333 let fail = Error("not an RFC 3339 date and time: {text:?}")
334 match ( digits b 0 4
335 , digits b 5 2
336 , digits b 8 2
337 , digits b 11 2
338 , digits b 14 2
339 , digits b 17 2
340 )
341 { ( Some(y)
342 , Some(mo)
343 , Some(d)
344 , Some(h)
345 , Some(mi)
346 , Some(s)
347 ) -> if !( at b 4 "-" && at b 7 "-"
348 && (at b 10 "T" || at b 10 "t" || at b 10 " ")
349 && at b 13 ":"
350 && at b 16 ":"
351 )
352 {
353 fail
354 }
355 else
356 {
357 let (ns, i) = fraction_at b 19
358 match (offset_at b i, from_utc DateTime(y, mo, d, h, mi, s, ns))
359 { (Some(off), Some(t)) -> Ok(add t (minutes (-off))), _ -> fail }
360 }
361 , _ -> fail
362 }
363}
364
365/// The `n`-digit number at byte `i`, if there is one.
366fn digits :: b: Bytes i: Int n: Int -> Option<Int>
367{
368 digits_from b i n 0
369}
370
371fn digits_from :: b: Bytes i: Int n: Int acc: Int -> Option<Int>
372{
373 if n == 0
374 {
375 Some(acc)
376 }
377 else
378 {
379 match bytes.get b i
380 { Some(c) if c >= 48 && c <= 57 ->
381 digits_from b (i + 1) (n - 1) (acc * 10 + c - 48)
382 , _ -> None
383 }
384 }
385}
386
387/// Whether byte `i` is `c` (one ASCII character).
388fn at :: b: Bytes i: Int c: String -> Bool
389{
390 bytes.get b i == bytes.get (bytes.from_string c) 0
391}
392
393/// A fraction `.ddd` at byte `i`: nanoseconds, and where it ends.
394fn fraction_at :: b: Bytes i: Int -> (Int, Int)
395{
396 if at b i "."
397 {
398 fraction_digits b (i + 1) 0 0
399 }
400 else
401 {
402 (0, i)
403 }
404}
405
406fn fraction_digits :: b: Bytes i: Int n: Int acc: Int -> (Int, Int)
407{
408 match bytes.get b i
409 { Some(c) if c >= 48 && c <= 57 -> if n < 9
410 {
411 fraction_digits b (i + 1) (n + 1) (acc * 10 + c - 48)
412 }
413 else
414 {
415 fraction_digits b (i + 1) n acc
416 }
417 , _ -> (acc * power10 (9 - n), if n == 0 { i - 1 } else { i })
418 }
419}
420
421fn power10 :: n: Int -> Int
422{
423 if n == 0
424 {
425 1
426 }
427 else
428 {
429 10 * power10 (n - 1)
430 }
431}
432
433/// The offset at byte `i`, in minutes east of UTC, if the text ends with
434/// it.
435fn offset_at :: b: Bytes i: Int -> Option<Int>
436{
437 if (at b i "Z" || at b i "z") && bytes.length b == i + 1
438 {
439 Some(0)
440 }
441 else if (at b i "+" || at b i "-") && at b (i + 3) ":"
442 && bytes.length b == i + 6
443 {
444 match (digits b (i + 1) 2, digits b (i + 4) 2)
445 { (Some(h), Some(m)) if h <= 23 && m <= 59 ->
446 Some(if at b i "-" { -(h * 60 + m) } else { h * 60 + m })
447 , _ -> None
448 }
449 }
450 else
451 {
452 None
453 }
454}
455
456impl Show<Timestamp>
457{
458 fn show :: t
459 {
460 format t
461 }
462}
463
464impl Debug<Timestamp>
465{
466 fn debug :: t
467 {
468 "time.Timestamp({format t})"
469 }
470}
471
472/// In the largest unit that keeps it exact: `2s`, `1500ms`, `3us`,
473/// `7ns`.
474impl Show<Duration>
475{
476 fn show :: d
477 {
478 let ns = in_nanoseconds d
479 if ns % 1000000000 == 0
480 {
481 "{ns / 1000000000}s"
482 }
483 else if ns % 1000000 == 0
484 {
485 "{ns / 1000000}ms"
486 }
487 else if ns % 1000 == 0
488 {
489 "{ns / 1000}us"
490 }
491 else
492 {
493 "{ns}ns"
494 }
495 }
496}
497
498impl Debug<Duration>
499{
500 fn debug :: d
501 {
502 "time.Duration({show d})"
503 }
504}