1
1
use anyhow:: Context ;
2
- use humantime:: parse_duration;
2
+ use humantime:: { format_duration , parse_duration} ;
3
3
use std:: time:: Duration ;
4
4
5
5
const ONE_MIN : Duration = Duration :: from_secs ( 60 ) ;
@@ -12,18 +12,11 @@ pub trait HumanReadable {
12
12
13
13
impl HumanReadable for Duration {
14
14
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 ( )
22
19
}
23
- let time = self . as_millis ( ) ;
24
- let unit = "ms" ;
25
-
26
- format ! ( "{}{}" , time, unit)
27
20
}
28
21
}
29
22
@@ -38,7 +31,7 @@ pub fn parse_delay(s: Option<&str>, t: &str) -> crate::Result<Option<Duration>>
38
31
if let Some ( d) = s. map ( parse_duration) {
39
32
let d =
40
33
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 {
42
35
anyhow:: bail!( "{} was out of range, allowed is 0ms < XXs <= 5m" , t)
43
36
} else {
44
37
Ok ( Some ( d) )
@@ -54,9 +47,15 @@ mod tests {
54
47
55
48
#[ test]
56
49
fn should_format_time ( ) {
50
+ assert_eq ! (
51
+ Duration :: from_secs( 60 * 60 + 1 ) . as_human_readable( ) ,
52
+ "1h 1s"
53
+ ) ;
57
54
assert_eq ! ( Duration :: from_secs( 100 ) . as_human_readable( ) , "1m 40s" ) ;
58
55
assert_eq ! ( Duration :: from_millis( 1200 ) . as_human_readable( ) , "~1s" ) ;
59
56
assert_eq ! ( Duration :: from_millis( 1800 ) . as_human_readable( ) , "~2s" ) ;
60
57
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" ) ;
61
60
}
62
61
}
0 commit comments