aboutsummaryrefslogtreecommitdiff
path: root/src/time.rs
blob: 791ff2eeb39b0608f262761f1309019407d6561f (plain)
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
use std::time::{SystemTime, Duration};

#[derive(PartialEq)]
pub enum State {
    Idle,
    Active,
    Inactive,
}

pub struct Timer {
    pub state: State,
    time: SystemTime,
    result: Duration,
}

impl Timer {
    pub fn new() -> Timer {
        Timer {
            state: State::Inactive,
            time: SystemTime::now(),
            result: Duration::new(0, 0),
        }
    }

    pub fn start(&mut self) {
        self.time = SystemTime::now();
        self.state = State::Active;
    }

    pub fn stop(&mut self) {
        self.result = self.time.elapsed().unwrap();
        self.state = State::Inactive;
    }

    pub fn idle(&mut self) {
        self.state = State::Idle;
    }
}

use std::fmt;

impl fmt::Display for Timer {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let current = if self.state == State::Active {
            self.time.elapsed().unwrap()
        } else {
            self.result
        }.as_millis();

        write!(f, "{}.{}", current / 1000, current % 1000)
    }
}