Skip to main content

qtbridge_gen/utils/
case_conv.rs

1// Copyright (C) 2025 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only
3
4pub fn snake_to_camel(input: &str) -> String {
5    let mut result = String::new();
6    for tok in input.split('_') {
7        let mut chars = tok.chars();
8        if let Some(first_char) = chars.next() {
9            let first_char = if result.is_empty() {
10                first_char.to_ascii_lowercase()
11            } else {
12                first_char.to_ascii_uppercase()
13            };
14            result.push(first_char);
15            result.push_str(chars.as_str());
16        }
17    }
18
19    result
20}
21
22pub fn camel_to_snake(input: &str) -> String {
23    let mut result = String::new();
24    let mut last_capital_pos: i32 = -1;
25    let mut last_ch = '\0';
26
27    for (pos, ch) in input.chars().enumerate() {
28        let pos = pos as i32;
29        let ch_lc = ch.to_ascii_lowercase();
30        if ch_lc != ch {
31            if pos - last_capital_pos > 1 && last_ch != '_' {
32                result.push('_');
33            }
34            last_capital_pos = pos;
35        }
36        result.push(ch_lc);
37        last_ch = ch_lc;
38    }
39
40    result
41}
42
43#[cfg(test)]
44mod tests {
45    use super::{camel_to_snake, snake_to_camel};
46
47    #[test]
48    pub fn require_that_camel_to_snake_returns_output_that_agrees_with_reference() {
49        let cases = [
50            ("", ""),
51            ("one", "one"),
52            ("oneTwoThree", "one_two_three"),
53            ("FirstCapital", "first_capital"),
54            ("already_in_snake", "already_in_snake"),
55            ("capitalAfter_Underscore", "capital_after_underscore"),
56            ("two__underscores_in_snake", "two__underscores_in_snake"),
57            ("RGB", "rgb"),
58            ("getResultAsQVariant", "get_result_as_qvariant"),
59        ];
60
61        for (src, expected) in cases {
62            let actual = camel_to_snake(src);
63            assert_eq!(actual, expected)
64        }
65    }
66
67    #[test]
68    pub fn require_that_snake_to_camel_returns_output_that_agrees_with_reference() {
69        let cases = [
70            ("", ""),
71            ("one", "one"),
72            ("one_two_three", "oneTwoThree"),
73            ("alreadyInCamel", "alreadyInCamel"),
74        ];
75
76        for (src, expected) in cases {
77            let actual = snake_to_camel(src);
78            assert_eq!(actual, expected)
79        }
80    }
81}