From d604f709cea04b6ae25b66ee8c192c4262fd0b98 Mon Sep 17 00:00:00 2001 From: Daniel Hofstetter Date: Tue, 15 Aug 2023 13:07:22 +0200 Subject: [PATCH] nl: handle line number overflow --- src/uu/nl/src/nl.rs | 5 ++++- tests/by-util/test_nl.rs | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/uu/nl/src/nl.rs b/src/uu/nl/src/nl.rs index 115b4efa95e..5bb1eb9e4c6 100644 --- a/src/uu/nl/src/nl.rs +++ b/src/uu/nl/src/nl.rs @@ -344,7 +344,10 @@ fn nl(reader: &mut BufReader, settings: &Settings) -> UResult<()> { line ); // update line number for the potential next line - line_no += settings.line_increment; + match line_no.checked_add(settings.line_increment) { + Some(new_line_no) => line_no = new_line_no, + None => return Err(USimpleError::new(1, "line number overflow")), + } } else { let spaces = " ".repeat(settings.number_width + 1); println!("{spaces}{line}"); diff --git a/tests/by-util/test_nl.rs b/tests/by-util/test_nl.rs index e178950b315..4aa95030b76 100644 --- a/tests/by-util/test_nl.rs +++ b/tests/by-util/test_nl.rs @@ -464,3 +464,21 @@ fn test_invalid_regex_numbering() { .stderr_contains("invalid regular expression"); } } + +#[test] +fn test_line_number_overflow() { + new_ucmd!() + .arg(format!("--starting-line-number={}", i64::MAX)) + .pipe_in("a\nb") + .fails() + .stdout_is(format!("{}\ta\n", i64::MAX)) + .stderr_is("nl: line number overflow\n"); + + new_ucmd!() + .arg(format!("--starting-line-number={}", i64::MIN)) + .arg("--line-increment=-1") + .pipe_in("a\nb") + .fails() + .stdout_is(format!("{}\ta\n", i64::MIN)) + .stderr_is("nl: line number overflow\n"); +}