Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions src/uucore/src/lib/features/format/spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -550,14 +550,31 @@ fn write_padded(

if left {
writer.write_all(text)?;
write!(writer, "{: <padlen$}", "")
write_spaces(&mut writer, padlen)
} else {
write!(writer, "{: >padlen$}", "")?;
write_spaces(&mut writer, padlen)?;
writer.write_all(text)
}
.map_err(FormatError::IoError)
}

/// Write `n` space bytes directly to `writer`.
///
/// Unlike `write!(writer, "{: <n$}", "")`, this does not feed `n` into Rust's
/// dynamic-width formatting, which panics with "Formatting argument out of
/// range" once the width exceeds `u16::MAX`. A `%s`/`%c` field width above that
/// bound is valid input for `printf`, so it must not panic (#12593, #12900).
fn write_spaces(mut writer: impl Write, n: usize) -> std::io::Result<()> {
const SPACES: [u8; 64] = [b' '; 64];
let mut remaining = n;
while remaining > 0 {
let chunk = remaining.min(SPACES.len());
writer.write_all(&SPACES[..chunk])?;
remaining -= chunk;
}
Ok(())
}

/// Check for a number ending with a '$'
fn eat_argument_position(rest: &mut &[u8], index: &mut usize) -> Option<ArgumentLocation> {
let original_index = *index;
Expand Down
13 changes: 13 additions & 0 deletions tests/by-util/test_printf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,19 @@ fn sub_min_width_negative() {
.stdout_only("hello world ");
}

#[test]
fn sub_string_char_width_above_u16_max_no_panic() {
// A %s/%c field width above u16::MAX must not panic (#12593, #12900).
new_ucmd!()
.args(&["%100000c", "A"])
.succeeds()
.stdout_only(format!("{}A", " ".repeat(99999)));
new_ucmd!()
.args(&["%-100000s", "hi"])
.succeeds()
.stdout_only(format!("hi{}", " ".repeat(99998)));
}

#[test]
fn sub_str_max_chars_input() {
new_ucmd!()
Expand Down
Loading