diff options
Diffstat (limited to 'crates/stdx')
-rw-r--r-- | crates/stdx/src/lib.rs | 18 |
1 files changed, 15 insertions, 3 deletions
diff --git a/crates/stdx/src/lib.rs b/crates/stdx/src/lib.rs index 011935cad..59d89f47d 100644 --- a/crates/stdx/src/lib.rs +++ b/crates/stdx/src/lib.rs | |||
@@ -28,20 +28,32 @@ pub fn timeit(label: &'static str) -> impl Drop { | |||
28 | Guard { label, start: Instant::now() } | 28 | Guard { label, start: Instant::now() } |
29 | } | 29 | } |
30 | 30 | ||
31 | pub fn to_lower_snake_case(s: &str) -> String { | 31 | fn to_snake_case<F: Fn(&char) -> char>(s: &str, change_case: F) -> String { |
32 | let mut buf = String::with_capacity(s.len()); | 32 | let mut buf = String::with_capacity(s.len()); |
33 | let mut prev = false; | 33 | let mut prev = false; |
34 | for c in s.chars() { | 34 | for c in s.chars() { |
35 | // `&& prev` is required to not insert `_` before the first symbol. | ||
35 | if c.is_ascii_uppercase() && prev { | 36 | 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.ends_with('_') { | ||
39 | buf.push('_') | ||
40 | } | ||
37 | } | 41 | } |
38 | prev = true; | 42 | prev = true; |
39 | 43 | ||
40 | buf.push(c.to_ascii_lowercase()); | 44 | buf.push(change_case(&c)); |
41 | } | 45 | } |
42 | buf | 46 | buf |
43 | } | 47 | } |
44 | 48 | ||
49 | pub fn to_lower_snake_case(s: &str) -> String { | ||
50 | to_snake_case(s, char::to_ascii_lowercase) | ||
51 | } | ||
52 | |||
53 | pub fn to_upper_snake_case(s: &str) -> String { | ||
54 | to_snake_case(s, char::to_ascii_uppercase) | ||
55 | } | ||
56 | |||
45 | pub fn replace(buf: &mut String, from: char, to: &str) { | 57 | pub fn replace(buf: &mut String, from: char, to: &str) { |
46 | if !buf.contains(from) { | 58 | if !buf.contains(from) { |
47 | return; | 59 | return; |