Skip to main content

bark_runtime/
clock.rs

1//! Clock types that also work in the browser.
2//!
3//! `std::time::Instant` and `std::time::SystemTime` panic on
4//! `wasm32-unknown-unknown`, so on WASM these come from `web_time`, which
5//! reads the JS clocks instead.
6
7#[cfg(not(target_arch = "wasm32"))]
8pub use std::time::{Instant, SystemTime, UNIX_EPOCH};
9
10#[cfg(target_arch = "wasm32")]
11pub use web_time::{Instant, SystemTime, UNIX_EPOCH};
12
13/// Wall-clock reading. On native this is `std::time::SystemTime::now()`;
14/// on WASM it goes through `Date.now()` so it doesn't panic on
15/// `wasm32-unknown-unknown`.
16pub fn now() -> SystemTime {
17	SystemTime::now()
18}
19
20/// The current unix timestamp in seconds.
21pub fn timestamp_secs() -> u64 {
22	now().duration_since(UNIX_EPOCH)
23		.expect("time went backwards")
24		.as_secs()
25}
26
27#[cfg(test)]
28mod test {
29	use std::time::Duration;
30
31	use super::*;
32
33	#[cfg(target_arch = "wasm32")]
34	use wasm_bindgen_test::wasm_bindgen_test;
35	#[cfg(target_arch = "wasm32")]
36	wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
37
38	/// The timestamp is a plausible current unix time.
39	#[cfg_attr(not(target_arch = "wasm32"), test)]
40	#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
41	fn timestamp_is_a_recent_unix_time() {
42		let ts = timestamp_secs();
43		assert!(ts > 1_750_000_000, "{}", ts);
44	}
45
46	/// The wall clock never reads earlier than the unix epoch.
47	#[cfg_attr(not(target_arch = "wasm32"), test)]
48	#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
49	fn wall_clock_is_after_the_epoch() {
50		assert!(now().duration_since(UNIX_EPOCH).is_ok());
51	}
52
53	/// An instant reports the time that passed since it was taken.
54	#[cfg_attr(not(target_arch = "wasm32"), tokio::test)]
55	#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
56	async fn instant_measures_elapsed_time() {
57		let start = Instant::now();
58		crate::sleep(Duration::from_millis(20)).await;
59		assert!(start.elapsed() >= Duration::from_millis(20), "{:?}", start.elapsed());
60	}
61}
62