Skip to content

Commit caf7c44

Browse files
Xylphysylvestre
andauthored
ptx: fix panic when truncation string/keyword contain multibyte Unicode (#10836)
Co-authored-by: Sylvestre Ledru <sylvestre@debian.org>
1 parent 7154766 commit caf7c44

2 files changed

Lines changed: 17 additions & 5 deletions

File tree

src/uu/ptx/src/ptx.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -459,11 +459,11 @@ fn get_output_chunks(
459459
// https://github.com/MaiZure/coreutils-8.3/blob/master/src/ptx.c#L1234
460460
let half_line_size = config.line_width / 2;
461461
let max_before_size = cmp::max(half_line_size as isize - config.gap_size as isize, 0) as usize;
462+
463+
let keyword_len = keyword.chars().count();
464+
let trunc_len = config.trunc_str.chars().count();
462465
let max_after_size = cmp::max(
463-
half_line_size as isize
464-
- (2 * config.trunc_str.len()) as isize
465-
- keyword.len() as isize
466-
- 1,
466+
half_line_size as isize - (2 * trunc_len) as isize - keyword_len as isize - 1,
467467
0,
468468
) as usize;
469469

@@ -504,7 +504,7 @@ fn get_output_chunks(
504504
// and get the string
505505
let after_str: String = all_after[0..after_end].iter().collect();
506506
after.push_str(&after_str);
507-
assert!(max_after_size >= after.len());
507+
assert!(max_after_size >= after.chars().count());
508508

509509
// the tail chunk
510510

tests/by-util/test_ptx.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,18 @@ fn test_unicode_truncation_alignment() {
339339
.stdout_only(" / bar\n föö/\n");
340340
}
341341

342+
#[test]
343+
fn test_unicode_in_after_chunk_does_not_panic() {
344+
// Regression test for a panic in get_output_chunks() when the computed
345+
// max_after_size used byte lengths but the output was assembled as chars.
346+
// The emoji is multibyte in UTF-8 and previously could trigger:
347+
// `assertion failed: max_after_size >= after.len()`.
348+
new_ucmd!()
349+
.pipe_in("We've got +11 more G of 1.70. 🛠\n")
350+
.succeeds()
351+
.stdout_contains("We've got +11");
352+
}
353+
342354
#[test]
343355
fn test_duplicate_input_files() {
344356
new_ucmd!()

0 commit comments

Comments
 (0)