Skip to content
This repository was archived by the owner on Nov 24, 2023. It is now read-only.

Commit fa8a2f0

Browse files
authored
Merge pull request #165 from phansch/fix_out_of_bounds
Fix out of bounds access in parse_snippet
2 parents 2f5f030 + cf0be8b commit fa8a2f0

File tree

3 files changed

+59
-2
lines changed

3 files changed

+59
-2
lines changed

src/lib.rs

+7-2
Original file line numberDiff line numberDiff line change
@@ -114,11 +114,16 @@ fn parse_snippet(span: &DiagnosticSpan) -> Option<Snippet> {
114114
}
115115
let mut tail = String::new();
116116
let last = &span.text[span.text.len() - 1];
117+
118+
// If we get a DiagnosticSpanLine where highlight_end > text.len(), we prevent an 'out of
119+
// bounds' access by making sure the index is within the array bounds.
120+
let last_tail_index = last.highlight_end.min(last.text.len()) - 1;
121+
117122
if span.text.len() > 1 {
118123
body.push('\n');
119-
body.push_str(&last.text[indent..last.highlight_end - 1]);
124+
body.push_str(&last.text[indent..last_tail_index]);
120125
}
121-
tail.push_str(&last.text[last.highlight_end - 1..]);
126+
tail.push_str(&last.text[last_tail_index..]);
122127
Some(Snippet {
123128
file_name: span.file_name.clone(),
124129
line_range: LineRange {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
{
2+
"message": "unterminated double quote string",
3+
"code": null,
4+
"level": "error",
5+
"spans": [
6+
{
7+
"file_name": "./tests/everything/tab_2.rs",
8+
"byte_start": 485,
9+
"byte_end": 526,
10+
"line_start": 12,
11+
"line_end": 13,
12+
"column_start": 7,
13+
"column_end": 3,
14+
"is_primary": true,
15+
"text": [
16+
{
17+
"text": " \"\"\"; //~ ERROR unterminated double quote",
18+
"highlight_start": 7,
19+
"highlight_end": 45
20+
},
21+
{
22+
"text": "}",
23+
"highlight_start": 1,
24+
"highlight_end": 3
25+
}
26+
],
27+
"label": null,
28+
"suggested_replacement": null,
29+
"suggestion_applicability": null,
30+
"expansion": null
31+
}
32+
],
33+
"children": [],
34+
"rendered": "error: unterminated double quote string\n --> ./tests/everything/tab_2.rs:12:7\n |\n12 | \"\"\"; //~ ERROR unterminated double quote\n | _______^\n13 | | }\n | |__^\n\n"
35+
}
36+
{
37+
"message": "aborting due to previous error",
38+
"code": null,
39+
"level": "error",
40+
"spans": [],
41+
"children": [],
42+
"rendered": "error: aborting due to previous error\n\n"
43+
}

tests/edge_cases.rs

+9
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,12 @@ fn multiple_fix_options_yield_no_suggestions() {
1010
.unwrap();
1111
assert!(expected_suggestions.is_empty());
1212
}
13+
14+
#[test]
15+
fn out_of_bounds_test() {
16+
let json = fs::read_to_string("./tests/edge-cases/out_of_bounds.recorded.json").unwrap();
17+
let expected_suggestions =
18+
rustfix::get_suggestions_from_json(&json, &HashSet::new(), rustfix::Filter::Everything)
19+
.unwrap();
20+
assert!(expected_suggestions.is_empty());
21+
}

0 commit comments

Comments
 (0)