1#![allow(clippy::unwrap_used)]
2
3use std::time::Duration;
4
5pub use human_time_macros::elapsed;
6
7const UNITS: [(&str, u128); 6] = [
8 ("d", 86400000000),
9 ("h", 3600000000),
10 ("m", 60000000),
11 ("s", 1000000),
12 ("ms", 1000),
13 ("μs", 1),
14];
15
16pub trait ToHumanTimeString {
17 fn to_human_time_string(&self) -> String;
18 fn to_human_time_string_with_format<F, F1>(&self, time_fmt: F, res_fmt: F1) -> String
19 where
20 F: Fn(u128, &str) -> String,
21 F1: Fn(String, String) -> String;
22}
23
24impl ToHumanTimeString for Duration {
25 fn to_human_time_string(&self) -> String {
26 crate::human_time(*self)
27 }
28
29 fn to_human_time_string_with_format<F, F1>(&self, time_fmt: F, res_fmt: F1) -> String
30 where
31 F: Fn(u128, &str) -> String,
32 F1: Fn(String, String) -> String,
33 {
34 human_time_with_format(*self, time_fmt, res_fmt)
35 }
36}
37
38pub fn human_time(d: Duration) -> String {
39 human_time_with_format(
40 d,
41 |n, unit| format!("{}{}", n, unit),
42 |acc, item| format!("{},{}", acc, item),
43 )
44}
45
46pub fn human_time_with_format<F, F1>(d: Duration, time_fmt: F, res_fmt: F1) -> String
47where
48 F: Fn(u128, &str) -> String,
49 F1: Fn(String, String) -> String,
50{
51 let mut map: Vec<(u128, &str)> = Vec::new();
52 let mut μs = d.as_micros();
53 for (unit, n_μs) in UNITS {
54 map.push((μs / n_μs, unit));
55 μs %= n_μs;
56 }
57
58 match map
59 .into_iter()
60 .filter_map(|(n, u)| if n > 0 { Some(time_fmt(n, u)) } else { None })
61 .reduce(res_fmt)
62 {
63 Some(val) => val,
64 None => time_fmt(0, UNITS.last().unwrap().0),
65 }
66}