Skip to main content

nautilus_core/string/
conversions.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! String case conversions (`snake_case`, Title Case).
17
18/// Converts a string from any common case to `snake_case`.
19///
20/// Word boundaries are detected at:
21/// - Non-alphanumeric characters (spaces, hyphens, underscores, colons, etc.)
22/// - Transitions from lowercase or digit to uppercase (`camelCase` -> `camel_case`)
23/// - Within consecutive uppercase letters, before the last if followed by lowercase
24///   (`XMLParser` -> `xml_parser`)
25#[must_use]
26pub fn to_snake_case(s: &str) -> String {
27    if s.is_ascii() {
28        to_snake_case_ascii(s.as_bytes())
29    } else {
30        to_snake_case_unicode(s)
31    }
32}
33
34fn to_snake_case_ascii(bytes: &[u8]) -> String {
35    // Single pass over bytes. Mode tracks the case of the last cased character
36    // within the current alphanumeric run, matching heck's word-boundary rules.
37    const BOUNDARY: u8 = 0;
38    const LOWER: u8 = 1;
39    const UPPER: u8 = 2;
40
41    let len = bytes.len();
42    let mut result = String::with_capacity(len + len / 4);
43    let mut first_word = true;
44    let mut mode: u8 = BOUNDARY;
45    let mut word_start = 0;
46    let mut i = 0;
47
48    while i < len {
49        let b = bytes[i];
50
51        if !b.is_ascii_alphanumeric() {
52            if word_start < i {
53                push_lower_ascii(&mut result, &bytes[word_start..i], &mut first_word);
54            }
55            word_start = i + 1;
56            mode = BOUNDARY;
57            i += 1;
58            continue;
59        }
60
61        let next_mode = if b.is_ascii_lowercase() {
62            LOWER
63        } else if b.is_ascii_uppercase() {
64            UPPER
65        } else {
66            mode
67        };
68
69        if i + 1 < len && bytes[i + 1].is_ascii_alphanumeric() {
70            let next = bytes[i + 1];
71
72            if next_mode == LOWER && next.is_ascii_uppercase() {
73                push_lower_ascii(&mut result, &bytes[word_start..=i], &mut first_word);
74                word_start = i + 1;
75                mode = BOUNDARY;
76            } else if mode == UPPER && b.is_ascii_uppercase() && next.is_ascii_lowercase() {
77                if word_start < i {
78                    push_lower_ascii(&mut result, &bytes[word_start..i], &mut first_word);
79                }
80                word_start = i;
81                mode = BOUNDARY;
82            } else {
83                mode = next_mode;
84            }
85        }
86
87        i += 1;
88    }
89
90    if word_start < len && bytes[word_start].is_ascii_alphanumeric() {
91        push_lower_ascii(&mut result, &bytes[word_start..], &mut first_word);
92    }
93
94    result
95}
96
97fn push_lower_ascii(result: &mut String, word: &[u8], first_word: &mut bool) {
98    if !*first_word {
99        result.push('_');
100    }
101    *first_word = false;
102
103    for &b in word {
104        result.push(char::from(b.to_ascii_lowercase()));
105    }
106}
107
108fn to_snake_case_unicode(s: &str) -> String {
109    #[derive(Clone, Copy, PartialEq)]
110    enum Mode {
111        Boundary,
112        Lowercase,
113        Uppercase,
114    }
115
116    let mut result = String::with_capacity(s.len() + s.len() / 4);
117    let mut first_word = true;
118
119    for word in s.split(|c: char| !c.is_alphanumeric()) {
120        let mut char_indices = word.char_indices().peekable();
121        let mut init = 0;
122        let mut mode = Mode::Boundary;
123
124        while let Some((i, c)) = char_indices.next() {
125            if let Some(&(next_i, next)) = char_indices.peek() {
126                let next_mode = if c.is_lowercase() {
127                    Mode::Lowercase
128                } else if c.is_uppercase() {
129                    Mode::Uppercase
130                } else {
131                    mode
132                };
133
134                if next_mode == Mode::Lowercase && next.is_uppercase() {
135                    push_lower_unicode(&mut result, &word[init..next_i], &mut first_word);
136                    init = next_i;
137                    mode = Mode::Boundary;
138                } else if mode == Mode::Uppercase && c.is_uppercase() && next.is_lowercase() {
139                    push_lower_unicode(&mut result, &word[init..i], &mut first_word);
140                    init = i;
141                    mode = Mode::Boundary;
142                } else {
143                    mode = next_mode;
144                }
145            } else {
146                push_lower_unicode(&mut result, &word[init..], &mut first_word);
147                break;
148            }
149        }
150    }
151
152    result
153}
154
155fn push_lower_unicode(result: &mut String, word: &str, first_word: &mut bool) {
156    if !*first_word {
157        result.push('_');
158    }
159    *first_word = false;
160
161    for c in word.chars() {
162        for lc in c.to_lowercase() {
163            result.push(lc);
164        }
165    }
166}
167
168/// Title-cases `s` by capitalizing the first letter of each alphabetic run.
169///
170/// Mirrors Python's `str.title()`: word boundaries fall at any non-alphabetic
171/// character, the first letter of each run is uppercased, and the rest are
172/// lowercased.
173///
174/// # Examples
175///
176/// ```
177/// use nautilus_core::string::conversions::title_case;
178///
179/// assert_eq!(title_case("example"), "Example");
180/// assert_eq!(title_case("hello_world"), "Hello_World");
181/// assert_eq!(title_case("hello world"), "Hello World");
182/// assert_eq!(title_case(""), "");
183/// ```
184#[must_use]
185pub fn title_case(s: &str) -> String {
186    let mut out = String::with_capacity(s.len());
187    let mut prev_alpha = false;
188
189    for ch in s.chars() {
190        if ch.is_alphabetic() {
191            if prev_alpha {
192                out.extend(ch.to_lowercase());
193            } else {
194                out.extend(ch.to_uppercase());
195            }
196            prev_alpha = true;
197        } else {
198            out.push(ch);
199            prev_alpha = false;
200        }
201    }
202
203    out
204}
205
206#[cfg(test)]
207mod tests {
208    use rstest::rstest;
209
210    use super::*;
211
212    #[rstest]
213    #[case("CamelCase", "camel_case")]
214    #[case("This is Human case.", "this_is_human_case")]
215    #[case(
216        "MixedUP CamelCase, with some Spaces",
217        "mixed_up_camel_case_with_some_spaces"
218    )]
219    #[case(
220        "mixed_up_ snake_case with some _spaces",
221        "mixed_up_snake_case_with_some_spaces"
222    )]
223    #[case("kebab-case", "kebab_case")]
224    #[case("SHOUTY_SNAKE_CASE", "shouty_snake_case")]
225    #[case("snake_case", "snake_case")]
226    #[case("XMLHttpRequest", "xml_http_request")]
227    #[case("FIELD_NAME11", "field_name11")]
228    #[case("99BOTTLES", "99bottles")]
229    #[case("abc123def456", "abc123def456")]
230    #[case("abc123DEF456", "abc123_def456")]
231    #[case("abc123Def456", "abc123_def456")]
232    #[case("abc123DEf456", "abc123_d_ef456")]
233    #[case("ABC123def456", "abc123def456")]
234    #[case("ABC123DEF456", "abc123def456")]
235    #[case("ABC123Def456", "abc123_def456")]
236    #[case("ABC123DEf456", "abc123d_ef456")]
237    #[case("ABC123dEEf456FOO", "abc123d_e_ef456_foo")]
238    #[case("abcDEF", "abc_def")]
239    #[case("ABcDE", "a_bc_de")]
240    #[case("", "")]
241    #[case("A", "a")]
242    #[case("AB", "ab")]
243    #[case("PascalCase", "pascal_case")]
244    #[case("camelCase", "camel_case")]
245    #[case("getHTTPResponse", "get_http_response")]
246    #[case("Level1", "level1")]
247    #[case("OrderBookDelta", "order_book_delta")]
248    #[case("IOError", "io_error")]
249    #[case("SimpleHTTPServer", "simple_http_server")]
250    #[case("version2Release", "version2_release")]
251    #[case("ALLCAPS", "allcaps")]
252    #[case("é--x", "é_x")]
253    #[case("nautilus_model::data::bar::Bar", "nautilus_model_data_bar_bar")] // nautilus-import-ok
254    fn test_to_snake_case(#[case] input: &str, #[case] expected: &str) {
255        assert_eq!(to_snake_case(input), expected);
256    }
257
258    #[rstest]
259    #[case("", "")]
260    #[case("a", "A")]
261    #[case("example", "Example")]
262    #[case("EXAMPLE", "Example")]
263    #[case("hello_world", "Hello_World")]
264    #[case("hello-world", "Hello-World")]
265    #[case("hello world", "Hello World")]
266    #[case("hELLO wORLD", "Hello World")]
267    #[case("123abc", "123Abc")]
268    #[case("_leading", "_Leading")]
269    fn test_title_case(#[case] input: &str, #[case] expected: &str) {
270        assert_eq!(title_case(input), expected);
271    }
272}