canic_core/cdk/utils/
time.rs1use std::time::SystemTime;
8
9#[cfg_attr(target_arch = "wasm32", expect(unreachable_code))]
11fn time_nanos() -> u128 {
12 #[cfg(target_arch = "wasm32")]
13 {
14 return u128::from(crate::cdk::api::time());
15 }
16
17 match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
18 Ok(d) => d.as_nanos(),
19 Err(_) => 0,
20 }
21}
22
23#[must_use]
25#[expect(clippy::cast_possible_truncation)]
26pub fn now_secs() -> u64 {
27 (time_nanos() / 1_000_000_000) as u64
28}
29
30#[must_use]
32#[expect(clippy::cast_possible_truncation)]
33pub fn now_millis() -> u64 {
34 (time_nanos() / 1_000_000) as u64
35}
36
37#[must_use]
39#[expect(clippy::cast_possible_truncation)]
40pub fn now_micros() -> u64 {
41 (time_nanos() / 1_000) as u64
42}
43
44#[must_use]
46#[expect(clippy::cast_possible_truncation)]
47pub fn now_nanos() -> u64 {
48 time_nanos() as u64
49}
50
51#[cfg(test)]
56mod tests {
57 use super::*;
58
59 #[test]
60 fn test_now_secs_sanity() {
61 let now = now_secs();
62 let current_year_secs = 1_700_000_000; assert!(now > current_year_secs);
64 }
65}