light_tool/
timestamp.rs

1use std::time::{SystemTime, UNIX_EPOCH};
2
3/// Returns the current time in seconds
4///
5/// # Example
6///
7/// ```no_run
8/// use light_tool::timestamp;
9/// println!("second timestamp: {}", timestamp::seconds());
10/// ```
11pub fn seconds() -> u64 {
12    match SystemTime::now().duration_since(UNIX_EPOCH) {
13        Ok(n) => n.as_secs(),
14        Err(_) => panic!("SystemTime before UNIX EPOCH!"),
15    }
16}
17
18/// Returns the current time in milliseconds
19///
20/// # Example
21///
22/// ```no_run
23/// use light_tool::timestamp;
24/// println!("milli second timestamp: {}", timestamp::milli_seconds());
25/// ```
26pub fn milli_seconds() -> u64 {
27    match SystemTime::now().duration_since(UNIX_EPOCH) {
28        Ok(n) => n.as_millis() as u64,
29        Err(_) => panic!("SystemTime before UNIX EPOCH!"),
30    }
31}
32
33/// Returns the current time in nanoseconds
34///
35/// # Example
36///
37/// ```no_run
38/// use light_tool::timestamp;
39/// println!("nano second timestamp: {}", timestamp::nano_seconds());
40/// ```
41pub fn nano_seconds() -> u64 {
42    match SystemTime::now().duration_since(UNIX_EPOCH) {
43        Ok(n) => n.as_nanos() as u64,
44        Err(_) => panic!("SystemTime before UNIX EPOCH!"),
45    }
46}
47
48#[cfg(test)]
49mod tests {
50    use super::*;
51
52    #[test]
53    fn test_seconds() {
54        let seconds = seconds();
55        println!("seconds: {}", seconds);
56        assert!(seconds > 0);
57    }
58
59    #[test]
60    fn test_milli_seconds() {
61        let milli_seconds = milli_seconds();
62        println!("milli_seconds: {}", milli_seconds);
63        assert!(milli_seconds > 0);
64    }
65
66    #[test]
67    fn test_nano_seconds() {
68        let nano_seconds = nano_seconds();
69        println!("nano_seconds: {}", nano_seconds);
70        assert!(nano_seconds > 0);
71    }
72}