1use std::sync::OnceLock;
7use std::sync::atomic::{AtomicU64, Ordering};
8
9use time::{Duration, Instant, SystemTime, UNIX_EPOCH};
10
11#[cfg(feature = "local")]
15pub mod local {
16 use jiff::civil::{Date, DateTime};
17 use jiff::{Timestamp, Zoned};
18
19 #[derive(Clone, Debug)]
21 pub struct Zone(platform::Zone);
22
23 impl Zone {
24 #[must_use]
27 pub fn here() -> Self {
28 if let Some(zone) = told::installed() {
29 return zone;
30 }
31 Self(platform::Zone::here())
32 }
33
34 #[must_use]
38 pub fn named(name: &str) -> Option<Self> {
39 if !crate::is_zone_name(name) {
40 return None;
41 }
42 #[cfg(all(target_family = "wasm", not(tilo_no_js)))]
43 {
44 platform::Zone::named(name).map(Self)
45 }
46 #[cfg(any(not(target_family = "wasm"), tilo_no_js))]
47 {
48 jiff::tz::TimeZone::get(name)
49 .ok()
50 .map(|zone| Self(platform::Zone::of(zone)))
51 }
52 }
53
54 #[cfg(not(target_family = "wasm"))]
57 #[must_use]
58 pub fn from_tzif(name: &str, data: &[u8]) -> Option<Self> {
59 jiff::tz::TimeZone::tzif(name, data).ok().map(Self::of)
60 }
61
62 #[cfg(not(target_family = "wasm"))]
64 #[must_use]
65 pub fn of(zone: jiff::tz::TimeZone) -> Self {
66 Self(platform::Zone::of(zone))
67 }
68
69 #[must_use]
72 pub fn at(&self, at: Timestamp) -> Zoned {
73 self.0.at(at)
74 }
75
76 #[must_use]
78 pub fn name(&self) -> Option<String> {
79 self.0.name()
80 }
81
82 #[must_use]
85 pub fn instant_of(&self, local: DateTime) -> Option<Timestamp> {
86 self.0.instant_of(local)
87 }
88 }
89
90 pub use told::install;
91 #[cfg(not(target_family = "wasm"))]
92 pub use zone_data::tzif;
93
94 #[must_use]
97 pub fn zone_names() -> Vec<String> {
98 #[cfg(all(target_family = "wasm", not(tilo_no_js)))]
99 let mut names = crate::page::zone_names();
100 #[cfg(any(not(target_family = "wasm"), tilo_no_js))]
101 let mut names: Vec<String> = jiff::tz::db()
102 .available()
103 .map(|name| name.as_str().to_owned())
104 .filter(|name| crate::is_zone_name(name))
105 .collect();
106 names.sort();
107 names.dedup();
108 names
109 }
110
111 mod told {
115 use std::cell::RefCell;
116
117 use super::Zone;
118
119 thread_local! {
120 static INSTALLED: RefCell<Option<Zone>> = const { RefCell::new(None) };
122 }
123
124 pub(super) fn installed() -> Option<Zone> {
125 INSTALLED.with(|installed| installed.borrow().clone())
126 }
127
128 pub fn install(zone: Option<Zone>) {
132 INSTALLED.with(|installed| *installed.borrow_mut() = zone);
133 }
134 }
135
136 #[cfg(not(target_family = "wasm"))]
139 mod zone_data {
140 use std::collections::HashMap;
141 use std::path::PathBuf;
142 use std::sync::{Arc, Mutex, PoisonError};
143
144 use super::Zone;
145
146 type Read = HashMap<String, Option<Arc<[u8]>>>;
148 static READ: Mutex<Option<Read>> = Mutex::new(None);
149
150 const MAX_REMEMBERED: usize = 1_024;
152
153 #[must_use]
157 pub fn tzif(name: &str) -> Option<Arc<[u8]>> {
158 if !crate::is_zone_name(name) {
159 return None;
160 }
161 let known = READ
162 .lock()
163 .unwrap_or_else(PoisonError::into_inner)
164 .as_ref()
165 .and_then(|read| read.get(name).cloned());
166 if let Some(known) = known {
167 return known;
168 }
169 let found = databases()
170 .iter()
171 .find_map(|database| std::fs::read(database.join(name)).ok())
172 .filter(|data| Zone::from_tzif(name, data).is_some())
173 .map(Arc::<[u8]>::from);
174 let mut remembered = READ.lock().unwrap_or_else(PoisonError::into_inner);
175 let read = remembered.get_or_insert_with(HashMap::new);
176 if read.len() >= MAX_REMEMBERED {
177 read.clear();
178 }
179 read.insert(name.to_owned(), found.clone());
180 drop(remembered);
181 found
182 }
183
184 fn databases() -> Vec<PathBuf> {
186 let mut databases: Vec<PathBuf> = std::env::var_os("TZDIR")
187 .map(PathBuf::from)
188 .filter(|dir| dir.is_absolute())
189 .into_iter()
190 .collect();
191 databases.extend(
192 [
193 "/usr/share/zoneinfo",
194 "/usr/share/lib/zoneinfo",
195 "/etc/zoneinfo",
196 ]
197 .into_iter()
198 .map(PathBuf::from),
199 );
200 databases
201 }
202
203 #[cfg(test)]
204 mod tests {
205 use super::tzif;
206 use crate::is_zone_name;
207
208 #[test]
209 fn only_a_zones_name_is_read() {
210 assert!(is_zone_name("Pacific/Auckland"));
211 assert!(is_zone_name("America/Argentina/Buenos_Aires"));
212 assert!(is_zone_name("Etc/GMT+12"));
213 assert!(is_zone_name("UTC"));
214 assert!(!is_zone_name(""));
215 assert!(!is_zone_name("/etc/passwd"));
216 assert!(!is_zone_name("../../etc/passwd"));
217 assert!(!is_zone_name("Europe/../../x"));
218 assert!(!is_zone_name("Europe//Vienna"));
219 assert!(!is_zone_name("Europe/Vi enna"));
220 assert!(tzif("../../etc/passwd").is_none());
221 }
222
223 #[test]
225 fn a_zone_read_from_its_data_is_the_databases() {
226 let Some(data) = tzif("Pacific/Auckland") else {
227 return;
229 };
230 let zone = super::Zone::from_tzif("Pacific/Auckland", &data).unwrap();
231 let at = jiff::Timestamp::from_second(1_773_583_500).unwrap();
232 assert_eq!(zone.name().as_deref(), Some("Pacific/Auckland"));
233 assert_eq!(
234 zone.at(at).offset().seconds(),
235 13 * 3600,
236 "summer in Auckland"
237 );
238 }
239 }
240 }
241
242 #[must_use]
244 pub fn now_instant() -> Timestamp {
245 Timestamp::try_from(crate::to_std(crate::wall())).unwrap_or(Timestamp::UNIX_EPOCH)
246 }
247
248 #[must_use]
250 pub fn now() -> Zoned {
251 at(now_instant())
252 }
253
254 #[must_use]
256 pub fn at(at: Timestamp) -> Zoned {
257 Zone::here().at(at)
258 }
259
260 #[must_use]
262 pub fn today() -> Date {
263 now().date()
264 }
265
266 #[must_use]
268 pub fn instant_of(local: DateTime) -> Option<Timestamp> {
269 Zone::here().instant_of(local)
270 }
271
272 #[cfg(any(test, all(target_family = "wasm", not(tilo_no_js))))]
276 fn resolve(
277 local: DateTime,
278 offset_at: impl Fn(Timestamp) -> jiff::tz::Offset,
279 ) -> Option<Timestamp> {
280 const A_DAY: jiff::SignedDuration = jiff::SignedDuration::from_hours(26);
282 let bare = local.to_zoned(jiff::tz::TimeZone::UTC).ok()?.timestamp();
283 let around = [
284 bare.checked_sub(A_DAY).ok()?,
285 bare,
286 bare.checked_add(A_DAY).ok()?,
287 ];
288 let instants = around.map(|instant| {
289 let offset = offset_at(instant);
290 bare.checked_sub(jiff::SignedDuration::from_secs(i64::from(offset.seconds())))
291 .ok()
292 });
293 instants
294 .into_iter()
295 .flatten()
296 .filter(|at| read(*at, &offset_at).datetime() == local)
297 .min()
298 }
299
300 #[cfg(any(test, all(target_family = "wasm", not(tilo_no_js))))]
302 fn read(at: Timestamp, offset_at: impl Fn(Timestamp) -> jiff::tz::Offset) -> Zoned {
303 at.to_zoned(jiff::tz::TimeZone::fixed(offset_at(at)))
304 }
305
306 #[cfg(any(not(target_family = "wasm"), tilo_no_js))]
308 mod platform {
309 use jiff::civil::DateTime;
310 use jiff::tz::{AmbiguousOffset, TimeZone};
311 use jiff::{Timestamp, Zoned};
312
313 #[derive(Clone, Debug)]
314 pub(super) struct Zone(TimeZone);
315
316 impl Zone {
317 pub(super) fn here() -> Self {
318 Self(TimeZone::system())
319 }
320
321 pub(super) fn of(zone: TimeZone) -> Self {
322 Self(zone)
323 }
324
325 pub(super) fn at(&self, at: Timestamp) -> Zoned {
326 at.to_zoned(self.0.clone())
327 }
328
329 pub(super) fn name(&self) -> Option<String> {
330 self.0.iana_name().map(str::to_owned)
331 }
332
333 pub(super) fn instant_of(&self, local: DateTime) -> Option<Timestamp> {
334 let named = self.0.to_ambiguous_timestamp(local);
335 if matches!(named.offset(), AmbiguousOffset::Gap { .. }) {
336 return None;
337 }
338 named.earlier().ok()
339 }
340 }
341 }
342
343 #[cfg(all(target_family = "wasm", not(tilo_no_js)))]
346 mod platform {
347 use std::rc::Rc;
348
349 use jiff::civil::DateTime;
350 use jiff::tz::Offset;
351 use jiff::{Timestamp, Zoned};
352
353 type Offsets = Box<dyn Fn(i64) -> Option<i32>>;
355
356 #[derive(Clone)]
357 pub(super) enum Zone {
358 Browser,
360 Named(Rc<(String, Offsets)>),
362 }
363
364 impl std::fmt::Debug for Zone {
365 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
366 match self {
367 Self::Browser => f.write_str("Browser"),
368 Self::Named(named) => f.debug_tuple("Named").field(&named.0).finish(),
369 }
370 }
371 }
372
373 impl Zone {
374 pub(super) const fn here() -> Self {
375 Self::Browser
376 }
377
378 pub(super) fn named(name: &str) -> Option<Self> {
379 let offsets = crate::page::zone_offsets(name)?;
380 Some(Self::Named(Rc::new((name.to_owned(), Box::new(offsets)))))
381 }
382
383 pub(super) fn at(&self, at: Timestamp) -> Zoned {
384 super::read(at, |at| self.offset(at))
385 }
386
387 pub(super) fn name(&self) -> Option<String> {
388 match self {
389 Self::Browser => crate::page::zone_name(),
390 Self::Named(named) => Some(named.0.clone()),
391 }
392 }
393
394 pub(super) fn instant_of(&self, local: DateTime) -> Option<Timestamp> {
395 super::resolve(local, |at| self.offset(at))
396 }
397
398 fn offset(&self, at: Timestamp) -> Offset {
400 let seconds = match self {
401 Self::Browser => Some(crate::page::offset_seconds(at.as_millisecond())),
402 Self::Named(named) => (named.1)(at.as_millisecond()),
403 };
404 seconds
405 .and_then(|seconds| Offset::from_seconds(seconds).ok())
406 .unwrap_or(Offset::UTC)
407 }
408 }
409 }
410
411 #[cfg(test)]
412 mod tests {
413 use jiff::Timestamp;
414 use jiff::civil::{Date, DateTime, Time};
415 use jiff::tz::{Offset, TimeZone};
416
417 use super::{read, resolve};
418
419 fn instant(local: DateTime) -> Timestamp {
421 local
422 .to_zoned(TimeZone::UTC)
423 .expect("the test's wall times are inside the calendar")
424 .timestamp()
425 }
426
427 fn spring() -> Timestamp {
429 instant(Date::new(2026, 3, 29).unwrap().at(1, 0, 0, 0))
430 }
431
432 fn autumn() -> Timestamp {
434 instant(Date::new(2026, 10, 25).unwrap().at(1, 0, 0, 0))
435 }
436
437 fn offsets(at: Timestamp) -> Offset {
439 if (spring()..autumn()).contains(&at) {
440 jiff::tz::offset(2)
441 } else {
442 jiff::tz::offset(1)
443 }
444 }
445
446 fn wall(at: Timestamp) -> DateTime {
447 read(at, offsets).datetime()
448 }
449
450 fn seconds(at: Timestamp) -> i64 {
451 at.as_second()
452 }
453
454 #[test]
455 fn a_clock_reads_local_on_each_side_of_a_change_of_clocks() {
456 let before = spring()
457 .checked_sub(jiff::SignedDuration::from_secs(1))
458 .unwrap();
459 assert_eq!((wall(before).hour(), wall(before).minute()), (1, 59));
460 assert_eq!(read(before, offsets).offset().seconds(), 3600);
461 assert_eq!(
462 (wall(spring()).hour(), wall(spring()).minute()),
463 (3, 0),
464 "02:00 is skipped"
465 );
466 assert_eq!(read(spring(), offsets).offset().seconds(), 7200);
467 let before = autumn()
468 .checked_sub(jiff::SignedDuration::from_secs(1))
469 .unwrap();
470 assert_eq!(read(before, offsets).offset().seconds(), 7200);
471 assert_eq!((wall(before).hour(), wall(before).minute()), (2, 59));
472 assert_eq!(wall(autumn()).hour(), 2, "02:00 comes twice");
473 assert_eq!(read(autumn(), offsets).offset().seconds(), 3600);
474 }
475
476 #[test]
479 fn a_zone_is_read_by_its_name_and_a_thread_told_it_reads_there() {
480 let Some(vienna) = super::Zone::named("Europe/Vienna") else {
481 return;
483 };
484 assert!(
485 super::zone_names()
486 .iter()
487 .any(|name| name == "Europe/Vienna")
488 );
489 assert!(super::Zone::named("../../etc/passwd").is_none());
490 assert!(super::Zone::named("Nowhere/Atlantis").is_none());
491 let winter = instant(Date::new(2026, 1, 15).unwrap().at(12, 0, 0, 0));
492 assert_eq!(vienna.at(winter).offset().seconds(), 3600);
493 std::thread::spawn(move || {
494 super::install(Some(vienna));
495 assert_eq!(super::Zone::here().name().as_deref(), Some("Europe/Vienna"));
496 assert_eq!(super::at(winter).datetime().hour(), 13);
497 super::install(None);
498 assert!(super::told::installed().is_none());
499 })
500 .join()
501 .unwrap();
502 }
503
504 #[test]
505 fn a_wall_time_the_clocks_skipped_names_no_instant() {
506 let skipped = Date::new(2026, 3, 29).unwrap().at(2, 30, 0, 0);
507 assert_eq!(resolve(skipped, offsets), None);
508 }
509
510 #[test]
511 fn a_wall_time_the_clocks_passed_twice_names_the_earlier_instant() {
512 let twice = Date::new(2026, 10, 25).unwrap().at(2, 30, 0, 0);
513 let at = resolve(twice, offsets).expect("02:30 stands twice");
514 assert_eq!(wall(at), twice, "the earlier one still reads 02:30");
515 assert_eq!(
516 seconds(at),
517 seconds(autumn()) - 1800,
518 "at +2, before the change"
519 );
520 }
521
522 #[test]
523 fn a_wall_time_away_from_a_change_names_its_one_instant() {
524 let noon = Date::new(2026, 7, 1).unwrap().at(12, 0, 0, 0);
525 let at = resolve(noon, offsets).expect("noon of a July day stands once");
526 assert_eq!(wall(at), noon);
527 assert_eq!(at.as_second() % 60, 0);
528 let midnight = Date::new(2026, 1, 1).unwrap().to_datetime(Time::midnight());
529 assert_eq!(
530 read(resolve(midnight, offsets).unwrap(), offsets).datetime(),
531 midnight
532 );
533 }
534
535 #[test]
538 fn the_wall_clock_is_one_reading_as_an_instant_and_in_the_persons_zone() {
539 tilo_test_env::in_own_process(
540 module_path!(),
541 "the_wall_clock_is_one_reading_as_an_instant_and_in_the_persons_zone",
542 || {
543 let held = crate::UNIX_EPOCH + crate::time::Duration::from_secs(1_791_086_040);
545 let _held = crate::testing::hold_wall_everywhere(
546 crate::testing::OwnProcess::of_a_test_in_its_own_process(),
547 held,
548 );
549 let instant = super::now_instant();
550 assert_eq!(instant.as_second(), 1_791_086_040);
551 assert_eq!(
552 super::now().timestamp(),
553 instant,
554 "the local reading is that instant"
555 );
556 assert_eq!(
557 super::at(instant),
558 super::now(),
559 "and the instant reads back as the same local time"
560 );
561 },
562 );
563 }
564 }
565}
566
567pub mod time {
570 pub use crate::imp::{Duration, Instant, SystemTime, SystemTimeError, UNIX_EPOCH};
571}
572
573#[cfg(any(not(target_family = "wasm"), tilo_no_js))]
574mod imp {
575 pub use std::time::{Duration, Instant, SystemTime, SystemTimeError, UNIX_EPOCH};
576
577 #[inline]
578 pub const fn to_std(time: SystemTime) -> std::time::SystemTime {
579 time
580 }
581
582 #[inline]
583 pub const fn from_std(time: std::time::SystemTime) -> SystemTime {
584 time
585 }
586}
587
588#[cfg(all(target_family = "wasm", not(tilo_no_js)))]
589mod imp {
590 pub use web_time::{Duration, Instant, SystemTime, SystemTimeError, UNIX_EPOCH};
591
592 pub fn to_std(time: SystemTime) -> std::time::SystemTime {
593 let converted = match time.duration_since(UNIX_EPOCH) {
594 Ok(after) => std::time::UNIX_EPOCH.checked_add(after),
595 Err(before) => std::time::UNIX_EPOCH.checked_sub(before.duration()),
596 };
597 converted.unwrap_or(std::time::UNIX_EPOCH)
598 }
599
600 pub fn from_std(time: std::time::SystemTime) -> SystemTime {
601 let converted = match time.duration_since(std::time::UNIX_EPOCH) {
602 Ok(after) => UNIX_EPOCH.checked_add(after),
603 Err(before) => UNIX_EPOCH.checked_sub(before.duration()),
604 };
605 converted.unwrap_or(UNIX_EPOCH)
606 }
607}
608
609#[allow(
613 clippy::disallowed_methods,
614 reason = "off the page this crate is where std's monotonic clock is read"
615)]
616#[must_use]
617#[inline]
618pub fn now() -> Instant {
619 #[cfg(any(test, feature = "test-support"))]
620 if let Some(at) = testing::monotonic_override() {
621 return at;
622 }
623 Instant::now()
624}
625
626#[cfg(any(test, feature = "test-support"))]
627pub mod testing {
628 use super::time::{Instant, SystemTime};
629 use std::cell::Cell;
630
631 thread_local! {
632 static MONOTONIC: Cell<Option<Instant>> = const { Cell::new(None) };
633 }
634
635 pub(super) fn monotonic_override() -> Option<Instant> {
636 MONOTONIC.with(Cell::get)
637 }
638
639 struct Restore(Option<Instant>);
640
641 impl Drop for Restore {
642 fn drop(&mut self) {
643 MONOTONIC.with(|clock| clock.set(self.0));
644 }
645 }
646
647 pub fn with_monotonic_time<T>(at: Instant, operation: impl FnOnce() -> T) -> T {
648 let _restore = Restore(MONOTONIC.with(|clock| clock.replace(Some(at))));
649 operation()
650 }
651
652 struct RestoreWall(Option<u64>);
653
654 impl Drop for RestoreWall {
655 fn drop(&mut self) {
656 super::FROZEN_HERE_MS.with(|here| here.set(self.0));
657 }
658 }
659
660 #[derive(Clone, Copy)]
664 pub struct OwnProcess(());
665
666 impl OwnProcess {
667 #[doc(hidden)]
668 #[must_use]
669 pub const fn of_a_test_in_its_own_process() -> Self {
670 Self(())
671 }
672 }
673
674 pub struct WallHold {
676 _process: OwnProcess,
677 pinned: std::sync::Arc<super::AtomicU64>,
678 replaced: Option<std::sync::Arc<super::AtomicU64>>,
679 }
680
681 impl Drop for WallHold {
682 fn drop(&mut self) {
683 let mut process = super::PROCESS
684 .lock()
685 .unwrap_or_else(std::sync::PoisonError::into_inner);
686 if process
687 .as_ref()
688 .is_some_and(|pin| std::sync::Arc::ptr_eq(pin, &self.pinned))
689 {
690 *process = self.replaced.take();
691 }
692 }
693 }
694
695 pub fn hold_wall_everywhere(process: OwnProcess, at: SystemTime) -> WallHold {
698 let pinned = std::sync::Arc::new(super::AtomicU64::new(super::wall_ms(at)));
699 let replaced = super::PROCESS
701 .lock()
702 .unwrap_or_else(std::sync::PoisonError::into_inner)
703 .replace(pinned.clone());
704 WallHold {
705 _process: process,
706 pinned,
707 replaced,
708 }
709 }
710
711 thread_local! {
712 static FOLLOWED: std::cell::RefCell<Option<std::sync::Arc<std::sync::atomic::AtomicU64>>> =
713 const { std::cell::RefCell::new(None) };
714 }
715
716 pub(super) fn followed_ms() -> u64 {
717 FOLLOWED.with(|followed| {
718 followed
719 .borrow()
720 .as_ref()
721 .map_or(0, |wall| wall.load(std::sync::atomic::Ordering::Relaxed))
722 })
723 }
724
725 #[derive(Clone, Debug, Default)]
728 pub struct SharedWall(std::sync::Arc<std::sync::atomic::AtomicU64>);
729
730 impl SharedWall {
731 pub fn follow(&self) {
734 FOLLOWED.with(|followed| *followed.borrow_mut() = Some(self.0.clone()));
735 }
736
737 pub fn pin(&self, at: SystemTime) {
738 self.0
739 .store(super::wall_ms(at), std::sync::atomic::Ordering::Relaxed);
740 }
741
742 pub fn release(&self) {
743 self.0.store(0, std::sync::atomic::Ordering::Relaxed);
744 }
745 }
746
747 pub fn with_wall<T>(at: SystemTime, operation: impl FnOnce() -> T) -> T {
750 let ms = super::wall_ms(at);
751 let _restore = RestoreWall(super::FROZEN_HERE_MS.with(|here| here.replace(Some(ms))));
752 operation()
753 }
754}
755
756#[cfg(test)]
757mod scoped_monotonic_tests {
758 use super::*;
759
760 tilo_test_env::scenario! {
761 fn a_held_clock_is_the_holding_threads_alone_and_ends_with_its_scope;
762
763 phase a_shared_wall_pins_the_threads_following_it_until_released;
764 {
765 const PINNED: u64 = 123_456;
766 let wall = testing::SharedWall::default();
767 let follower = {
768 let wall = wall.clone();
769 move || {
770 wall.follow();
771 unix_now()
772 }
773 };
774 assert_ne!(std::thread::spawn(follower.clone()).join().unwrap(), PINNED);
775 wall.pin(UNIX_EPOCH + Duration::from_secs(PINNED));
776 assert_eq!(std::thread::spawn(follower.clone()).join().unwrap(), PINNED);
777 assert_ne!(
778 unix_now(),
779 PINNED,
780 "a thread following none keeps its clock"
781 );
782 wall.release();
783 assert_ne!(std::thread::spawn(follower).join().unwrap(), PINNED);
784 }
785
786 phase scoped_time_is_thread_local_nested_and_restored_after_unwind;
787 {
788 let at = now().checked_add(Duration::from_secs(60)).unwrap();
789 testing::with_monotonic_time(at, || {
790 assert_eq!(now(), at);
791 let later = at.checked_add(Duration::from_secs(1)).unwrap();
792 testing::with_monotonic_time(later, || assert_eq!(now(), later));
793 assert_eq!(now(), at);
794 assert!(std::thread::spawn(now).join().unwrap() < at);
795 let panicked = std::panic::catch_unwind(|| {
796 testing::with_monotonic_time(later, || panic!("unwind the clock scope"));
797 });
798 assert!(panicked.is_err());
799 assert_eq!(now(), at);
800 });
801 assert!(now() < at);
802 }
803
804 phase scoped_wall_time_is_thread_local_nested_and_restored_after_unwind;
805 {
806 let at = UNIX_EPOCH + Duration::from_secs(4_000_000_000);
807 testing::with_wall(at, || {
808 assert_eq!(wall(), at);
809 let later = at + Duration::from_secs(3);
810 testing::with_wall(later, || assert_eq!(wall(), later));
811 assert_eq!(wall(), at);
812 assert!(std::thread::spawn(wall).join().unwrap() < at);
813 let panicked = std::panic::catch_unwind(|| {
814 testing::with_wall(later, || panic!("unwind the clock scope"));
815 });
816 assert!(panicked.is_err());
817 assert_eq!(wall(), at);
818 });
819 assert!(wall() < at);
820 }
821
822 phase a_clock_lent_at_the_epoch_is_a_clock_the_code_reads;
823 {
824 let (ms, held, frozen) = with_wall_ms(0, || (unix_now_ms(), wall(), wall_frozen()));
828 assert_eq!(ms, 0, "the lent time is the time the code reads");
829 assert_eq!(held, UNIX_EPOCH);
830 assert!(frozen, "a hold at the epoch is a hold");
831 assert!(
832 unix_now_ms() > 0,
833 "the thread's own clock runs again after the hold"
834 );
835 }
836
837 phase two_threads_holding_different_wall_times_at_once_each_read_their_own;
838 {
839 let first = UNIX_EPOCH + Duration::from_secs(4_000_000_000);
840 let second = UNIX_EPOCH + Duration::from_secs(4_100_000_000);
841 let together = std::sync::Arc::new(std::sync::Barrier::new(2));
842 let hold = |at: SystemTime, other: SystemTime| {
843 let together = std::sync::Arc::clone(&together);
844 std::thread::spawn(move || {
845 testing::with_wall(at, || {
846 together.wait();
847 assert_eq!(wall(), at);
848 assert_ne!(wall(), other);
849 together.wait();
850 });
851 together.wait();
852 assert!(wall() < first, "the hold ended with its scope");
853 })
854 };
855 let threads = [hold(first, second), hold(second, first)];
856 for thread in threads {
857 thread.join().unwrap();
858 }
859 }
860 }
861}
862
863thread_local! {
864 static FROZEN_HERE_MS: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
866}
867
868fn frozen_ms() -> Option<u64> {
869 match FROZEN_HERE_MS.with(std::cell::Cell::get) {
870 Some(here) => Some(here),
871 None => match followed_ms() {
872 0 => match pinned_ms() {
873 0 => None,
874 pinned => Some(pinned),
875 },
876 followed => Some(followed),
877 },
878 }
879}
880
881pub fn with_wall_ms<T>(now_ms: u64, f: impl FnOnce() -> T) -> T {
884 struct Restore(Option<u64>);
885 impl Drop for Restore {
886 fn drop(&mut self) {
887 FROZEN_HERE_MS.with(|here| here.set(self.0));
888 }
889 }
890 let _restore = Restore(FROZEN_HERE_MS.with(|here| here.replace(Some(now_ms))));
891 f()
892}
893
894static PROCESS: std::sync::Mutex<Option<std::sync::Arc<AtomicU64>>> = std::sync::Mutex::new(None);
895
896fn pinned_ms() -> u64 {
897 PROCESS
898 .lock()
899 .unwrap_or_else(std::sync::PoisonError::into_inner)
900 .as_ref()
901 .map_or(0, |ms| ms.load(Ordering::Relaxed))
902}
903
904#[cfg(any(test, feature = "test-support"))]
905fn followed_ms() -> u64 {
906 testing::followed_ms()
907}
908
909#[cfg(not(any(test, feature = "test-support")))]
910const fn followed_ms() -> u64 {
911 0
912}
913
914#[allow(
915 clippy::disallowed_methods,
916 reason = "off the page this crate is where std's wall clock is read"
917)]
918#[must_use]
919#[inline]
920pub fn wall() -> SystemTime {
921 match frozen_ms() {
922 Some(ms) => UNIX_EPOCH
923 .checked_add(Duration::from_millis(ms))
924 .unwrap_or(UNIX_EPOCH),
925 None => SystemTime::now(),
926 }
927}
928
929#[cfg(not(test))]
932pub fn pin_wall(at: SystemTime) {
933 let pinned = std::sync::Arc::new(AtomicU64::new(wall_ms(at)));
934 *PROCESS
935 .lock()
936 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(pinned);
937}
938
939fn wall_ms(at: SystemTime) -> u64 {
941 at.duration_since(UNIX_EPOCH)
942 .map_or(1, |since| saturating_u64(since.as_millis()).max(1))
943}
944
945#[must_use]
947pub fn wall_frozen() -> bool {
948 frozen_ms().is_some()
949}
950
951#[must_use]
954pub fn is_synchronised() -> Option<bool> {
955 #[cfg(all(target_os = "linux", not(target_family = "wasm")))]
956 {
957 let output = std::process::Command::new("timedatectl")
958 .args(["show", "-p", "NTPSynchronized", "--value"])
959 .output()
960 .ok()?;
961 if !output.status.success() {
962 return None;
963 }
964 match String::from_utf8_lossy(&output.stdout).trim() {
965 "yes" => Some(true),
966 "no" => Some(false),
967 _ => None,
968 }
969 }
970 #[cfg(not(all(target_os = "linux", not(target_family = "wasm"))))]
971 {
972 None
973 }
974}
975
976#[must_use]
979pub fn is_zone_name(name: &str) -> bool {
980 const MAX_NAME: usize = 64;
982 !name.is_empty()
983 && name.len() <= MAX_NAME
984 && name.split('/').all(|part| {
985 !part.is_empty()
986 && part != "."
987 && part != ".."
988 && part.chars().all(|character| {
989 character.is_ascii_alphanumeric() || "_+-.".contains(character)
990 })
991 })
992}
993
994#[must_use]
995pub fn local_zone_name() -> Option<String> {
996 #[cfg(all(unix, not(target_family = "wasm")))]
997 {
998 if let Ok(tz) = std::env::var("TZ") {
999 let tz = tz.trim_start_matches(':');
1000 if !tz.is_empty() && !tz.starts_with('/') {
1001 return Some(tz.to_owned());
1002 }
1003 }
1004 let link = std::fs::read_link("/etc/localtime").ok()?;
1005 let (_, zone) = link.to_str()?.split_once("zoneinfo/")?;
1006 (!zone.is_empty()).then(|| zone.to_owned())
1007 }
1008 #[cfg(all(target_family = "wasm", not(tilo_no_js)))]
1011 {
1012 page::zone_name()
1013 }
1014 #[cfg(not(any(
1015 all(unix, not(target_family = "wasm")),
1016 all(target_family = "wasm", not(tilo_no_js))
1017 )))]
1018 {
1019 None
1020 }
1021}
1022
1023#[cfg(all(target_family = "wasm", not(tilo_no_js)))]
1025mod page {
1026 use wasm_bindgen::JsValue;
1027
1028 thread_local! {
1029 static ZONE_NAME: std::cell::OnceCell<Option<String>> = const { std::cell::OnceCell::new() };
1032 }
1033
1034 pub(crate) fn zone_name() -> Option<String> {
1036 ZONE_NAME.with(|name| name.get_or_init(read_zone_name).clone())
1037 }
1038
1039 fn read_zone_name() -> Option<String> {
1040 let format = js_sys::Intl::DateTimeFormat::default();
1041 let resolved = js_sys::Intl::DateTimeFormat::resolved_options(&format);
1042 js_sys::Reflect::get(&resolved, &JsValue::from_str("timeZone"))
1043 .ok()?
1044 .as_string()
1045 }
1046
1047 #[cfg(feature = "local")]
1051 pub(crate) fn zone_offsets(name: &str) -> Option<impl Fn(i64) -> Option<i32> + use<>> {
1052 use wasm_bindgen::JsCast as _;
1053 let intl = js_sys::Reflect::get(&js_sys::global(), &JsValue::from_str("Intl")).ok()?;
1054 let make = js_sys::Reflect::get(&intl, &JsValue::from_str("DateTimeFormat"))
1055 .ok()?
1056 .dyn_into::<js_sys::Function>()
1057 .ok()?;
1058 let options = js_sys::Object::new();
1059 js_sys::Reflect::set(
1060 &options,
1061 &JsValue::from_str("timeZone"),
1062 &JsValue::from_str(name),
1063 )
1064 .ok()?;
1065 js_sys::Reflect::set(
1067 &options,
1068 &JsValue::from_str("timeZoneName"),
1069 &JsValue::from_str("longOffset"),
1070 )
1071 .ok()?;
1072 let arguments = js_sys::Array::of2(&js_sys::Array::of1(&"en-US".into()), &options);
1073 let format: js_sys::Intl::DateTimeFormat = js_sys::Reflect::construct(&make, &arguments)
1075 .ok()?
1076 .unchecked_into();
1077 Some(move |unix_ms: i64| {
1078 let date = js_sys::Date::new(&millis(unix_ms));
1079 let parts = format.format_to_parts(&date);
1080 parts.iter().find_map(|part| {
1081 let kind = js_sys::Reflect::get(&part, &JsValue::from_str("type")).ok()?;
1082 if kind.as_string().as_deref() != Some("timeZoneName") {
1083 return None;
1084 }
1085 let value = js_sys::Reflect::get(&part, &JsValue::from_str("value")).ok()?;
1086 offset_named(&value.as_string()?)
1087 })
1088 })
1089 }
1090
1091 #[cfg(feature = "local")]
1093 pub(crate) fn zone_names() -> Vec<String> {
1094 let names = (|| {
1095 let intl = js_sys::Reflect::get(&js_sys::global(), &JsValue::from_str("Intl")).ok()?;
1096 let list: js_sys::Function = wasm_bindgen::JsCast::dyn_into(
1097 js_sys::Reflect::get(&intl, &JsValue::from_str("supportedValuesOf")).ok()?,
1098 )
1099 .ok()?;
1100 let names = list.call1(&intl, &JsValue::from_str("timeZone")).ok()?;
1101 Some(
1102 js_sys::Array::from(&names)
1103 .iter()
1104 .filter_map(|name| name.as_string())
1105 .collect::<Vec<_>>(),
1106 )
1107 })();
1108 names.unwrap_or_default()
1109 }
1110
1111 #[cfg(feature = "local")]
1113 fn offset_named(written: &str) -> Option<i32> {
1114 let offset = written.strip_prefix("GMT")?;
1115 if offset.is_empty() {
1116 return Some(0);
1117 }
1118 let mut chars = offset.chars();
1119 let sign = match chars.next()? {
1120 '+' => 1,
1121 '-' | '\u{2212}' => -1,
1122 _ => return None,
1123 };
1124 let offset = chars.as_str();
1125 let mut parts = offset.split(':');
1126 let hours: i32 = parts.next()?.parse().ok()?;
1127 let minutes: i32 = parts
1128 .next()
1129 .map_or(Some(0), |minutes| minutes.parse().ok())?;
1130 let seconds: i32 = parts
1131 .next()
1132 .map_or(Some(0), |seconds| seconds.parse().ok())?;
1133 hours
1134 .checked_mul(3600)?
1135 .checked_add(minutes.checked_mul(60)?)?
1136 .checked_add(seconds)?
1137 .checked_mul(sign)
1138 }
1139
1140 #[cfg(feature = "local")]
1142 pub(crate) fn offset_seconds(unix_ms: i64) -> i32 {
1143 let date = js_sys::Date::new(&millis(unix_ms));
1144 let west = minutes(js_sys::Date::get_timezone_offset(&date));
1146 west.saturating_mul(60).saturating_neg()
1147 }
1148
1149 #[cfg(feature = "local")]
1150 #[allow(
1151 clippy::cast_precision_loss,
1152 reason = "the browser's clock takes milliseconds as a double, which holds them exactly"
1153 )]
1154 fn millis(unix_ms: i64) -> JsValue {
1155 JsValue::from_f64(unix_ms as f64)
1156 }
1157
1158 #[cfg(feature = "local")]
1159 #[allow(
1160 clippy::cast_possible_truncation,
1161 reason = "the browser's offset is a whole number of minutes, within an hour's twelve"
1162 )]
1163 fn minutes(west_of_utc: f64) -> i32 {
1164 i32::try_from(west_of_utc as i64).unwrap_or(0)
1165 }
1166}
1167
1168#[must_use]
1169#[inline]
1170pub fn to_std(time: SystemTime) -> std::time::SystemTime {
1171 imp::to_std(time)
1172}
1173
1174#[must_use]
1175#[inline]
1176pub fn from_std(time: std::time::SystemTime) -> SystemTime {
1177 imp::from_std(time)
1178}
1179
1180fn since_epoch() -> Option<Duration> {
1181 wall().duration_since(UNIX_EPOCH).ok()
1182}
1183
1184fn saturating_u64(value: u128) -> u64 {
1185 u64::try_from(value).unwrap_or(u64::MAX)
1186}
1187
1188pub fn try_unix_now() -> Option<u64> {
1189 since_epoch().map(|duration| duration.as_secs())
1190}
1191
1192pub fn try_unix_now_ms() -> Option<u64> {
1193 since_epoch().map(|duration| saturating_u64(duration.as_millis()))
1194}
1195
1196pub fn try_unix_now_ns() -> Option<u64> {
1197 since_epoch().map(|duration| saturating_u64(duration.as_nanos()))
1198}
1199
1200pub fn unix_now() -> u64 {
1201 try_unix_now().unwrap_or(0)
1202}
1203
1204pub fn unix_now_ms() -> u64 {
1205 try_unix_now_ms().unwrap_or(0)
1206}
1207
1208pub fn unix_now_ns() -> u64 {
1209 try_unix_now_ns().unwrap_or(0)
1210}
1211
1212pub fn unix_now_i64() -> i64 {
1213 i64::try_from(unix_now()).unwrap_or(i64::MAX)
1214}
1215
1216pub fn unix_now_ms_i64() -> i64 {
1217 i64::try_from(unix_now_ms()).unwrap_or(i64::MAX)
1218}
1219
1220pub trait Clock: Send + Sync {
1221 fn now_ms(&self) -> u64;
1222}
1223
1224#[derive(Clone, Copy, Debug, Default)]
1225pub struct SystemClock;
1226
1227impl Clock for SystemClock {
1228 fn now_ms(&self) -> u64 {
1229 unix_now_ms()
1230 }
1231}
1232
1233#[derive(Clone, Copy, Debug, Default)]
1236pub struct MonotonicClock;
1237
1238impl Clock for MonotonicClock {
1239 #[allow(
1240 clippy::disallowed_methods,
1241 reason = "off the page this crate is where std's monotonic clock is read"
1242 )]
1243 fn now_ms(&self) -> u64 {
1244 static START: OnceLock<Instant> = OnceLock::new();
1245 saturating_u64(START.get_or_init(now).elapsed().as_millis())
1246 }
1247}
1248
1249#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1250pub struct FixedClock(pub u64);
1251
1252impl Clock for FixedClock {
1253 fn now_ms(&self) -> u64 {
1254 self.0
1255 }
1256}
1257
1258#[derive(Debug, Default)]
1259pub struct ManualClock(AtomicU64);
1260
1261impl ManualClock {
1262 pub const fn new(now_ms: u64) -> Self {
1263 Self(AtomicU64::new(now_ms))
1264 }
1265
1266 pub fn set(&self, now_ms: u64) {
1267 self.0.store(now_ms, Ordering::SeqCst);
1268 }
1269
1270 pub fn advance(&self, delta_ms: u64) {
1271 let _ = self
1272 .0
1273 .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |now| {
1274 Some(now.saturating_add(delta_ms))
1275 });
1276 }
1277}
1278
1279impl Clock for ManualClock {
1280 fn now_ms(&self) -> u64 {
1281 self.0.load(Ordering::SeqCst)
1282 }
1283}
1284
1285#[cfg(test)]
1286mod tests {
1287 use super::*;
1288
1289 #[test]
1290 fn a_threads_own_wall_clock_shadows_the_process_pin_only_on_that_thread() {
1291 const OTHER: u64 = 4_000_000_000;
1292 let at = UNIX_EPOCH + Duration::from_secs(OTHER);
1293 tilo_test_env::in_own_process(
1294 module_path!(),
1295 "a_threads_own_wall_clock_shadows_the_process_pin_only_on_that_thread",
1296 || {
1297 let process = testing::OwnProcess::of_a_test_in_its_own_process();
1298 let _held = testing::hold_wall_everywhere(process, at);
1299 assert_eq!(unix_now(), OTHER);
1300 assert!(wall_frozen());
1301 testing::with_wall(at + Duration::from_secs(1), || {
1302 assert_eq!(wall(), at + Duration::from_secs(1), "the thread's own");
1303 assert_eq!(
1304 std::thread::spawn(wall).join().unwrap(),
1305 at,
1306 "another thread keeps the process's"
1307 );
1308 });
1309 assert_eq!(wall(), at, "the process's, after the thread's scope");
1310 },
1311 );
1312 }
1313
1314 #[test]
1318 #[cfg(feature = "local")]
1319 fn a_named_zone_is_read_as_itself_whatever_the_machines_own() {
1320 tilo_test_env::in_own_process(
1321 module_path!(),
1322 "a_named_zone_is_read_as_itself_whatever_the_machines_own",
1323 || {
1324 let mut zone = tilo_test_env::ScopedEnv::new();
1325 zone.set("TZ", "America/Los_Angeles");
1326 let _held = testing::hold_wall_everywhere(
1328 testing::OwnProcess::of_a_test_in_its_own_process(),
1329 UNIX_EPOCH + Duration::from_secs(1_794_459_600),
1330 );
1331 let now = local::now();
1332 assert_eq!(
1333 now.time_zone().iana_name(),
1334 Some("America/Los_Angeles"),
1335 "the named zone is the one the clock stands in"
1336 );
1337 assert_eq!(
1338 local::today().to_string(),
1339 "2026-11-11",
1340 "their day, not UTC's"
1341 );
1342 assert_eq!(
1343 local::instant_of(jiff::civil::date(2026, 11, 11).at(21, 0, 0, 0)),
1344 jiff::Timestamp::from_second(1_794_459_600).ok(),
1345 "and the evening they read is the instant it names"
1346 );
1347 },
1348 );
1349 }
1350
1351 tilo_test_env::scenario! {
1352 fn clocks_read_units_that_agree_and_a_hold_ends_with_its_scope;
1353
1354 phase a_frozen_wall_clock_holds_while_the_monotonic_clock_runs;
1355 {
1356 let at = UNIX_EPOCH + Duration::from_secs(1_782_816_120);
1357 let before = now();
1358 testing::with_wall(at, || {
1359 assert!(wall_frozen());
1360 assert_eq!(wall(), at);
1361 assert_eq!(unix_now(), 1_782_816_120);
1362 assert_eq!(wall(), at, "it stays put");
1363 assert!(now() >= before, "the monotonic clock is not frozen");
1364 });
1365 assert!(!wall_frozen(), "the scope ended");
1366 }
1367
1368 phase clocks_agree_on_units_move_only_as_told_and_never_backwards;
1369 {
1370 assert!(!wall_frozen(), "no other test's pinned time is read here");
1371 {
1372 let secs = unix_now();
1373 let ms = unix_now_ms();
1374 let ns = unix_now_ns();
1375 assert!(secs > 1_600_000_000);
1376 assert!(ms / 1_000 >= secs);
1377 assert!(ns / 1_000_000 >= ms);
1378 assert_eq!(unix_now_i64(), i64::try_from(unix_now()).unwrap());
1379 }
1380 {
1381 assert_eq!(FixedClock(7).now_ms(), 7);
1382 let clock = ManualClock::new(10);
1383 assert_eq!(clock.now_ms(), 10);
1384 clock.advance(5);
1385 assert_eq!(clock.now_ms(), 15);
1386 clock.set(3);
1387 assert_eq!(clock.now_ms(), 3);
1388 clock.set(u64::MAX - 1);
1389 clock.advance(10);
1390 assert_eq!(clock.now_ms(), u64::MAX);
1391 }
1392 {
1393 let first = MonotonicClock.now_ms();
1394 assert!(MonotonicClock.now_ms() >= first);
1395 }
1396 }
1397
1398 phase now_is_monotonic;
1399 {
1400 let earlier = now();
1401 assert!(now() >= earlier);
1402 }
1403
1404 phase wall_is_after_the_epoch;
1405 {
1406 assert!(wall().duration_since(UNIX_EPOCH).is_ok());
1407 }
1408
1409 phase std_conversions_round_trip_on_both_sides_of_the_epoch;
1410 {
1411 let offset = Duration::from_millis(1_700_000_000_123);
1412 for time in [UNIX_EPOCH + offset, UNIX_EPOCH - offset, UNIX_EPOCH] {
1413 assert_eq!(from_std(to_std(time)), time);
1414 }
1415 assert_eq!(to_std(UNIX_EPOCH + offset), std::time::UNIX_EPOCH + offset);
1416 }
1417 }
1418}