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