From 99120d32c13f01b6e146b1f5546c5e2520d73a16 Mon Sep 17 00:00:00 2001 From: Sylvestre Ledru Date: Sun, 24 Sep 2023 23:13:34 +0200 Subject: [PATCH 1/2] cut: fail when the input == usize::MAX --- src/uucore/src/lib/features/ranges.rs | 2 ++ tests/by-util/test_cut.rs | 8 ++++++++ 2 files changed, 10 insertions(+) diff --git a/src/uucore/src/lib/features/ranges.rs b/src/uucore/src/lib/features/ranges.rs index 29f402183..7c09f922d 100644 --- a/src/uucore/src/lib/features/ranges.rs +++ b/src/uucore/src/lib/features/ranges.rs @@ -38,6 +38,8 @@ impl FromStr for Range { fn parse(s: &str) -> Result { match s.parse::() { Ok(0) => Err("fields and positions are numbered from 1"), + // GNU fails when we are at the limit. Match their behavior + Ok(n) if n == usize::MAX => Err("byte/character offset is too large"), Ok(n) => Ok(n), Err(_) => Err("failed to parse range"), } diff --git a/tests/by-util/test_cut.rs b/tests/by-util/test_cut.rs index 7f86c803e..184e413a8 100644 --- a/tests/by-util/test_cut.rs +++ b/tests/by-util/test_cut.rs @@ -117,6 +117,14 @@ fn test_whitespace_with_char() { .code_is(1); } +#[test] +fn test_too_large() { + new_ucmd!() + .args(&["-b1-18446744073709551615", "/dev/null"]) + .fails() + .code_is(1); +} + #[test] fn test_specify_delimiter() { for param in ["-d", "--delimiter", "--del"] { From 265c25871385eaf33c1945609ae5cf6521a790f3 Mon Sep 17 00:00:00 2001 From: Sylvestre Ledru Date: Sun, 24 Sep 2023 23:23:27 +0200 Subject: [PATCH 2/2] ranges: add unit tests to verify the parsing To test them: $ cargo test -p uucore --features ranges --- src/uucore/src/lib/features/ranges.rs | 30 +++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/uucore/src/lib/features/ranges.rs b/src/uucore/src/lib/features/ranges.rs index 7c09f922d..19ba23fb2 100644 --- a/src/uucore/src/lib/features/ranges.rs +++ b/src/uucore/src/lib/features/ranges.rs @@ -161,6 +161,7 @@ pub fn contain(ranges: &[Range], n: usize) -> bool { #[cfg(test)] mod test { use super::{complement, Range}; + use std::str::FromStr; fn m(a: Vec, b: &[Range]) { assert_eq!(Range::merge(a), b); @@ -231,4 +232,33 @@ mod test { // With start and end assert_eq!(complement(&[r(1, 4), r(6, usize::MAX - 1)]), vec![r(5, 5)]); } + + #[test] + fn test_from_str() { + assert_eq!(Range::from_str("5"), Ok(Range { low: 5, high: 5 })); + assert_eq!(Range::from_str("3-5"), Ok(Range { low: 3, high: 5 })); + assert_eq!( + Range::from_str("5-3"), + Err("high end of range less than low end") + ); + assert_eq!(Range::from_str("-"), Err("invalid range with no endpoint")); + assert_eq!( + Range::from_str("3-"), + Ok(Range { + low: 3, + high: usize::MAX - 1 + }) + ); + assert_eq!(Range::from_str("-5"), Ok(Range { low: 1, high: 5 })); + assert_eq!( + Range::from_str("0"), + Err("fields and positions are numbered from 1") + ); + + let max_value = format!("{}", usize::MAX); + assert_eq!( + Range::from_str(&max_value), + Err("byte/character offset is too large") + ); + } }