1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use crate::duration::Duration;

//TODO: Timestamp & Instant implementations can probably be merged

cfg_if! {
    if #[cfg(target_arch = "wasm32")] {
        // Wasm //

        use js_sys::Date;

        /// Represents a specific moment in time
        #[derive(Debug, Clone)]
        pub struct Instant {
            inner: f64,
        }

        impl Instant {
            /// Creates an Instant from the moment the method is called
            pub fn now() -> Self {
                Instant {
                    inner: Date::now(),
                }
            }

            /// Returns time elapsed since the Instant
            pub fn elapsed(&self) -> Duration {
                let inner_duration = Date::now() - self.inner;
                let seconds: u64 = (inner_duration as u64) / 1000;
                let nanos: u32 = ((inner_duration as u32) % 1000) * 1000000;
                return Duration::new(seconds, nanos);
            }
        }
    }
    else {
        // Linux //
        /// Represents a specific moment in time
        #[derive(Debug, Clone)]
        pub struct Instant {
            inner: std::time::Instant,
        }

        impl Instant {
            /// Creates an Instant from the moment the method is called
            pub fn now() -> Self {
                Instant {
                    inner: std::time::Instant::now(),
                }
            }

            /// Returns time elapsed since the Instant
            pub fn elapsed(&self) -> Duration {
                let inner_duration = self.inner.elapsed();
                return Duration::new(inner_duration.as_secs(), inner_duration.subsec_nanos());
            }
        }
    }
}