diff options
author | HampusM <hampus@hampusmat.com> | 2023-09-25 22:09:52 +0200 |
---|---|---|
committer | HampusM <hampus@hampusmat.com> | 2023-10-01 10:47:49 +0200 |
commit | 1fc0371867b02127a5da63f01f03d264b382b552 (patch) | |
tree | 1e4222dc8cffed7903a4553fee1cf5030d6a3289 /macros/src/util/string.rs | |
parent | 731b5138686c25247f61480e5e468ab4a01ac020 (diff) |
refactor: make camel cased text snake cased without regex
Diffstat (limited to 'macros/src/util/string.rs')
-rw-r--r-- | macros/src/util/string.rs | 39 |
1 files changed, 29 insertions, 10 deletions
diff --git a/macros/src/util/string.rs b/macros/src/util/string.rs index a04a021..b29fe21 100644 --- a/macros/src/util/string.rs +++ b/macros/src/util/string.rs @@ -1,14 +1,28 @@ -use once_cell::sync::Lazy; -use regex::Regex; - -static CAMELCASE_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"([a-z])([A-Z])").unwrap()); - pub fn camelcase_to_snakecase(camelcased: &str) -> String { - CAMELCASE_RE - .replace(camelcased, "${1}_$2") - .to_string() - .to_lowercase() + let mut prev_char_was_lowercase = false; + + camelcased + .chars() + .fold(String::new(), |mut acc, character| { + if character.is_lowercase() { + prev_char_was_lowercase = true; + + acc.push(character); + + return acc; + } + + if character.is_uppercase() && prev_char_was_lowercase { + prev_char_was_lowercase = false; + + acc.push('_'); + } + + acc.push(character.to_ascii_lowercase()); + + acc + }) } #[cfg(test)] @@ -21,6 +35,11 @@ mod tests { assert_eq!(camelcase_to_snakecase("LoginHandler"), "login_handler"); - assert_eq!(camelcase_to_snakecase("Regex"), "regex"); + assert_eq!(camelcase_to_snakecase("Transient"), "transient"); + + assert_eq!( + camelcase_to_snakecase("SystemInfoManager"), + "system_info_manager" + ); } } |