Skip to main content

amq_protocol_codegen/
util.rs

1/// Convert input to camel case
2#[must_use]
3pub fn camel_case(name: &str) -> String {
4    let mut new_word = true;
5    name.chars().fold("".to_string(), |mut result, ch| {
6        if ch == '-' || ch == '_' || ch == ' ' {
7            new_word = true;
8            result
9        } else {
10            result.push(if new_word {
11                ch.to_ascii_uppercase()
12            } else {
13                ch
14            });
15            new_word = false;
16            result
17        }
18    })
19}
20
21/// Convert input to snake case
22///
23/// For the purpose of the AMQP codegen usage, we also handle a few special cases:
24/// "type" and "return" become "kind" and "r#return" if raw is true
25///
26/// A word needs to be composed of at least two letters, this makes UInt become uint and not u_int
27#[must_use]
28pub fn snake_case(name: &str, raw: bool) -> String {
29    match name {
30        "return" if raw => "r#return".to_string(),
31        "type" if !raw => "type".to_string(),
32        "type" => "kind".to_string(),
33        name => {
34            let mut new_word = false;
35            let mut last_was_upper = false;
36            name.chars().fold("".to_string(), |mut result, ch| {
37                if ch == '-' || ch == '_' || ch == ' ' {
38                    new_word = true;
39                    result
40                } else {
41                    let uppercase = ch.is_uppercase();
42                    if new_word || (!last_was_upper && !result.is_empty() && uppercase) {
43                        result.push('_');
44                        new_word = false;
45                    }
46                    last_was_upper = uppercase;
47                    result.push(if uppercase {
48                        ch.to_ascii_lowercase()
49                    } else {
50                        ch
51                    });
52                    result
53                }
54            })
55        }
56    }
57}
58
59#[cfg(test)]
60mod test {
61    use super::*;
62
63    #[test]
64    fn test_camel_case() {
65        assert_eq!(camel_case(""), "");
66        assert_eq!(camel_case("foobar"), "Foobar");
67        assert_eq!(camel_case("FooBar"), "FooBar");
68        assert_eq!(camel_case("foo_bar"), "FooBar");
69        assert_eq!(camel_case("_foo__bar baz-zzz"), "FooBarBazZzz");
70    }
71
72    #[test]
73    fn test_snake_case() {
74        assert_eq!(snake_case("", true), "");
75        assert_eq!(snake_case("Foobar", true), "foobar");
76        assert_eq!(snake_case("FooBar", true), "foo_bar");
77        assert_eq!(snake_case("Foo-BarBaz_zzz", true), "foo_bar_baz_zzz");
78    }
79
80    #[test]
81    fn test_snake_case_uint() {
82        /* special case: we want UInt to be converted as uint */
83        assert_eq!(snake_case("UInt", true), "uint");
84        assert_eq!(snake_case("LongUInt", true), "long_uint");
85    }
86}