Skip to content

Commit 6195096

Browse files
author
Geobert Quach
committed
feat(assists): Even smarter with hashes
Count `"#*` streak only, extract the counting in a function, unit test this function
1 parent b06c5fa commit 6195096

File tree

1 file changed

+44
-12
lines changed

1 file changed

+44
-12
lines changed

crates/ra_assists/src/assists/raw_string.rs

+44-12
Original file line numberDiff line numberDiff line change
@@ -28,17 +28,7 @@ pub(crate) fn make_raw_string(mut ctx: AssistCtx<impl HirDatabase>) -> Option<As
2828
if error.is_err() {
2929
eprintln!("Error unescaping string");
3030
} else {
31-
let mut max_hash_streak = 0;
32-
unescaped.chars().fold(0, |acc, c| {
33-
if c == '#' {
34-
acc + 1
35-
} else {
36-
if acc > max_hash_streak {
37-
max_hash_streak = acc;
38-
}
39-
0
40-
}
41-
});
31+
let max_hash_streak = count_hashes(&unescaped);
4232
let mut hashes = String::with_capacity(max_hash_streak + 1);
4333
for _ in 0..hashes.capacity() {
4434
hashes.push('#');
@@ -52,6 +42,19 @@ pub(crate) fn make_raw_string(mut ctx: AssistCtx<impl HirDatabase>) -> Option<As
5242
ctx.build()
5343
}
5444

45+
fn count_hashes(s: &str) -> usize {
46+
let indexes: Vec<_> = s.match_indices("\"#").map(|(i, _)| i).collect();
47+
let mut max_hash_streak = 0usize;
48+
for idx in indexes {
49+
let (_, sub) = s.split_at(idx + 1);
50+
let nb_hash = sub.chars().take_while(|c| *c == '#').count();
51+
if nb_hash > max_hash_streak {
52+
max_hash_streak = nb_hash;
53+
}
54+
}
55+
max_hash_streak
56+
}
57+
5558
fn find_usual_string_range(s: &str) -> Option<TextRange> {
5659
Some(TextRange::from_to(
5760
TextUnit::from(s.find('"')? as u32),
@@ -165,12 +168,31 @@ string"#;
165168
"###,
166169
r####"
167170
fn f() {
168-
let s = <|>r###"#random##
171+
let s = <|>r#"#random##
172+
string"#;
173+
}
174+
"####,
175+
)
176+
}
177+
178+
#[test]
179+
fn make_raw_string_closing_hashes_inside_works() {
180+
check_assist(
181+
make_raw_string,
182+
r###"
183+
fn f() {
184+
let s = <|>"#random\"##\nstring";
185+
}
186+
"###,
187+
r####"
188+
fn f() {
189+
let s = <|>r###"#random"##
169190
string"###;
170191
}
171192
"####,
172193
)
173194
}
195+
174196
#[test]
175197
fn make_raw_string_nothing_to_unescape_works() {
176198
check_assist(
@@ -410,4 +432,14 @@ string"###;
410432
"#,
411433
);
412434
}
435+
436+
#[test]
437+
fn count_hashes_test() {
438+
assert_eq!(0, count_hashes("abc"));
439+
assert_eq!(0, count_hashes("###"));
440+
assert_eq!(1, count_hashes("\"#abc"));
441+
assert_eq!(0, count_hashes("#abc"));
442+
assert_eq!(2, count_hashes("#ab\"##c"));
443+
assert_eq!(4, count_hashes("#ab\"##\"####c"));
444+
}
413445
}

0 commit comments

Comments
 (0)