rust_clock/
lib.rs

1/* 
2    rust-clock
3    Copyright (c) 2016 Sam Saint-Pettersen.
4
5    Released under the MIT License.
6*/
7
8//! Rust library to create a hh:mm:ss clock for the CLI from seconds or miliseconds.
9
10pub struct Clock {
11    hours: i64,
12    minutes: i64,
13    seconds: i64,
14}
15
16impl Clock {
17
18    ///
19    /// Create a new clock.
20    ///
21    pub fn new() -> Clock {
22        Clock {
23            hours: 0,
24            minutes: 0,
25            seconds: 0,
26        }
27    }
28
29    /// 
30    /// Set the clock time in milliseconds.
31    /// 
32    /// * `ms` - Milliseconds to set time from.
33    pub fn set_time_ms(&mut self, ms: i64) {
34        self.seconds = (ms / 1000) % 60;
35        self.minutes = (ms / (1000 * 60)) % 60;
36        self.hours = (ms / (1000 * 60 * 60)) % 24;
37    }
38
39    ///
40    /// Set the clock time in seconds.
41    ///
42    /// * `seconds` - Seconds to set time from.
43    pub fn set_time_secs(&mut self, seconds: i64) {
44        self.set_time_ms(seconds * 1000);
45    }
46
47    ///
48    /// Get the clock time in hh:mm:ss notation.
49    ///
50    pub fn get_time(&self) -> String {
51        format!("{:02}:{:02}:{:02}", self.hours, self.minutes, self.seconds)
52    }
53}
54
55#[cfg(test)]
56#[test]
57fn test_clock_ms() {
58    let mut clock = Clock::new();
59    clock.set_time_ms(60000);
60    assert_eq!(clock.get_time(), "00:01:00");
61}
62
63#[test]
64fn test_clock_secs() {
65    let mut clock = Clock::new();
66    clock.set_time_secs(330);
67    assert_eq!(clock.get_time(), "00:05:30");
68}