lib_ruby_parser_nodes/
helpers.rs1pub fn camelcase_to_snakecase(s: &str) -> String {
2 let mut words = vec![];
3 let mut word = String::from("");
4
5 for c in s.chars() {
6 if c.is_uppercase() {
7 words.push(word);
9 word = String::from("");
10 }
11 word.push(c);
12 }
13
14 words.push(word);
15
16 words
17 .into_iter()
18 .filter(|w| !w.is_empty())
19 .collect::<Vec<_>>()
20 .join("_")
21 .to_lowercase()
22}
23
24#[test]
25fn test_camelcase_to_snakecase() {
26 assert_eq!(camelcase_to_snakecase("FooBar"), "foo_bar");
27 assert_eq!(camelcase_to_snakecase("Foo"), "foo");
28 assert_eq!(camelcase_to_snakecase("F"), "f");
29}
30
31pub fn escape_rust_keyword(s: &str) -> String {
32 match s {
33 "const" | "as" | "else" | "self" | "break" | "false" | "for" | "if" | "return" | "str"
34 | "super" | "true" | "while" | "yield" => format!("{}_", s),
35 _ => s.to_string(),
36 }
37}
38
39#[test]
40fn test_escape_rust_keyword() {
41 assert_eq!(escape_rust_keyword("foo"), "foo");
42 assert_eq!(escape_rust_keyword("while"), "while_");
43}
44
45pub fn snakecase_to_camelcase(s: &str) -> String {
46 fn capitalize_word(s: &str) -> String {
47 let mut c = s.chars();
48 match c.next() {
49 None => String::new(),
50 Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
51 }
52 }
53
54 s.split('_').map(capitalize_word).collect()
55}
56
57#[test]
58fn test_snakecase_to_camelcase() {
59 assert_eq!(snakecase_to_camelcase("foo_bar"), "FooBar");
60 assert_eq!(snakecase_to_camelcase("foo"), "Foo");
61 assert_eq!(snakecase_to_camelcase("f"), "F");
62}
63
64pub fn escape_c_keyword(s: &str) -> String {
65 match s {
66 "default" | "operator" | "else" | "const" | "and" | "break" | "case" | "class"
67 | "false" | "float" | "for" | "if" | "int" | "or" | "return" | "true" | "while" => {
68 format!("{}_", s)
69 }
70 _ => s.to_string(),
71 }
72}
73
74#[test]
75fn test_escape_c_keyword() {
76 assert_eq!(escape_c_keyword("foo"), "foo");
77 assert_eq!(escape_c_keyword("default"), "default_");
78}
79
80pub fn escape_cpp_keyword(s: &str) -> String {
81 match s {
82 "default" | "operator" | "else" | "const" | "and" | "break" | "case" | "class"
83 | "false" | "float" | "for" | "if" | "int" | "or" | "return" | "true" | "while"
84 | "ERANGE" => format!("{}_", s),
85 _ => s.to_string(),
86 }
87}
88
89#[test]
90fn test_escape_cpp_keyword() {
91 assert_eq!(escape_cpp_keyword("foo"), "foo");
92 assert_eq!(escape_cpp_keyword("default"), "default_");
93}
94
95pub fn escape_js_keyword(s: &str) -> String {
96 match s {
97 "const" | "default" | "var" | "else" => format!("{}_", s),
98 _ => s.to_string(),
99 }
100}
101
102#[test]
103fn test_escape_js_keyword() {
104 assert_eq!(escape_js_keyword("var"), "var_");
105 assert_eq!(escape_js_keyword("foo"), "foo");
106}