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 dcs::coordination::{Stopwatch, Timer};
use std::thread::sleep;
use std::time::{Duration, Instant, SystemTime};

pub struct OsClock {
    delta: Duration,
    last_instant: Instant,
}

impl Default for OsClock {
    fn default() -> Self {
        Self { delta: Default::default(), last_instant: Instant::now() }
    }
}

impl Stopwatch for OsClock {
    fn from_millis(millis: u64) -> Self {
        Self { delta: Duration::from_millis(millis), last_instant: Instant::now() }
    }

    fn as_secs(&self) -> u64 {
        self.delta.as_secs()
    }

    fn restart(&mut self) {
        self.last_instant = Instant::now();
    }

    fn is_timeout(&self) -> bool {
        self.last_instant + self.delta < Instant::now()
    }

    fn current_time_as_secs(&mut self) -> u64 {
        SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs()
    }
}

pub struct OsTimer {
    delta: Duration,
}

impl Timer for OsTimer {
    fn from_millis(millis: u64) -> Self {
        Self { delta: Duration::from_millis(millis) }
    }

    fn as_secs(&self) -> u64 {
        self.delta.as_secs()
    }

    fn wait(&self) {
        sleep(self.delta);
    }
}