aboutsummaryrefslogtreecommitdiff
path: root/src/time.rs
blob: eba7507cc8e0087fd1326507f71a8fe678700fd9 (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
53
54
55
56
57
58
59
60
use std::time::{SystemTime, Duration};
use sdl2::ttf;
use sdl2::render::{Texture, TextureCreator};
use sdl2::pixels::Color;

#[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;
    }

    pub fn to_texture<'a, T>(
        &'a self,
        font: &ttf::Font,
        tex_creator: &'a TextureCreator<T>,
        bg: &Color
    ) -> Texture
    {
        let current = if self.state == State::Active {
            self.time.elapsed().unwrap()
        } else {
            self.result
        }.as_millis();

        let s = format!("{}.{}", current / 1000, current % 1000);

        let surface = font.render(&s).shaded(Color::RGB(255, 255, 255), *bg).unwrap();
        tex_creator.create_texture_from_surface(&surface).unwrap()
    }
}