naming_conventions/conventions/
macro_case.rs1use crate::{conventions::to_no_case, Convention};
2
3use regex::{Error, Regex};
4
5pub struct MacroCase;
6
7impl Convention for MacroCase {
8 fn to(&self, string: &str) -> Result<String, Error> {
9 to_macro_case(string)
10 }
11
12 fn is(&self, string: &str) -> Result<bool, Error> {
13 is_macro_case(string)
14 }
15}
16
17pub fn to_macro_case(string: &str) -> Result<String, Error> {
18 let no_case = to_no_case(string)?.to_uppercase();
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::macro_case::to_macro_case", "'{}' changed to '{}' (macro_case).", string, result);
24 Ok(result)
25}
26
27pub fn is_macro_case(string: &str) -> Result<bool, Error> {
28 let macro_case = to_macro_case(string)?;
29 Ok(macro_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_macro_case() {
43 tests::init();
44
45 let result = to_macro_case("vahid_Vakili ").unwrap();
46 assert_eq!(&result, "VAHID_VAKILI")
47 }
48
49 #[test]
50 fn test_is_macro_case() {
51 tests::init();
52
53 let result = is_macro_case("VAHID_VAKILI").unwrap();
54 assert_eq!(result, true);
55
56 let result = is_macro_case("VAHID_Vakili").unwrap();
57 assert_eq!(result, false);
58 }
59}