Skip to main content

hyprstream_rpc_build/
util.rs

1//! Utility functions for name conversion.
2
3/// Convert snake_case or camelCase to PascalCase.
4pub fn to_pascal_case(s: &str) -> String {
5    let mut result = String::with_capacity(s.len());
6    let mut capitalize_next = true;
7
8    for c in s.chars() {
9        if c == '_' || c == '-' {
10            capitalize_next = true;
11        } else if capitalize_next {
12            result.push(c.to_ascii_uppercase());
13            capitalize_next = false;
14        } else {
15            result.push(c);
16        }
17    }
18
19    result
20}
21
22/// Convert PascalCase or camelCase to snake_case.
23pub fn to_snake_case(s: &str) -> String {
24    let mut result = String::with_capacity(s.len() + 4);
25    let chars: Vec<char> = s.chars().collect();
26
27    for (i, &c) in chars.iter().enumerate() {
28        if c.is_ascii_uppercase() {
29            if i > 0 && !chars[i - 1].is_ascii_uppercase() {
30                result.push('_');
31            }
32            if i > 0
33                && chars[i - 1].is_ascii_uppercase()
34                && i + 1 < chars.len()
35                && chars[i + 1].is_ascii_lowercase()
36            {
37                result.push('_');
38            }
39            result.push(c.to_ascii_lowercase());
40        } else {
41            result.push(c);
42        }
43    }
44
45    result
46}
47
48/// Convert a camelCase name to snake_case for use as a TypeScript identifier.
49pub fn to_camel_case(s: &str) -> String {
50    let pascal = to_pascal_case(s);
51    let mut chars = pascal.chars();
52    match chars.next() {
53        None => String::new(),
54        Some(first) => {
55            let mut result = first.to_ascii_lowercase().to_string();
56            result.extend(chars);
57            result
58        }
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    #[test]
67    fn to_pascal_case_works() {
68        assert_eq!(to_pascal_case("hello_world"), "HelloWorld");
69        assert_eq!(to_pascal_case("helloWorld"), "HelloWorld");
70        assert_eq!(to_pascal_case("policy"), "Policy");
71    }
72
73    #[test]
74    fn to_snake_case_works() {
75        assert_eq!(to_snake_case("HelloWorld"), "hello_world");
76        assert_eq!(to_snake_case("helloWorld"), "hello_world");
77        assert_eq!(to_snake_case("HTTPRequest"), "http_request");
78    }
79
80    #[test]
81    fn to_camel_case_works() {
82        assert_eq!(to_camel_case("hello_world"), "helloWorld");
83        assert_eq!(to_camel_case("HelloWorld"), "helloWorld");
84    }
85}