Skip to content

Commit 8b6a08b

Browse files
adampetrozesterer
authored andcommitted
Fix panic with byte indexes
1 parent a061071 commit 8b6a08b

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

src/write.rs

+24-1
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,9 @@ impl<S: Span> Report<'_, S> {
7070
let Some((start_line_obj, start_line, start_byte_col)) = src.get_byte_line(given_label_span.start) else {continue;};
7171
let line_text = src.get_line_text(start_line_obj).unwrap();
7272

73-
let num_chars_before_start = line_text[..start_byte_col].chars().count();
73+
let num_chars_before_start = line_text[..start_byte_col.min(line_text.len())]
74+
.chars()
75+
.count();
7476
let start_char_offset = start_line_obj.offset() + num_chars_before_start;
7577

7678
if given_label_span.start >= given_label_span.end {
@@ -985,6 +987,27 @@ mod tests {
985987
"###);
986988
}
987989

990+
#[test]
991+
fn label_of_width_zero_at_end_of_line() {
992+
let source = "apple ==\n";
993+
let msg = Report::<Range<usize>>::build(ReportKind::Error, (), 0)
994+
.with_config(no_color_and_ascii().with_index_type(IndexType::Byte))
995+
.with_message("unexpected end of file")
996+
.with_label(Label::new(9..9).with_message("Unexpected end of file"))
997+
.finish()
998+
.write_to_string(Source::from(source));
999+
1000+
assert_snapshot!(msg, @r###"
1001+
Error: unexpected end of file
1002+
,-[<unknown>:1:1]
1003+
|
1004+
1 | apple ==
1005+
| |
1006+
| `- Unexpected end of file
1007+
---'
1008+
"###);
1009+
}
1010+
9881011
#[test]
9891012
fn multiline_label() {
9901013
let source = "apple\n==\norange";

0 commit comments

Comments
 (0)