Skip to content

Commit 17f1026

Browse files
committed
Improve string helpers functions
1 parent 21dd704 commit 17f1026

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

crates/hir_ty/src/diagnostics/decl_check/str_helpers.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,9 @@ fn is_upper_snake_case(ident: &str) -> bool {
6161

6262
fn is_camel_case(ident: &str) -> bool {
6363
// We assume that the string is either snake case or camel case.
64-
ident.chars().all(|c| c != '_')
64+
// `_` is allowed only at the beginning or in the end of identifier, not between characters.
65+
ident.trim_matches('_').chars().all(|c| c != '_')
66+
&& ident.chars().find(|c| c.is_alphabetic()).map(|c| c.is_ascii_uppercase()).unwrap_or(true)
6567
}
6668

6769
#[cfg(test)]
@@ -80,13 +82,18 @@ mod tests {
8082
fn test_to_lower_snake_case() {
8183
check(to_lower_snake_case, "lower_snake_case", expect![[""]]);
8284
check(to_lower_snake_case, "UPPER_SNAKE_CASE", expect![["upper_snake_case"]]);
85+
check(to_lower_snake_case, "Weird_Case", expect![["weird_case"]]);
8386
check(to_lower_snake_case, "CamelCase", expect![["camel_case"]]);
8487
}
8588

8689
#[test]
8790
fn test_to_camel_case() {
8891
check(to_camel_case, "CamelCase", expect![[""]]);
92+
check(to_camel_case, "CamelCase_", expect![[""]]);
93+
check(to_camel_case, "_CamelCase", expect![[""]]);
8994
check(to_camel_case, "lower_snake_case", expect![["LowerSnakeCase"]]);
9095
check(to_camel_case, "UPPER_SNAKE_CASE", expect![["UpperSnakeCase"]]);
96+
check(to_camel_case, "Weird_Case", expect![["WeirdCase"]]);
97+
check(to_camel_case, "name", expect![["Name"]]);
9198
}
9299
}

crates/stdx/src/lib.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,12 @@ pub fn to_lower_snake_case(s: &str) -> String {
3232
let mut buf = String::with_capacity(s.len());
3333
let mut prev = false;
3434
for c in s.chars() {
35+
// `&& prev` is required to not insert `_` before the first symbol.
3536
if c.is_ascii_uppercase() && prev {
36-
buf.push('_')
37+
// This check is required to not translate `Weird_Case` into `weird__case`.
38+
if buf.chars().last() != Some('_') {
39+
buf.push('_')
40+
}
3741
}
3842
prev = true;
3943

0 commit comments

Comments
 (0)