Skip to main content

logicaffeine_system/
time.rs

1//! Time Utilities
2//!
3//! Provides time-related functions for timestamps and delays.
4//!
5//! # Platform Support
6//!
7//! - **Native**: Uses `std::time::SystemTime` and `std::thread::sleep`
8//! - **WASM**: Not available (use browser APIs via JavaScript interop)
9//!
10//! # Example
11//!
12//! ```no_run
13//! use logicaffeine_system::time;
14//!
15//! let start = time::now();
16//! time::sleep(1000); // Sleep for 1 second
17//! let elapsed = time::now() - start;
18//! println!("Elapsed: {}ms", elapsed);
19//! ```
20
21/// Returns the current time as milliseconds since Unix epoch.
22///
23/// # Returns
24///
25/// Milliseconds since January 1, 1970 00:00:00 UTC.
26/// Returns 0 if system time is before the Unix epoch (should not happen
27/// on properly configured systems).
28///
29/// # Example
30///
31/// ```
32/// use logicaffeine_system::time;
33///
34/// let timestamp = time::now();
35/// assert!(timestamp > 0);
36/// ```
37pub fn now() -> u64 {
38    if let Some(sealed) = crate::testworld::intercept_now() {
39        return sealed;
40    }
41    #[cfg(not(target_arch = "wasm32"))]
42    {
43        use std::time::{Duration, SystemTime, UNIX_EPOCH};
44        SystemTime::now()
45            .duration_since(UNIX_EPOCH)
46            .unwrap_or(Duration::ZERO)
47            .as_millis() as u64
48    }
49    #[cfg(target_arch = "wasm32")]
50    {
51        js_sys::Date::now() as u64
52    }
53}
54
55/// Blocks the current thread for the specified duration.
56///
57/// # Arguments
58///
59/// * `ms` - Duration to sleep in milliseconds, of any integer type; a negative duration is no wait
60///
61/// # Note
62///
63/// This blocks the entire thread. For async code, use `tokio::time::sleep`
64/// instead to avoid blocking the executor.
65///
66/// # Example
67///
68/// ```no_run
69/// use logicaffeine_system::time;
70///
71/// time::sleep(500); // Sleep for half a second
72/// ```
73pub fn sleep<T: TryInto<u64>>(ms: T) {
74    let ms = ms.try_into().unwrap_or(0);
75    if crate::testworld::intercept_sleep(ms) {
76        return; // sealed: logical time advanced instantly, no real wait
77    }
78    #[cfg(not(target_arch = "wasm32"))]
79    std::thread::sleep(std::time::Duration::from_millis(ms));
80    #[cfg(target_arch = "wasm32")]
81    let _ = ms; // the browser cannot block its thread; a live sleep is a no-op
82}