Skip to content

Commit

Permalink
unexpand: handle too large "tabs" arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
cakebaker authored and sylvestre committed Jun 22, 2022
1 parent 75edeea commit cf605c2
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
19 changes: 13 additions & 6 deletions src/uu/unexpand/src/unexpand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use std::error::Error;
use std::fmt;
use std::fs::File;
use std::io::{stdin, stdout, BufRead, BufReader, BufWriter, Read, Stdout, Write};
use std::num::IntErrorKind;
use std::str::from_utf8;
use unicode_width::UnicodeWidthChar;
use uucore::display::Quotable;
Expand All @@ -33,6 +34,7 @@ const DEFAULT_TABSTOP: usize = 8;
enum ParseError {
InvalidCharacter(String),
TabSizeCannotBeZero,
TabSizeTooLarge,
TabSizesMustBeAscending,
}

Expand All @@ -46,6 +48,7 @@ impl fmt::Display for ParseError {
write!(f, "tab size contains invalid character(s): {}", s.quote())
}
Self::TabSizeCannotBeZero => write!(f, "tab size cannot be 0"),
Self::TabSizeTooLarge => write!(f, "tab stop value is too large"),
Self::TabSizesMustBeAscending => write!(f, "tab sizes must be ascending"),
}
}
Expand All @@ -57,12 +60,16 @@ fn tabstops_parse(s: &str) -> Result<Vec<usize>, ParseError> {
let mut nums = Vec::new();

for word in words {
if let Ok(num) = word.parse() {
nums.push(num);
} else {
return Err(ParseError::InvalidCharacter(
word.trim_start_matches(char::is_numeric).to_string(),
));
match word.parse::<usize>() {
Ok(num) => nums.push(num),
Err(e) => match e.kind() {
IntErrorKind::PosOverflow => return Err(ParseError::TabSizeTooLarge),
_ => {
return Err(ParseError::InvalidCharacter(
word.trim_start_matches(char::is_numeric).to_string(),
))
}
},
}
}

Expand Down
8 changes: 8 additions & 0 deletions tests/by-util/test_unexpand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,3 +218,11 @@ fn test_tabs_with_invalid_chars() {
.fails()
.stderr_contains("tab size contains invalid character(s): 'x2'");
}

#[test]
fn test_tabs_shortcut_with_too_large_size() {
let arg = format!("-{}", u128::MAX);
let expected_error = "tab stop value is too large";

new_ucmd!().arg(arg).fails().stderr_contains(expected_error);
}

0 comments on commit cf605c2

Please sign in to comment.