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
21use std::time::{SystemTime, UNIX_EPOCH, Duration};
22use std::thread;
23
24/// Returns the current time as milliseconds since Unix epoch.
25///
26/// # Returns
27///
28/// Milliseconds since January 1, 1970 00:00:00 UTC.
29/// Returns 0 if system time is before the Unix epoch (should not happen
30/// on properly configured systems).
31///
32/// # Example
33///
34/// ```
35/// use logicaffeine_system::time;
36///
37/// let timestamp = time::now();
38/// assert!(timestamp > 0);
39/// ```
40pub fn now() -> u64 {
41    SystemTime::now()
42        .duration_since(UNIX_EPOCH)
43        .unwrap_or(Duration::ZERO)
44        .as_millis() as u64
45}
46
47/// Blocks the current thread for the specified duration.
48///
49/// # Arguments
50///
51/// * `ms` - Duration to sleep in milliseconds
52///
53/// # Note
54///
55/// This blocks the entire thread. For async code, use `tokio::time::sleep`
56/// instead to avoid blocking the executor.
57///
58/// # Example
59///
60/// ```no_run
61/// use logicaffeine_system::time;
62///
63/// time::sleep(500); // Sleep for half a second
64/// ```
65pub fn sleep(ms: u64) {
66    thread::sleep(Duration::from_millis(ms));
67}