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 {
572 pub use crate::imp::{Duration, Instant, SystemTime, SystemTimeError, UNIX_EPOCH};
573 #[cfg(not(test))]
575 pub use crate::pin_wall;
576 pub use crate::{
577 from_std, is_synchronised, local_zone_name, now, to_std, try_unix_now, try_unix_now_ms,
578 try_unix_now_ns, unix_now, unix_now_i64, unix_now_ms, unix_now_ms_i64, unix_now_ns, wall,
579 wall_frozen,
580 };
581
582 pub use crate::from_std as from_file_time;
584
585 #[cfg(any(test, feature = "test-support"))]
587 pub use crate::testing;
588}
589
590#[cfg(any(not(target_family = "wasm"), tilo_no_js))]
591mod imp {
592 pub use std::time::{Duration, Instant, SystemTime, SystemTimeError, UNIX_EPOCH};
593
594 #[inline]
595 pub const fn to_std(time: SystemTime) -> std::time::SystemTime {
596 time
597 }
598
599 #[inline]
600 pub const fn from_std(time: std::time::SystemTime) -> SystemTime {
601 time
602 }
603}
604
605#[cfg(all(target_family = "wasm", not(tilo_no_js)))]
606mod imp {
607 pub use web_time::{Duration, Instant, SystemTime, SystemTimeError, UNIX_EPOCH};
608
609 pub fn to_std(time: SystemTime) -> std::time::SystemTime {
610 let converted = match time.duration_since(UNIX_EPOCH) {
611 Ok(after) => std::time::UNIX_EPOCH.checked_add(after),
612 Err(before) => std::time::UNIX_EPOCH.checked_sub(before.duration()),
613 };
614 converted.unwrap_or(std::time::UNIX_EPOCH)
615 }
616
617 pub fn from_std(time: std::time::SystemTime) -> SystemTime {
618 let converted = match time.duration_since(std::time::UNIX_EPOCH) {
619 Ok(after) => UNIX_EPOCH.checked_add(after),
620 Err(before) => UNIX_EPOCH.checked_sub(before.duration()),
621 };
622 converted.unwrap_or(UNIX_EPOCH)
623 }
624}
625
626#[allow(
630 clippy::disallowed_methods,
631 reason = "off the page this crate is where std's monotonic clock is read"
632)]
633#[must_use]
634#[inline]
635pub fn now() -> Instant {
636 #[cfg(any(test, feature = "test-support"))]
637 if let Some(at) = testing::monotonic_override() {
638 return at;
639 }
640 Instant::now()
641}
642
643#[cfg(any(test, feature = "test-support"))]
644pub mod testing {
645 use super::time::{Instant, SystemTime};
646 use std::cell::Cell;
647
648 thread_local! {
649 static MONOTONIC: Cell<Option<Instant>> = const { Cell::new(None) };
650 }
651
652 pub(super) fn monotonic_override() -> Option<Instant> {
653 MONOTONIC.with(Cell::get)
654 }
655
656 struct Restore(Option<Instant>);
657
658 impl Drop for Restore {
659 fn drop(&mut self) {
660 MONOTONIC.with(|clock| clock.set(self.0));
661 }
662 }
663
664 pub fn with_monotonic_time<T>(at: Instant, operation: impl FnOnce() -> T) -> T {
665 let _restore = Restore(MONOTONIC.with(|clock| clock.replace(Some(at))));
666 operation()
667 }
668
669 struct RestoreWall(Option<u64>);
670
671 impl Drop for RestoreWall {
672 fn drop(&mut self) {
673 super::FROZEN_HERE_MS.with(|here| here.set(self.0));
674 }
675 }
676
677 #[derive(Clone, Copy)]
681 pub struct OwnProcess(());
682
683 impl OwnProcess {
684 #[doc(hidden)]
685 #[must_use]
686 pub const fn of_a_test_in_its_own_process() -> Self {
687 Self(())
688 }
689 }
690
691 pub struct WallHold {
693 _process: OwnProcess,
694 pinned: std::sync::Arc<super::AtomicU64>,
695 replaced: Option<std::sync::Arc<super::AtomicU64>>,
696 }
697
698 impl Drop for WallHold {
699 fn drop(&mut self) {
700 let mut process = super::PROCESS
701 .lock()
702 .unwrap_or_else(std::sync::PoisonError::into_inner);
703 if process
704 .as_ref()
705 .is_some_and(|pin| std::sync::Arc::ptr_eq(pin, &self.pinned))
706 {
707 *process = self.replaced.take();
708 }
709 }
710 }
711
712 pub fn hold_wall_everywhere(process: OwnProcess, at: SystemTime) -> WallHold {
715 let pinned = std::sync::Arc::new(super::AtomicU64::new(super::wall_ms(at)));
716 let replaced = super::PROCESS
718 .lock()
719 .unwrap_or_else(std::sync::PoisonError::into_inner)
720 .replace(pinned.clone());
721 WallHold {
722 _process: process,
723 pinned,
724 replaced,
725 }
726 }
727
728 thread_local! {
729 static FOLLOWED: std::cell::RefCell<Option<std::sync::Arc<std::sync::atomic::AtomicU64>>> =
730 const { std::cell::RefCell::new(None) };
731 }
732
733 pub(super) fn followed_ms() -> u64 {
734 FOLLOWED.with(|followed| {
735 followed
736 .borrow()
737 .as_ref()
738 .map_or(0, |wall| wall.load(std::sync::atomic::Ordering::Relaxed))
739 })
740 }
741
742 #[derive(Clone, Debug, Default)]
745 pub struct SharedWall(std::sync::Arc<std::sync::atomic::AtomicU64>);
746
747 impl SharedWall {
748 pub fn follow(&self) {
751 FOLLOWED.with(|followed| *followed.borrow_mut() = Some(self.0.clone()));
752 }
753
754 pub fn pin(&self, at: SystemTime) {
755 self.0
756 .store(super::wall_ms(at), std::sync::atomic::Ordering::Relaxed);
757 }
758
759 pub fn release(&self) {
760 self.0.store(0, std::sync::atomic::Ordering::Relaxed);
761 }
762 }
763
764 pub fn with_wall<T>(at: SystemTime, operation: impl FnOnce() -> T) -> T {
767 let ms = super::wall_ms(at);
768 let _restore = RestoreWall(super::FROZEN_HERE_MS.with(|here| here.replace(Some(ms))));
769 operation()
770 }
771}
772
773#[cfg(test)]
774mod scoped_monotonic_tests {
775 use super::*;
776
777 tilo_test_env::scenario! {
778 fn a_held_clock_is_the_holding_threads_alone_and_ends_with_its_scope;
779
780 phase a_shared_wall_pins_the_threads_following_it_until_released;
781 {
782 const PINNED: u64 = 123_456;
783 let wall = testing::SharedWall::default();
784 let follower = {
785 let wall = wall.clone();
786 move || {
787 wall.follow();
788 unix_now()
789 }
790 };
791 assert_ne!(std::thread::spawn(follower.clone()).join().unwrap(), PINNED);
792 wall.pin(UNIX_EPOCH + Duration::from_secs(PINNED));
793 assert_eq!(std::thread::spawn(follower.clone()).join().unwrap(), PINNED);
794 assert_ne!(
795 unix_now(),
796 PINNED,
797 "a thread following none keeps its clock"
798 );
799 wall.release();
800 assert_ne!(std::thread::spawn(follower).join().unwrap(), PINNED);
801 }
802
803 phase scoped_time_is_thread_local_nested_and_restored_after_unwind;
804 {
805 let at = now().checked_add(Duration::from_secs(60)).unwrap();
806 testing::with_monotonic_time(at, || {
807 assert_eq!(now(), at);
808 let later = at.checked_add(Duration::from_secs(1)).unwrap();
809 testing::with_monotonic_time(later, || assert_eq!(now(), later));
810 assert_eq!(now(), at);
811 assert!(std::thread::spawn(now).join().unwrap() < at);
812 let panicked = std::panic::catch_unwind(|| {
813 testing::with_monotonic_time(later, || panic!("unwind the clock scope"));
814 });
815 assert!(panicked.is_err());
816 assert_eq!(now(), at);
817 });
818 assert!(now() < at);
819 }
820
821 phase scoped_wall_time_is_thread_local_nested_and_restored_after_unwind;
822 {
823 let at = UNIX_EPOCH + Duration::from_secs(4_000_000_000);
824 testing::with_wall(at, || {
825 assert_eq!(wall(), at);
826 let later = at + Duration::from_secs(3);
827 testing::with_wall(later, || assert_eq!(wall(), later));
828 assert_eq!(wall(), at);
829 assert!(std::thread::spawn(wall).join().unwrap() < at);
830 let panicked = std::panic::catch_unwind(|| {
831 testing::with_wall(later, || panic!("unwind the clock scope"));
832 });
833 assert!(panicked.is_err());
834 assert_eq!(wall(), at);
835 });
836 assert!(wall() < at);
837 }
838
839 phase a_clock_lent_at_the_epoch_is_a_clock_the_code_reads;
840 {
841 let (ms, held, frozen) = with_wall_ms(0, || (unix_now_ms(), wall(), wall_frozen()));
845 assert_eq!(ms, 0, "the lent time is the time the code reads");
846 assert_eq!(held, UNIX_EPOCH);
847 assert!(frozen, "a hold at the epoch is a hold");
848 assert!(
849 unix_now_ms() > 0,
850 "the thread's own clock runs again after the hold"
851 );
852 }
853
854 phase two_threads_holding_different_wall_times_at_once_each_read_their_own;
855 {
856 let first = UNIX_EPOCH + Duration::from_secs(4_000_000_000);
857 let second = UNIX_EPOCH + Duration::from_secs(4_100_000_000);
858 let together = std::sync::Arc::new(std::sync::Barrier::new(2));
859 let hold = |at: SystemTime, other: SystemTime| {
860 let together = std::sync::Arc::clone(&together);
861 std::thread::spawn(move || {
862 testing::with_wall(at, || {
863 together.wait();
864 assert_eq!(wall(), at);
865 assert_ne!(wall(), other);
866 together.wait();
867 });
868 together.wait();
869 assert!(wall() < first, "the hold ended with its scope");
870 })
871 };
872 let threads = [hold(first, second), hold(second, first)];
873 for thread in threads {
874 thread.join().unwrap();
875 }
876 }
877 }
878}
879
880thread_local! {
881 static FROZEN_HERE_MS: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
883}
884
885fn frozen_ms() -> Option<u64> {
886 match FROZEN_HERE_MS.with(std::cell::Cell::get) {
887 Some(here) => Some(here),
888 None => match followed_ms() {
889 0 => match pinned_ms() {
890 0 => None,
891 pinned => Some(pinned),
892 },
893 followed => Some(followed),
894 },
895 }
896}
897
898pub fn with_wall_ms<T>(now_ms: u64, f: impl FnOnce() -> T) -> T {
901 struct Restore(Option<u64>);
902 impl Drop for Restore {
903 fn drop(&mut self) {
904 FROZEN_HERE_MS.with(|here| here.set(self.0));
905 }
906 }
907 let _restore = Restore(FROZEN_HERE_MS.with(|here| here.replace(Some(now_ms))));
908 f()
909}
910
911static PROCESS: std::sync::Mutex<Option<std::sync::Arc<AtomicU64>>> = std::sync::Mutex::new(None);
912
913fn pinned_ms() -> u64 {
914 PROCESS
915 .lock()
916 .unwrap_or_else(std::sync::PoisonError::into_inner)
917 .as_ref()
918 .map_or(0, |ms| ms.load(Ordering::Relaxed))
919}
920
921#[cfg(any(test, feature = "test-support"))]
922fn followed_ms() -> u64 {
923 testing::followed_ms()
924}
925
926#[cfg(not(any(test, feature = "test-support")))]
927const fn followed_ms() -> u64 {
928 0
929}
930
931#[allow(
932 clippy::disallowed_methods,
933 reason = "off the page this crate is where std's wall clock is read"
934)]
935#[must_use]
936#[inline]
937pub fn wall() -> SystemTime {
938 match frozen_ms() {
939 Some(ms) => UNIX_EPOCH
940 .checked_add(Duration::from_millis(ms))
941 .unwrap_or(UNIX_EPOCH),
942 None => SystemTime::now(),
943 }
944}
945
946#[cfg(not(test))]
949pub fn pin_wall(at: SystemTime) {
950 let pinned = std::sync::Arc::new(AtomicU64::new(wall_ms(at)));
951 *PROCESS
952 .lock()
953 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(pinned);
954}
955
956fn wall_ms(at: SystemTime) -> u64 {
958 at.duration_since(UNIX_EPOCH)
959 .map_or(1, |since| saturating_u64(since.as_millis()).max(1))
960}
961
962#[must_use]
964pub fn wall_frozen() -> bool {
965 frozen_ms().is_some()
966}
967
968#[must_use]
971pub fn is_synchronised() -> Option<bool> {
972 #[cfg(all(target_os = "linux", not(target_family = "wasm")))]
973 {
974 let output = std::process::Command::new("timedatectl")
975 .args(["show", "-p", "NTPSynchronized", "--value"])
976 .output()
977 .ok()?;
978 if !output.status.success() {
979 return None;
980 }
981 match String::from_utf8_lossy(&output.stdout).trim() {
982 "yes" => Some(true),
983 "no" => Some(false),
984 _ => None,
985 }
986 }
987 #[cfg(not(all(target_os = "linux", not(target_family = "wasm"))))]
988 {
989 None
990 }
991}
992
993#[must_use]
996pub fn is_zone_name(name: &str) -> bool {
997 const MAX_NAME: usize = 64;
999 !name.is_empty()
1000 && name.len() <= MAX_NAME
1001 && name.split('/').all(|part| {
1002 !part.is_empty()
1003 && part != "."
1004 && part != ".."
1005 && part.chars().all(|character| {
1006 character.is_ascii_alphanumeric() || "_+-.".contains(character)
1007 })
1008 })
1009}
1010
1011#[must_use]
1012pub fn local_zone_name() -> Option<String> {
1013 #[cfg(all(unix, not(target_family = "wasm")))]
1014 {
1015 if let Ok(tz) = std::env::var("TZ") {
1016 let tz = tz.trim_start_matches(':');
1017 if !tz.is_empty() && !tz.starts_with('/') {
1018 return Some(tz.to_owned());
1019 }
1020 }
1021 let link = std::fs::read_link("/etc/localtime").ok()?;
1022 let (_, zone) = link.to_str()?.split_once("zoneinfo/")?;
1023 (!zone.is_empty()).then(|| zone.to_owned())
1024 }
1025 #[cfg(all(target_family = "wasm", not(tilo_no_js)))]
1028 {
1029 page::zone_name()
1030 }
1031 #[cfg(not(any(
1032 all(unix, not(target_family = "wasm")),
1033 all(target_family = "wasm", not(tilo_no_js))
1034 )))]
1035 {
1036 None
1037 }
1038}
1039
1040#[cfg(all(target_family = "wasm", not(tilo_no_js)))]
1042mod page {
1043 use wasm_bindgen::JsValue;
1044
1045 thread_local! {
1046 static ZONE_NAME: std::cell::OnceCell<Option<String>> = const { std::cell::OnceCell::new() };
1049 }
1050
1051 pub(crate) fn zone_name() -> Option<String> {
1053 ZONE_NAME.with(|name| name.get_or_init(read_zone_name).clone())
1054 }
1055
1056 fn read_zone_name() -> Option<String> {
1057 let format = js_sys::Intl::DateTimeFormat::default();
1058 let resolved = js_sys::Intl::DateTimeFormat::resolved_options(&format);
1059 js_sys::Reflect::get(&resolved, &JsValue::from_str("timeZone"))
1060 .ok()?
1061 .as_string()
1062 }
1063
1064 #[cfg(feature = "local")]
1068 pub(crate) fn zone_offsets(name: &str) -> Option<impl Fn(i64) -> Option<i32> + use<>> {
1069 use wasm_bindgen::JsCast as _;
1070 let intl = js_sys::Reflect::get(&js_sys::global(), &JsValue::from_str("Intl")).ok()?;
1071 let make = js_sys::Reflect::get(&intl, &JsValue::from_str("DateTimeFormat"))
1072 .ok()?
1073 .dyn_into::<js_sys::Function>()
1074 .ok()?;
1075 let options = js_sys::Object::new();
1076 js_sys::Reflect::set(
1077 &options,
1078 &JsValue::from_str("timeZone"),
1079 &JsValue::from_str(name),
1080 )
1081 .ok()?;
1082 js_sys::Reflect::set(
1084 &options,
1085 &JsValue::from_str("timeZoneName"),
1086 &JsValue::from_str("longOffset"),
1087 )
1088 .ok()?;
1089 let arguments = js_sys::Array::of2(&js_sys::Array::of1(&"en-US".into()), &options);
1090 let format: js_sys::Intl::DateTimeFormat = js_sys::Reflect::construct(&make, &arguments)
1092 .ok()?
1093 .unchecked_into();
1094 Some(move |unix_ms: i64| {
1095 let date = js_sys::Date::new(&millis(unix_ms));
1096 let parts = format.format_to_parts(&date);
1097 parts.iter().find_map(|part| {
1098 let kind = js_sys::Reflect::get(&part, &JsValue::from_str("type")).ok()?;
1099 if kind.as_string().as_deref() != Some("timeZoneName") {
1100 return None;
1101 }
1102 let value = js_sys::Reflect::get(&part, &JsValue::from_str("value")).ok()?;
1103 offset_named(&value.as_string()?)
1104 })
1105 })
1106 }
1107
1108 #[cfg(feature = "local")]
1110 pub(crate) fn zone_names() -> Vec<String> {
1111 let names = (|| {
1112 let intl = js_sys::Reflect::get(&js_sys::global(), &JsValue::from_str("Intl")).ok()?;
1113 let list: js_sys::Function = wasm_bindgen::JsCast::dyn_into(
1114 js_sys::Reflect::get(&intl, &JsValue::from_str("supportedValuesOf")).ok()?,
1115 )
1116 .ok()?;
1117 let names = list.call1(&intl, &JsValue::from_str("timeZone")).ok()?;
1118 Some(
1119 js_sys::Array::from(&names)
1120 .iter()
1121 .filter_map(|name| name.as_string())
1122 .collect::<Vec<_>>(),
1123 )
1124 })();
1125 names.unwrap_or_default()
1126 }
1127
1128 #[cfg(feature = "local")]
1130 fn offset_named(written: &str) -> Option<i32> {
1131 let offset = written.strip_prefix("GMT")?;
1132 if offset.is_empty() {
1133 return Some(0);
1134 }
1135 let mut chars = offset.chars();
1136 let sign = match chars.next()? {
1137 '+' => 1,
1138 '-' | '\u{2212}' => -1,
1139 _ => return None,
1140 };
1141 let offset = chars.as_str();
1142 let mut parts = offset.split(':');
1143 let hours: i32 = parts.next()?.parse().ok()?;
1144 let minutes: i32 = parts
1145 .next()
1146 .map_or(Some(0), |minutes| minutes.parse().ok())?;
1147 let seconds: i32 = parts
1148 .next()
1149 .map_or(Some(0), |seconds| seconds.parse().ok())?;
1150 hours
1151 .checked_mul(3600)?
1152 .checked_add(minutes.checked_mul(60)?)?
1153 .checked_add(seconds)?
1154 .checked_mul(sign)
1155 }
1156
1157 #[cfg(feature = "local")]
1159 pub(crate) fn offset_seconds(unix_ms: i64) -> i32 {
1160 let date = js_sys::Date::new(&millis(unix_ms));
1161 let west = minutes(js_sys::Date::get_timezone_offset(&date));
1163 west.saturating_mul(60).saturating_neg()
1164 }
1165
1166 #[cfg(feature = "local")]
1167 #[allow(
1168 clippy::cast_precision_loss,
1169 reason = "the browser's clock takes milliseconds as a double, which holds them exactly"
1170 )]
1171 fn millis(unix_ms: i64) -> JsValue {
1172 JsValue::from_f64(unix_ms as f64)
1173 }
1174
1175 #[cfg(feature = "local")]
1176 #[allow(
1177 clippy::cast_possible_truncation,
1178 reason = "the browser's offset is a whole number of minutes, within an hour's twelve"
1179 )]
1180 fn minutes(west_of_utc: f64) -> i32 {
1181 i32::try_from(west_of_utc as i64).unwrap_or(0)
1182 }
1183}
1184
1185#[must_use]
1186#[inline]
1187pub fn to_std(time: SystemTime) -> std::time::SystemTime {
1188 imp::to_std(time)
1189}
1190
1191#[must_use]
1192#[inline]
1193pub fn from_std(time: std::time::SystemTime) -> SystemTime {
1194 imp::from_std(time)
1195}
1196
1197fn since_epoch() -> Option<Duration> {
1198 wall().duration_since(UNIX_EPOCH).ok()
1199}
1200
1201fn saturating_u64(value: u128) -> u64 {
1202 u64::try_from(value).unwrap_or(u64::MAX)
1203}
1204
1205pub fn try_unix_now() -> Option<u64> {
1206 since_epoch().map(|duration| duration.as_secs())
1207}
1208
1209pub fn try_unix_now_ms() -> Option<u64> {
1210 since_epoch().map(|duration| saturating_u64(duration.as_millis()))
1211}
1212
1213pub fn try_unix_now_ns() -> Option<u64> {
1214 since_epoch().map(|duration| saturating_u64(duration.as_nanos()))
1215}
1216
1217pub fn unix_now() -> u64 {
1218 try_unix_now().unwrap_or(0)
1219}
1220
1221pub fn unix_now_ms() -> u64 {
1222 try_unix_now_ms().unwrap_or(0)
1223}
1224
1225pub fn unix_now_ns() -> u64 {
1226 try_unix_now_ns().unwrap_or(0)
1227}
1228
1229pub fn unix_now_i64() -> i64 {
1230 i64::try_from(unix_now()).unwrap_or(i64::MAX)
1231}
1232
1233pub fn unix_now_ms_i64() -> i64 {
1234 i64::try_from(unix_now_ms()).unwrap_or(i64::MAX)
1235}
1236
1237pub trait Clock: Send + Sync {
1238 fn now_ms(&self) -> u64;
1239}
1240
1241#[derive(Clone, Copy, Debug, Default)]
1242pub struct SystemClock;
1243
1244impl Clock for SystemClock {
1245 fn now_ms(&self) -> u64 {
1246 unix_now_ms()
1247 }
1248}
1249
1250#[derive(Clone, Copy, Debug, Default)]
1253pub struct MonotonicClock;
1254
1255impl Clock for MonotonicClock {
1256 #[allow(
1257 clippy::disallowed_methods,
1258 reason = "off the page this crate is where std's monotonic clock is read"
1259 )]
1260 fn now_ms(&self) -> u64 {
1261 static START: OnceLock<Instant> = OnceLock::new();
1262 saturating_u64(START.get_or_init(now).elapsed().as_millis())
1263 }
1264}
1265
1266#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1267pub struct FixedClock(pub u64);
1268
1269impl Clock for FixedClock {
1270 fn now_ms(&self) -> u64 {
1271 self.0
1272 }
1273}
1274
1275#[derive(Debug, Default)]
1276pub struct ManualClock(AtomicU64);
1277
1278impl ManualClock {
1279 pub const fn new(now_ms: u64) -> Self {
1280 Self(AtomicU64::new(now_ms))
1281 }
1282
1283 pub fn set(&self, now_ms: u64) {
1284 self.0.store(now_ms, Ordering::SeqCst);
1285 }
1286
1287 pub fn advance(&self, delta_ms: u64) {
1288 let _ = self
1289 .0
1290 .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |now| {
1291 Some(now.saturating_add(delta_ms))
1292 });
1293 }
1294}
1295
1296impl Clock for ManualClock {
1297 fn now_ms(&self) -> u64 {
1298 self.0.load(Ordering::SeqCst)
1299 }
1300}
1301
1302#[cfg(test)]
1303mod tests {
1304 use super::*;
1305
1306 #[test]
1307 fn a_threads_own_wall_clock_shadows_the_process_pin_only_on_that_thread() {
1308 const OTHER: u64 = 4_000_000_000;
1309 let at = UNIX_EPOCH + Duration::from_secs(OTHER);
1310 tilo_test_env::in_own_process(
1311 module_path!(),
1312 "a_threads_own_wall_clock_shadows_the_process_pin_only_on_that_thread",
1313 || {
1314 let process = testing::OwnProcess::of_a_test_in_its_own_process();
1315 let _held = testing::hold_wall_everywhere(process, at);
1316 assert_eq!(unix_now(), OTHER);
1317 assert!(wall_frozen());
1318 testing::with_wall(at + Duration::from_secs(1), || {
1319 assert_eq!(wall(), at + Duration::from_secs(1), "the thread's own");
1320 assert_eq!(
1321 std::thread::spawn(wall).join().unwrap(),
1322 at,
1323 "another thread keeps the process's"
1324 );
1325 });
1326 assert_eq!(wall(), at, "the process's, after the thread's scope");
1327 },
1328 );
1329 }
1330
1331 #[test]
1335 #[cfg(feature = "local")]
1336 fn a_named_zone_is_read_as_itself_whatever_the_machines_own() {
1337 tilo_test_env::in_own_process(
1338 module_path!(),
1339 "a_named_zone_is_read_as_itself_whatever_the_machines_own",
1340 || {
1341 let mut zone = tilo_test_env::ScopedEnv::new();
1342 zone.set("TZ", "America/Los_Angeles");
1343 let _held = testing::hold_wall_everywhere(
1345 testing::OwnProcess::of_a_test_in_its_own_process(),
1346 UNIX_EPOCH + Duration::from_secs(1_794_459_600),
1347 );
1348 let now = local::now();
1349 assert_eq!(
1350 now.time_zone().iana_name(),
1351 Some("America/Los_Angeles"),
1352 "the named zone is the one the clock stands in"
1353 );
1354 assert_eq!(
1355 local::today().to_string(),
1356 "2026-11-11",
1357 "their day, not UTC's"
1358 );
1359 assert_eq!(
1360 local::instant_of(jiff::civil::date(2026, 11, 11).at(21, 0, 0, 0)),
1361 jiff::Timestamp::from_second(1_794_459_600).ok(),
1362 "and the evening they read is the instant it names"
1363 );
1364 },
1365 );
1366 }
1367
1368 tilo_test_env::scenario! {
1369 fn clocks_read_units_that_agree_and_a_hold_ends_with_its_scope;
1370
1371 phase a_frozen_wall_clock_holds_while_the_monotonic_clock_runs;
1372 {
1373 let at = UNIX_EPOCH + Duration::from_secs(1_782_816_120);
1374 let before = now();
1375 testing::with_wall(at, || {
1376 assert!(wall_frozen());
1377 assert_eq!(wall(), at);
1378 assert_eq!(unix_now(), 1_782_816_120);
1379 assert_eq!(wall(), at, "it stays put");
1380 assert!(now() >= before, "the monotonic clock is not frozen");
1381 });
1382 assert!(!wall_frozen(), "the scope ended");
1383 }
1384
1385 phase clocks_agree_on_units_move_only_as_told_and_never_backwards;
1386 {
1387 assert!(!wall_frozen(), "no other test's pinned time is read here");
1388 {
1389 let secs = unix_now();
1390 let ms = unix_now_ms();
1391 let ns = unix_now_ns();
1392 assert!(secs > 1_600_000_000);
1393 assert!(ms / 1_000 >= secs);
1394 assert!(ns / 1_000_000 >= ms);
1395 assert_eq!(unix_now_i64(), i64::try_from(unix_now()).unwrap());
1396 }
1397 {
1398 assert_eq!(FixedClock(7).now_ms(), 7);
1399 let clock = ManualClock::new(10);
1400 assert_eq!(clock.now_ms(), 10);
1401 clock.advance(5);
1402 assert_eq!(clock.now_ms(), 15);
1403 clock.set(3);
1404 assert_eq!(clock.now_ms(), 3);
1405 clock.set(u64::MAX - 1);
1406 clock.advance(10);
1407 assert_eq!(clock.now_ms(), u64::MAX);
1408 }
1409 {
1410 let first = MonotonicClock.now_ms();
1411 assert!(MonotonicClock.now_ms() >= first);
1412 }
1413 }
1414
1415 phase now_is_monotonic;
1416 {
1417 let earlier = now();
1418 assert!(now() >= earlier);
1419 }
1420
1421 phase wall_is_after_the_epoch;
1422 {
1423 assert!(wall().duration_since(UNIX_EPOCH).is_ok());
1424 }
1425
1426 phase std_conversions_round_trip_on_both_sides_of_the_epoch;
1427 {
1428 let offset = Duration::from_millis(1_700_000_000_123);
1429 for time in [UNIX_EPOCH + offset, UNIX_EPOCH - offset, UNIX_EPOCH] {
1430 assert_eq!(from_std(to_std(time)), time);
1431 }
1432 assert_eq!(to_std(UNIX_EPOCH + offset), std::time::UNIX_EPOCH + offset);
1433 }
1434 }
1435}