aboutsummaryrefslogtreecommitdiff
path: root/macros/src/util/string.rs
blob: b29fe212ce84ab2defedd10c32b3486eff0db896 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
pub fn camelcase_to_snakecase(camelcased: &str) -> String
{
    let mut prev_char_was_lowercase = false;

    camelcased
        .chars()
        .fold(String::new(), |mut acc, character| {
            if character.is_lowercase() {
                prev_char_was_lowercase = true;

                acc.push(character);

                return acc;
            }

            if character.is_uppercase() && prev_char_was_lowercase {
                prev_char_was_lowercase = false;

                acc.push('_');
            }

            acc.push(character.to_ascii_lowercase());

            acc
        })
}

#[cfg(test)]
mod tests
{
    use super::*;

    #[test]
    fn camelcase_to_snakecase_works()
    {
        assert_eq!(camelcase_to_snakecase("LoginHandler"), "login_handler");

        assert_eq!(camelcase_to_snakecase("Transient"), "transient");

        assert_eq!(
            camelcase_to_snakecase("SystemInfoManager"),
            "system_info_manager"
        );
    }
}