From f4af22682068f44a32523ad929b3a3f3e66f156b Mon Sep 17 00:00:00 2001 From: Jeffrey Finkelstein Date: Sun, 20 Mar 2022 15:35:32 -0400 Subject: [PATCH] uucore: error on negative interval in parse_time Return an error when a negative interval is provided as the argument to `uucore::parse_time::from_str()`, since a `Duration` should only be non-negative. --- src/uucore/src/lib/parser/parse_time.rs | 9 +++++++++ tests/by-util/test_sleep.rs | 8 ++++++++ tests/by-util/test_timeout.rs | 8 ++++++++ 3 files changed, 25 insertions(+) diff --git a/src/uucore/src/lib/parser/parse_time.rs b/src/uucore/src/lib/parser/parse_time.rs index 366eebdea..79387c0b1 100644 --- a/src/uucore/src/lib/parser/parse_time.rs +++ b/src/uucore/src/lib/parser/parse_time.rs @@ -63,6 +63,10 @@ pub fn from_str(string: &str) -> Result { .parse::() .map_err(|e| format!("invalid time interval {}: {}", string.quote(), e))?; + if num < 0. { + return Err(format!("invalid time interval {}", string.quote())); + } + const NANOS_PER_SEC: u32 = 1_000_000_000; let whole_secs = num.trunc(); let nanos = (num.fract() * (NANOS_PER_SEC as f64)).trunc(); @@ -105,4 +109,9 @@ mod tests { fn test_error_invalid_magnitude() { assert!(from_str("12abc3s").is_err()); } + + #[test] + fn test_negative() { + assert!(from_str("-1").is_err()); + } } diff --git a/tests/by-util/test_sleep.rs b/tests/by-util/test_sleep.rs index 6c3f940e8..c7c6b3af1 100644 --- a/tests/by-util/test_sleep.rs +++ b/tests/by-util/test_sleep.rs @@ -149,3 +149,11 @@ fn test_sum_overflow() { .no_stderr() .no_stdout(); } + +#[test] +fn test_negative_interval() { + new_ucmd!() + .args(&["--", "-1"]) + .fails() + .usage_error("invalid time interval '-1'"); +} diff --git a/tests/by-util/test_timeout.rs b/tests/by-util/test_timeout.rs index ac2d3e539..01ff85590 100644 --- a/tests/by-util/test_timeout.rs +++ b/tests/by-util/test_timeout.rs @@ -89,3 +89,11 @@ fn test_dont_overflow() { .no_stderr() .no_stdout(); } + +#[test] +fn test_negative_interval() { + new_ucmd!() + .args(&["--", "-1", "sleep", "0"]) + .fails() + .usage_error("invalid time interval '-1'"); +}