naming_conventions/conventions/
flat_case.rs

1use crate::{conventions::to_no_case, Convention};
2
3use regex::{Error, Regex};
4
5pub struct FlatCase;
6
7impl Convention for FlatCase {
8    fn to(&self, string: &str) -> Result<String, Error> {
9        to_flat_case(string)
10    }
11
12    fn is(&self, string: &str) -> Result<bool, Error> {
13        is_flat_case(string)
14    }
15}
16
17pub fn to_flat_case(string: &str) -> Result<String, Error> {
18    let no_case = to_no_case(string)?.to_lowercase();
19
20    let re = Regex::new(r"\s+").unwrap();
21    let result = re.replace_all(&no_case, "").to_string();
22
23    log::debug!(target: "convention::flat_case::to_flat_case", "'{}' changed to '{}' (flat_case).", string, result);
24    Ok(result)
25}
26
27pub fn is_flat_case(string: &str) -> Result<bool, Error> {
28    let flat_case = to_flat_case(string)?;
29    Ok(flat_case == string)
30}
31
32#[cfg(test)]
33mod tests {
34    use super::*;
35
36    fn init() {
37        dotenv::dotenv().ok();
38        let _ = env_logger::try_init();
39    }
40
41    #[test]
42    fn test_to_flat_case() {
43        tests::init();
44
45        let result = to_flat_case("vahid_Vakili ").unwrap();
46        assert_eq!(&result, "vahidvakili")
47    }
48
49    #[test]
50    fn test_is_flat_case() {
51        tests::init();
52
53        let result = is_flat_case("vahidvakili").unwrap();
54        assert_eq!(result, true);
55
56        let result = is_flat_case("vahid_Vakili").unwrap();
57        assert_eq!(result, false);
58    }
59}