fn words(s: &str) -> Vec<String> {
let mut out: Vec<String> = vec![];
let mut cur = String::new();
let mut prev_lower = false;
for c in s.chars() {
if c == '_' || c == '-' || c == ' ' {
if !cur.is_empty() {
out.push(std::mem::take(&mut cur));
}
prev_lower = false;
continue;
}
if c.is_uppercase() && prev_lower && !cur.is_empty() {
out.push(std::mem::take(&mut cur));
}
prev_lower = c.is_lowercase() || c.is_ascii_digit();
cur.extend(c.to_lowercase());
}
if !cur.is_empty() {
out.push(cur);
}
out
}
pub fn snake(s: &str) -> String {
words(s).join("_")
}
pub fn pascal(s: &str) -> String {
words(s)
.iter()
.map(|w| {
let mut c = w.chars();
c.next()
.map(|f| f.to_uppercase().chain(c).collect::<String>())
.unwrap_or_default()
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn casing() {
assert_eq!(snake("PostComment"), "post_comment");
assert_eq!(snake("post-comment"), "post_comment");
assert_eq!(snake("Post"), "post");
assert_eq!(pascal("post_comment"), "PostComment");
assert_eq!(pascal("PostComment"), "PostComment");
assert_eq!(pascal("post"), "Post");
}
}