diff --git a/src/uu/pr/src/pr.rs b/src/uu/pr/src/pr.rs index 029f475625d..99eb867c532 100644 --- a/src/uu/pr/src/pr.rs +++ b/src/uu/pr/src/pr.rs @@ -105,34 +105,11 @@ impl FileLine { buf: &[u8], options: &OutputOptions, ) -> Result { - let line_content = if let Some(expand_tabs) = &options.expand_tabs { - // Expanding tabs can make a line far longer than the input, so - // bound it like GNU does. The exact length is only worth measuring - // when every byte growing to a full tab stop could pass the limit. - let widest_stop = (expand_tabs.width as usize).max(8); - if buf.len().saturating_mul(widest_stop) > i32::MAX as usize { - let expanded = buf - .iter() - .fold(0, |len, b| len + expanded_byte_width(len, *b, expand_tabs)); - if expanded > i32::MAX as usize { - return Err(PrError::IntegerOverflow); - } - } - let mut result = - Vec::with_capacity(buf.len() + buf.len() / 20 * expand_tabs.width as usize); - for b in buf { - apply_expand_tab(&mut result, *b, expand_tabs); - } - result - } else { - buf.to_vec() - }; - Ok(Self { file_id, page_number, line_number: Some(line_number), - line_content, + line_content: prepare_line(buf, options.expand_tabs.as_ref())?, unterminated: false, }) } @@ -1145,30 +1122,57 @@ fn read_to_end(name: &OsStr) -> Result, PrError> { } } -/// How many bytes `byte` takes once expanded, written at column `len`. -fn expanded_byte_width(len: usize, byte: u8, expand_options: &ExpandTabsOptions) -> usize { - if byte == expand_options.input_char as u8 { - // If the byte encountered is the input char we use width to calculate - // the amount of spaces needed (if no input char given we stored '\t' - // in our struct) - expand_options.width as usize - (len % expand_options.width as usize) - } else if byte == TAB as u8 { - // If a byte got passed to the -e flag (eg -ea1) which is not '\t' GNU - // still expands it but does not use an optionally given width parameter - // but does the '\t' expansion with the default value (8) - 8 - (len % 8) - } else { - 1 +/// Expand input tabs and keep backspaces within the current text column. +fn prepare_line(buf: &[u8], tabs: Option<&ExpandTabsOptions>) -> Result, PrError> { + if tabs.is_none() && memchr::memchr(b'\x08', buf).is_none() { + return Ok(buf.to_vec()); } -} -fn apply_expand_tab(chunk: &mut Vec, byte: u8, expand_options: &ExpandTabsOptions) { - if byte == expand_options.input_char as u8 || byte == TAB as u8 { - let spaces_needed = expanded_byte_width(chunk.len(), byte, expand_options); - chunk.extend(std::iter::repeat_n(b' ', spaces_needed)); - } else { - chunk.push(byte); + // The input position can move backward even as the output buffer grows. + let mut column = 0_u64; + let runs = buf.iter().map(move |&byte| { + let tab_width = match tabs { + Some(tabs) if byte == tabs.input_char as u8 => tabs.width as u64, + _ if byte == b'\t' => 8, + _ => 0, + }; + if tab_width != 0 { + let spaces = tab_width - column % tab_width; + column += spaces; + if tabs.is_some() { + return (b' ', spaces as usize); + } + } else if byte == b'\x08' { + if column == 0 { + return (byte, 0); + } + column -= 1; + } else if !byte.is_ascii_control() { + column += 1; + } + (byte, 1) + }); + + // Measure unusually large expansions before allocating any of their output. + let mut capacity = buf.len(); + if let Some(tabs) = tabs + && buf.len().saturating_mul((tabs.width as usize).max(8)) > MAX_INT_VALUE + { + capacity = runs + .clone() + .try_fold(0_i32, |len, (_, count)| len.checked_add(count as i32)) + .ok_or(PrError::IntegerOverflow)? as usize; + } + + let mut result = Vec::with_capacity(capacity); + for (byte, count) in runs { + if count == 1 { + result.push(byte); + } else { + result.extend(std::iter::repeat_n(byte, count)); + } } + Ok(result) } fn pr(name: &OsStr, options: &OutputOptions) -> Result { diff --git a/tests/by-util/test_pr.rs b/tests/by-util/test_pr.rs index 49be062f101..63529ca9e4d 100644 --- a/tests/by-util/test_pr.rs +++ b/tests/by-util/test_pr.rs @@ -1212,6 +1212,32 @@ fn test_simple_expand_tab() { .stdout_matches(&output_regex); } +#[test] +fn test_backspace_at_start_of_column() { + new_ucmd!() + .arg("-t") + .pipe_in("\x08L\nx\x08\x08R\n\t\x08\x08Z\n") + .succeeds() + .stdout_only("L\nx\x08R\n\t\x08\x08Z\n"); +} + +#[rstest] +#[case::tab("-e4", "ab\x08\tQ\n", "ab\x08 Q\n")] +#[case::zero_width_control("-e4", "a\r\x08\tQ\n", "a\r\x08 Q\n")] +#[case::custom_tab_then_tab("-e@3", "ab\x08@Q\tR\n", "ab\x08 Q R\n")] +#[case::backspace_as_input_tab("-e\x083", "\x08a\x08Q\n", " a Q\n")] +fn test_tab_expansion_with_backspaces( + #[case] option: &str, + #[case] input: &str, + #[case] output: &str, +) { + new_ucmd!() + .args(&["-t", option]) + .pipe_in(input) + .succeeds() + .stdout_only(output); +} + #[test] fn test_expand_tab_at_end_of_short_flag_cluster() { // `-e` closing a cluster of value-less short flags carries no attached argument, so it has