Skip to content

Commit 4fc5650

Browse files
authored
Simplify Unicode-aware trimming
1 parent e9a93be commit 4fc5650

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

src/librustc_errors/emitter.rs

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -529,18 +529,21 @@ impl EmitterWriter {
529529
let left = margin.left(line_len);
530530
let right = margin.right(line_len);
531531
// On long lines, we strip the source line, accounting for unicode.
532-
let mut taken = 0;
533-
let code: String = source_string.chars().skip(left).take_while(|ch| {
534-
// Make sure that the trimming on the right will fall within the terminal width.
535-
// FIXME: `unicode_width` sometimes disagrees with terminals on how wide a `char` is.
536-
// For now, just accept that sometimes the code line will be longer than desired.
537-
let next = unicode_width::UnicodeWidthChar::width(*ch).unwrap_or(1);
538-
if taken + next > right - left {
539-
return false;
540-
}
541-
taken += next;
542-
true
543-
}).collect();
532+
// Make sure that the trimming on the right will fall within the terminal width.
533+
// FIXME: `unicode_width` sometimes disagrees with terminals on how wide a `char` is.
534+
// For now, just accept that sometimes the code line will be longer than desired.
535+
let code: String = source_string.chars().skip(left)
536+
.map(|ch| {
537+
let width = unicode_width::UnicodeWidthChar::width(*ch).unwrap_or(1);
538+
(width, ch)
539+
})
540+
.scan(0, |len, (width, ch)| {
541+
*len += width;
542+
Some(*len, ch)
543+
})
544+
.take_while(|&(prefix_len, _ch)| prefix_len <= right - left)
545+
.map(|(_prefix_len, ch)| ch)
546+
.collect();
544547
buffer.puts(line_offset, code_offset, &code, Style::Quotation);
545548
if margin.was_cut_left() {
546549
// We have stripped some code/whitespace from the beginning, make it clear.

0 commit comments

Comments
 (0)