amq_protocol_codegen/
util.rs

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