ctb_formats_string/
string.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! String parsing, CamelCase word splitting, and text formatting helpers.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29/// Splits a CamelCase string into its constituent subwords.
30#[must_use]
31pub fn split_camel_case(s: &str) -> Vec<String> {
32    let chars: Vec<char> = s.chars().collect();
33    let len = chars.len();
34    if len == 0 {
35        return Vec::new();
36    }
37
38    let mut words = Vec::new();
39    let mut start = 0;
40    for i in 1..len {
41        let Some(&prev) = chars.get(i.saturating_sub(1)) else {
42            continue;
43        };
44        let Some(&curr) = chars.get(i) else {
45            continue;
46        };
47        let next = chars.get(i.saturating_add(1)).copied();
48
49        let is_lower_to_upper = prev.is_lowercase() && curr.is_uppercase();
50        let is_upper_to_upper_then_lower = prev.is_uppercase()
51            && curr.is_uppercase()
52            && next.is_some_and(char::is_lowercase);
53        let is_letter_to_digit = prev.is_alphabetic() && curr.is_ascii_digit();
54        let is_digit_to_letter = prev.is_ascii_digit() && curr.is_alphabetic();
55
56        if is_lower_to_upper
57            || is_upper_to_upper_then_lower
58            || is_letter_to_digit
59            || is_digit_to_letter
60        {
61            if let Some(slice) = chars.get(start..i) {
62                let word: String = slice.iter().collect();
63                if !word.is_empty() {
64                    words.push(word);
65                }
66            }
67            start = i;
68        }
69    }
70    if let Some(slice) = chars.get(start..len) {
71        let last: String = slice.iter().collect();
72        if !last.is_empty() {
73            words.push(last);
74        }
75    }
76    words
77}
78
79/// Formats arbitrary binary bytes into a human-readable, valid UTF-8 string,
80/// preserving valid UTF-8 text and escaping invalid UTF-8 bytes and control
81/// characters as `\xHH` or standard escape sequences.
82#[must_use]
83pub fn escape_bytes_human_readable(bytes: &[u8]) -> String {
84    let mut out = String::with_capacity(bytes.len());
85    for chunk in bytes.utf8_chunks() {
86        for ch in chunk.valid().chars() {
87            match ch {
88                '\\' => out.push_str(r"\\"),
89                '\n' => out.push_str(r"\n"),
90                '\r' => out.push_str(r"\r"),
91                '\t' => out.push_str(r"\t"),
92                c if u32::from(c) < 0x20 || c == '\x7f' => {
93                    let hex = format!("\\x{:02x}", u32::from(c));
94                    out.push_str(&hex);
95                }
96                c => out.push(c),
97            }
98        }
99        for &b in chunk.invalid() {
100            let hex = format!("\\x{b:02x}");
101            out.push_str(&hex);
102        }
103    }
104    out
105}
106
107/// Formats a filesystem path into a human-readable, valid UTF-8 string,
108/// escaping invalid UTF-8 bytes and control characters as `\xHH` hex escapes.
109///
110/// On POSIX/Unix systems, paths are read as raw native bytes; on Windows, paths
111/// are read as canonical WTF-8 bytes via `OsStr::as_encoded_bytes()`.
112/// Any invalid UTF-8 bytes (including unpaired surrogates in WTF-8) and
113/// control characters are losslessly escaped as `\xHH`.
114#[must_use]
115pub fn escape_path_human_readable(path: &std::path::Path) -> String {
116    escape_bytes_human_readable(path.as_os_str().as_encoded_bytes())
117}
118
119#[cfg(test)]
120#[allow(
121    clippy::panic,
122    clippy::expect_used,
123    clippy::unwrap_used,
124    clippy::unwrap_in_result,
125    clippy::panic_in_result_fn,
126    clippy::indexing_slicing,
127    clippy::arithmetic_side_effects,
128    reason = "Standard repository test boilerplate"
129)]
130mod tests {
131    use super::*;
132
133    #[crate::ctb_test]
134    fn test_split_camel_case() {
135        assert_eq!(split_camel_case(""), Vec::<String>::new());
136        assert_eq!(split_camel_case("Foo"), vec!["Foo"]);
137        assert_eq!(split_camel_case("FooBar"), vec!["Foo", "Bar"]);
138        assert_eq!(
139            split_camel_case("FooBarRegular"),
140            vec!["Foo", "Bar", "Regular"]
141        );
142        assert_eq!(split_camel_case("XMLParser"), vec!["XML", "Parser"]);
143        assert_eq!(split_camel_case("utf8String"), vec!["utf", "8", "String"]);
144    }
145
146    #[crate::ctb_test]
147    fn test_escape_bytes_human_readable_ascii_and_unicode() {
148        assert_eq!(escape_bytes_human_readable(b"hello world"), "hello world");
149        assert_eq!(
150            escape_bytes_human_readable(
151                "🦀 /path/to/ünicøde/日本語/file.txt".as_bytes()
152            ),
153            "🦀 /path/to/ünicøde/日本語/file.txt"
154        );
155    }
156
157    #[crate::ctb_test]
158    fn test_escape_bytes_human_readable_controls_and_escapes() {
159        assert_eq!(
160            escape_bytes_human_readable(b"line1\nline2\r\ttab\\slash"),
161            "line1\\nline2\\r\\ttab\\\\slash"
162        );
163        assert_eq!(
164            escape_bytes_human_readable(b"\x00null\x1funit"),
165            "\\x00null\\x1funit"
166        );
167    }
168
169    #[crate::ctb_test]
170    fn test_escape_bytes_human_readable_invalid_utf8() {
171        // 0xe9 alone is invalid UTF-8 (e.g. Latin-1 'é')
172        assert_eq!(
173            escape_bytes_human_readable(b"/path/caf\xe9.txt"),
174            "/path/caf\\xe9.txt"
175        );
176        // 0xff and 0xfe
177        assert_eq!(
178            escape_bytes_human_readable(b"\xff\xfe_raw"),
179            "\\xff\\xfe_raw"
180        );
181    }
182
183    #[crate::ctb_test]
184    fn test_escape_path_human_readable() {
185        let p = std::path::Path::new("/normal/path/file.txt");
186        assert_eq!(escape_path_human_readable(p), "/normal/path/file.txt");
187    }
188
189    #[crate::ctb_test]
190    fn test_escape_bytes_human_readable_wtf8_surrogates() {
191        // Unpaired surrogate U+D800 encoded as 3-byte WTF-8: 0xED, 0xA0, 0x80
192        let wtf8_bytes = [b'a', 0xED, 0xA0, 0x80, b'b'];
193        assert_eq!(
194            escape_bytes_human_readable(&wtf8_bytes),
195            "a\\xed\\xa0\\x80b"
196        );
197    }
198}