1pub trait TimeTrait : Copy {
2 fn now() -> Self;
3 fn sub(&self, other: &Self) -> f64;
4 fn supports_sleep() -> bool;
5 fn sleep(seconds: f64);
6}
7
8pub use time::*;
9
10#[cfg(not(target_arch = "wasm32"))]
11mod time {
12 use super::*;
13 use std::time::{Instant, Duration};
14 use std::thread::sleep;
15
16 #[derive(Copy, Clone)]
17 pub struct Time(Instant);
18
19 impl TimeTrait for Time {
20 fn now() -> Self {
21 Self(Instant::now())
22 }
23
24 fn sub(&self, other: &Self) -> f64 {
25 self.0.duration_since(other.0).as_secs_f64()
26 }
27
28 fn supports_sleep() -> bool {
29 true
30 }
31
32 fn sleep(seconds: f64) {
33 sleep(Duration::from_secs_f64(seconds));
34 }
35 }
36}
37
38#[cfg(target_arch = "wasm32")]
39mod time {
40 use super::*;
41 use web_sys::window;
42
43 #[derive(Copy, Clone)]
44 pub struct Time(f64);
45
46 impl TimeTrait for Time {
47 fn now() -> Self {
48 Self(window().unwrap().performance().unwrap().now() / 1000.)
49 }
50
51 fn sub(&self, other: &Self) -> f64 {
52 self.0 - other.0
53 }
54
55 fn supports_sleep() -> bool {
56 false
57 }
58
59 fn sleep(_seconds: f64) {
60 unimplemented!("Not supported for WASM.");
61 }
62 }
63}