naming_conventions/conventions/
camel_case.rs

1use crate::{conventions::to_no_case, tool, Convention};
2
3use regex::{Captures, Error, Regex};
4
5pub struct CamelCase;
6
7impl Convention for CamelCase {
8    fn to(&self, string: &str) -> Result<String, Error> {
9        to_camel_case(string)
10    }
11
12    fn is(&self, string: &str) -> Result<bool, Error> {
13        is_camel_case(string)
14    }
15}
16
17pub fn to_camel_case(string: &str) -> Result<String, Error> {
18    let replacement =
19        |haystack: &str, caps: &Captures, _options: &Option<bool>| -> Result<String, Error> {
20            let m = caps.get(0).unwrap();
21            Ok(haystack[m.start()..m.end()].to_uppercase())
22        };
23
24    let no_case = to_no_case(string)?.to_lowercase();
25
26    let re = Regex::new(r"[^\w][a-z]").unwrap();
27    let result = tool::replace_all(&re, &no_case, replacement, &None)?;
28
29    let re = Regex::new(r"\s+").unwrap();
30    let result = re.replace_all(&result, "").to_string();
31
32    log::debug!(target: "convention::camel_case::to_camel_case", "'{}' changed to '{}' (camel_case).", string, result);
33    Ok(result)
34}
35
36pub fn is_camel_case(string: &str) -> Result<bool, Error> {
37    let camel_case = to_camel_case(string)?;
38    Ok(camel_case == string)
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    fn init() {
46        dotenv::dotenv().ok();
47        let _ = env_logger::try_init();
48    }
49
50    #[test]
51    fn test_to_camel_case() {
52        tests::init();
53
54        let result = to_camel_case("vahid_Vakili ").unwrap();
55        assert_eq!(&result, "vahidVakili")
56    }
57
58    #[test]
59    fn test_is_camel_case() {
60        tests::init();
61
62        let result = is_camel_case("vahidVakili").unwrap();
63        assert_eq!(result, true);
64
65        let result = is_camel_case("VahidVakili").unwrap();
66        assert_eq!(result, false);
67    }
68}