Skip to content

Commit f25918c

Browse files
committed
refactor(human-readable):
- throw away handmade code for time presentation - now all is offloaded to the `humantime` crate
1 parent 6189820 commit f25918c

File tree

1 file changed

+12
-13
lines changed

1 file changed

+12
-13
lines changed

src/common/utils.rs

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use anyhow::Context;
2-
use humantime::parse_duration;
2+
use humantime::{format_duration, parse_duration};
33
use std::time::Duration;
44

55
const ONE_MIN: Duration = Duration::from_secs(60);
@@ -12,18 +12,11 @@ pub trait HumanReadable {
1212

1313
impl HumanReadable for Duration {
1414
fn as_human_readable(&self) -> String {
15-
if self >= &ONE_MIN {
16-
let time = (self.as_secs() / 60) as u128;
17-
let seconds = self.as_secs() - (time * 60) as u64;
18-
return format!("{}m {}s", time, seconds);
19-
} else if self >= &ONE_SEC {
20-
let unit = "s";
21-
return format!("~{}{}", self.as_secs_f32().round(), unit);
15+
if self >= &ONE_SEC && self < &ONE_MIN {
16+
format!("~{}s", self.as_secs_f32().round())
17+
} else {
18+
format_duration(*self).to_string()
2219
}
23-
let time = self.as_millis();
24-
let unit = "ms";
25-
26-
format!("{}{}", time, unit)
2720
}
2821
}
2922

@@ -38,7 +31,7 @@ pub fn parse_delay(s: Option<&str>, t: &str) -> crate::Result<Option<Duration>>
3831
if let Some(d) = s.map(parse_duration) {
3932
let d =
4033
d.with_context(|| format!("{} had an valid format, allowed is 0ms < XXs <= 5m", t))?;
41-
if d.as_millis() <= 0 || d > MAX_DELAY {
34+
if d > MAX_DELAY {
4235
anyhow::bail!("{} was out of range, allowed is 0ms < XXs <= 5m", t)
4336
} else {
4437
Ok(Some(d))
@@ -54,9 +47,15 @@ mod tests {
5447

5548
#[test]
5649
fn should_format_time() {
50+
assert_eq!(
51+
Duration::from_secs(60 * 60 + 1).as_human_readable(),
52+
"1h 1s"
53+
);
5754
assert_eq!(Duration::from_secs(100).as_human_readable(), "1m 40s");
5855
assert_eq!(Duration::from_millis(1200).as_human_readable(), "~1s");
5956
assert_eq!(Duration::from_millis(1800).as_human_readable(), "~2s");
6057
assert_eq!(Duration::from_millis(100).as_human_readable(), "100ms");
58+
assert_eq!(Duration::from_micros(10).as_human_readable(), "10us");
59+
assert_eq!(Duration::from_nanos(10).as_human_readable(), "10ns");
6160
}
6261
}

0 commit comments

Comments
 (0)