aboutsummaryrefslogtreecommitdiff
path: root/src/util/time.rs
blob: b8a85e6a83a8647ef1ed401869cb908f6c871ef6 (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
use anyhow::Result;
use std::thread;
use std::time::SystemTime;

pub fn seconds_since_unix_epoch() -> Result<u64> {
    seconds_since_unix_epoch_of(SystemTime::now())
}

pub fn seconds_since_unix_epoch_of(time: SystemTime) -> Result<u64> {
    Ok(time
        .duration_since(std::time::SystemTime::UNIX_EPOCH)?
        .as_secs())
}

/// Pretty print duration.
pub fn pp_duration(seconds: u64) -> String {
    let minutes = (seconds as f64 / 60.).round();
    let hours = (minutes / 60.).round();
    let days = (hours / 24.).round();

    if seconds < 60 {
        plural(seconds, "seconde")
    } else if minutes < 60. {
        plural(minutes as u64, "minute")
    } else if hours < 24. {
        plural(hours as u64, "heure")
    } else {
        plural(days as u64, "jour")
    }
}

fn plural(n: u64, str: &str) -> String {
    if n <= 1 {
        format!("{} {}", n, str)
    } else {
        format!("{} {}s", n, str)
    }
}

/// Call the function, then sleep if necessary.
///
/// Calling this will at least take the duration asked for in parameters.
pub fn wait_at_least<F>(f: F, d: std::time::Duration) -> Result<()>
where
    F: Fn() -> Result<()>,
{
    let t1 = SystemTime::now();
    f()?;
    let t2 = SystemTime::now();
    let elapsed = t2.duration_since(t1)?;
    if elapsed < d {
        thread::sleep(d - elapsed);
    }
    Ok(())
}