1 | //! Contains utilities used to convert strings between different cases. |
2 | |
3 | /// Convert to pascal or camel case, assuming snake case. |
4 | /// |
5 | /// If `s` is already in pascal or camel case, should yield the same result. |
6 | pub fn pascal_or_camel_case(s: &str, is_pascal_case: bool) -> String { |
7 | let mut result: String = String::new(); |
8 | let mut capitalize: bool = is_pascal_case; |
9 | let mut first: bool = true; |
10 | for ch: char in s.chars() { |
11 | if ch == '_' { |
12 | capitalize = true; |
13 | } else if capitalize { |
14 | result.push(ch:ch.to_ascii_uppercase()); |
15 | capitalize = false; |
16 | } else if first && !is_pascal_case { |
17 | result.push(ch:ch.to_ascii_lowercase()); |
18 | } else { |
19 | result.push(ch); |
20 | } |
21 | |
22 | if first { |
23 | first = false; |
24 | } |
25 | } |
26 | result |
27 | } |
28 | |
29 | /// Convert to snake case, assuming pascal case. |
30 | /// |
31 | /// If `s` is already in snake case, should yield the same result. |
32 | pub fn snake_case(s: &str) -> String { |
33 | let mut snake: String = String::new(); |
34 | for ch: char in s.chars() { |
35 | if ch.is_ascii_uppercase() && !snake.is_empty() { |
36 | snake.push(ch:'_' ); |
37 | } |
38 | snake.push(ch:ch.to_ascii_lowercase()); |
39 | } |
40 | snake |
41 | } |
42 | |