Fix panic on raw string assist

Strings that do not contain two quotation marks
would cause a slice indexing panic because code
was assuming `find_usual_string_range` would return
a string with two quotes, but it would incorrectly
also return text ranges containing only a single quote.
This commit is contained in:
Alexander Elís Ebenesersson 2019-10-28 03:00:28 +09:00
parent 7dfbe28211
commit 17bd3e59f8

View File

@ -159,10 +159,17 @@ fn count_hashes(s: &str) -> usize {
}
fn find_usual_string_range(s: &str) -> Option<TextRange> {
Some(TextRange::from_to(
TextUnit::from(s.find('"')? as u32),
TextUnit::from(s.rfind('"')? as u32),
))
let left_quote = s.find('"')?;
let right_quote = s.rfind('"')?;
if left_quote == right_quote {
// `s` only contains one quote
None
} else {
Some(TextRange::from_to(
TextUnit::from(left_quote as u32),
TextUnit::from(right_quote as u32),
))
}
}
#[cfg(test)]
@ -271,6 +278,30 @@ string"###;
)
}
#[test]
fn make_raw_string_not_works_on_partial_string() {
check_assist_not_applicable(
make_raw_string,
r#"
fn f() {
let s = "foo<|>
}
"#,
)
}
#[test]
fn make_usual_string_not_works_on_partial_string() {
check_assist_not_applicable(
make_usual_string,
r#"
fn main() {
let s = r#"bar<|>
}
"#,
)
}
#[test]
fn add_hash_target() {
check_assist_target(