ctb_formats_utf8/
utf8.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//! UTF-8 character encoding, validation, and stream parsing utilities.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29use anyhow::{Result, anyhow, bail};
30
31pub const UTF8_REPLACEMENT_CHARACTER: &[u8; 3] = &[0xEF, 0xBF, 0xBD];
32
33/// Truncate a string to a maximum byte length, respecting UTF-8 boundaries.
34#[expect(
35    clippy::expect_used,
36    reason = "end is guaranteed to be a valid char boundary within s"
37)]
38pub fn truncate_to_max_bytes(s: &str, max_len: usize) -> String {
39    if s.len() <= max_len {
40        return s.to_owned();
41    }
42    // Find the last valid char boundary at or before max_len.
43    let mut end = max_len;
44    while end > 0 && !s.is_char_boundary(end) {
45        end = end.saturating_sub(1);
46    }
47    s.get(..end)
48        .expect("end is a valid char boundary within s")
49        .to_owned()
50}
51
52/// Ellipsize a string to a maximum byte length, respecting UTF-8 boundaries.
53pub fn ellipsize_to_max_bytes(s: &str, max_len: usize) -> String {
54    let start_len = s.len();
55    if start_len <= max_len {
56        return s.to_owned();
57    }
58    let max_len = max_len.saturating_sub(3); // for "..."
59    format!("{}...", truncate_to_max_bytes(s, max_len))
60}
61
62/// Roughly transliterate a UTF-8 string to ASCII.
63/// I have in mind a new transliteration "transformation" (defined in transformations.csv) which could be applied in some general way as a fallback encoding handler (that isn't a concept that exists anywhere in code yet, but basically a generalization of the "replacement character" idea where a Dc format chain could be defined to perform more complex conversion operations on text during an export).
64pub fn to_ascii_translit(input: &str) -> String {
65    deunicode::deunicode(input)
66}
67
68/// Return a character (or for invalid part of the string, the replacement
69/// character) of a UTF-8 string as bytes, as well as the number of input bytes
70/// consumed. For valid UTF-8 input, the number of input bytes will always match
71/// the number of output bytes.
72pub fn first_char_of_utf8_string(bytes: &[u8]) -> Result<(Vec<u8>, usize)> {
73    let (bytes, (consumed, _valid)) = _first_char_of_utf8_string(bytes, true)?;
74    Ok((bytes, consumed))
75}
76
77/// Return a character or invalid part of a UTF-8 string as bytes, as well as
78/// the number of input bytes consumed.
79pub fn first_char_of_utf8_string_lossless(
80    bytes: &[u8],
81) -> Result<(Vec<u8>, (usize, bool))> {
82    _first_char_of_utf8_string(bytes, false)
83}
84
85fn _first_char_of_utf8_string(
86    bytes: &[u8],
87    replace_invalid: bool,
88) -> Result<(Vec<u8>, (usize, bool))> {
89    // This is inefficient because it operates on the WHOLE string, meaning it
90    // will decode all valid characters in a single chunk, then all but the
91    // first is discarded. Could possibly trim the string to the maximum length
92    // of a valid character to make it faster, but I don't know if that might
93    // have side effects on how many replacement characters would be returned
94    // compared to using String from_utf8_lossy(). It could also be made more efficient by returning a Cow slice into the input buffer instead of a Vec.
95    if bytes.is_empty() {
96        return Err(anyhow!("Empty input in first_char_of_utf8_string"));
97    }
98    let mut iter = bytes.utf8_chunks();
99    let chunk = iter.next().ok_or_else(|| {
100        anyhow!("At least some chunk should be found for non-empty string")
101    })?;
102
103    let valid = chunk.valid();
104    if valid.is_empty() {
105        let invalid = chunk.invalid();
106        if !invalid.is_empty() {
107            if replace_invalid {
108                // Return replacement character for invalid sequence
109                return Ok((vec![0xEF, 0xBF, 0xBD], (invalid.len(), false)));
110            }
111            return Ok((invalid.to_vec(), (invalid.len(), false)));
112        }
113        bail!("Chunk contained neither valid nor invalid data");
114    }
115
116    let first_char = valid
117        .chars()
118        .next()
119        .context("Chunk contains no valid character")?;
120    let out = &mut [0u8; 4];
121    let first_char_len = first_char.encode_utf8(out).len();
122
123    let char_bytes = out
124        .get(..first_char_len)
125        .context("Invalid character length")?
126        .to_vec();
127    Ok((char_bytes, (first_char_len, true)))
128}
129
130pub fn utf8_from_scalar(cp: u32) -> Result<Vec<u8>> {
131    if cp > 0x10FFFF {
132        bail!("Invalid Unicode codepoint U+{cp:X}");
133    }
134    let mut buf = [0u8; 4];
135    let s = char::from_u32(cp)
136        .ok_or_else(|| anyhow!("Invalid Unicode codepoint U+{cp:X}"))?
137        .encode_utf8(&mut buf);
138    Ok(s.as_bytes().to_vec())
139}
140
141#[cfg(test)]
142#[allow(
143    clippy::panic,
144    clippy::expect_used,
145    clippy::unwrap_used,
146    clippy::unwrap_in_result,
147    clippy::panic_in_result_fn,
148    clippy::indexing_slicing,
149    clippy::arithmetic_side_effects,
150    reason = "Standard repository test boilerplate"
151)]
152mod tests {
153    use super::*;
154
155    #[crate::ctb_test]
156    fn test_truncate_to_max_bytes() {
157        assert_eq!(truncate_to_max_bytes("hello", 10), "hello");
158        assert_eq!(truncate_to_max_bytes("hello", 5), "hello");
159        assert_eq!(truncate_to_max_bytes("hello", 3), "hel");
160
161        // UTF-8 boundary handling.
162        let s = "日本語";
163        // Each Japanese char is 3 bytes. "日本語" = 9 bytes.
164        assert_eq!(truncate_to_max_bytes(s, 9), "日本語");
165        assert_eq!(truncate_to_max_bytes(s, 8), "日本");
166        assert_eq!(truncate_to_max_bytes(s, 7), "日本");
167        assert_eq!(truncate_to_max_bytes(s, 6), "日本");
168        assert_eq!(truncate_to_max_bytes(s, 3), "日");
169        assert_eq!(truncate_to_max_bytes(s, 2), "");
170        assert_eq!(truncate_to_max_bytes(s, 0), "");
171    }
172
173    #[crate::ctb_test]
174    fn test_first_char_of_utf8_string_ascii() {
175        let input = b"hello";
176        let (ch, consumed) = first_char_of_utf8_string(input).unwrap();
177        assert_eq!(ch, vec![b'h']);
178        assert_eq!(consumed, 1);
179    }
180
181    #[crate::ctb_test]
182    fn test_first_char_of_utf8_string_multibyte() {
183        let input = "éclair".as_bytes();
184        let (ch, consumed) = first_char_of_utf8_string(input).unwrap();
185        assert_eq!(ch, "é".as_bytes());
186        assert_eq!(consumed, "é".len());
187    }
188
189    #[crate::ctb_test]
190    fn test_first_char_of_utf8_string_astral() {
191        let input = "🥴test".as_bytes();
192        let (ch, consumed) = first_char_of_utf8_string(input).unwrap();
193        assert_eq!(ch, "🥴".as_bytes());
194        assert_eq!(consumed, "🥴".len());
195    }
196
197    #[crate::ctb_test]
198    fn test_first_char_of_utf8_string_invalid() {
199        let input = &[0xFF, 0x61, 0x62];
200        let (ch, consumed) = first_char_of_utf8_string(input).unwrap();
201        assert_eq!(ch, vec![0xEF, 0xBF, 0xBD]); // UTF-8 replacement character
202        assert_eq!(consumed, 1);
203    }
204
205    #[crate::ctb_test]
206    fn test_first_char_of_utf8_string_overlong() {
207        let input = &[0xC1, 0x81];
208        let (ch, consumed) = first_char_of_utf8_string(input).unwrap();
209        assert_eq!(ch, vec![0xEF, 0xBF, 0xBD]); // UTF-8 replacement character
210        assert_eq!(consumed, 1);
211    }
212
213    #[crate::ctb_test]
214    fn test_first_char_of_utf8_string_partly_invalid() {
215        let input = &[0xE2, 0x80, 0xA9, 0xFF, 0x61, 0x62];
216        let (ch, consumed) = first_char_of_utf8_string(input).unwrap();
217        assert_eq!(ch, vec![0xE2, 0x80, 0xA9]);
218        assert_eq!(consumed, 3);
219    }
220
221    #[crate::ctb_test]
222    fn test_first_char_of_utf8_string_empty() {
223        let input = b"";
224        let result = first_char_of_utf8_string(input);
225        result.unwrap_err();
226    }
227
228    #[crate::ctb_test]
229    fn test_first_char_of_utf8_string_only_invalid() {
230        let input = &[0xFF, 0xFE];
231        let (ch, consumed) = first_char_of_utf8_string(input).unwrap();
232        assert_eq!(ch, vec![0xEF, 0xBF, 0xBD]);
233        assert_eq!(consumed, 1);
234    }
235
236    #[crate::ctb_test]
237    fn test_first_char_of_utf8_string_lossless_valid() {
238        let input = &[0x61, 0x62];
239        let (ch, (consumed, valid)) =
240            first_char_of_utf8_string_lossless(input).unwrap();
241        assert_eq!(ch, vec![0x61]);
242        assert_eq!(consumed, 1);
243        assert!(valid);
244    }
245
246    #[crate::ctb_test]
247    fn test_first_char_of_utf8_string_lossless_multibyte() {
248        let input = "🥴test".as_bytes();
249        let (ch, (consumed, valid)) =
250            first_char_of_utf8_string_lossless(input).unwrap();
251        assert_eq!(ch, "🥴".as_bytes());
252        assert_eq!(consumed, "🥴".len());
253        assert!(valid);
254    }
255
256    #[crate::ctb_test]
257    fn test_first_char_of_utf8_string_lossless_invalid() {
258        let input = &[0xFF, 0x61, 0x62];
259        let (ch, (consumed, valid)) =
260            first_char_of_utf8_string_lossless(input).unwrap();
261        assert_eq!(ch, vec![0xFF]); // UTF-8 replacement character
262        assert_eq!(consumed, 1);
263        assert!(!valid);
264    }
265
266    #[crate::ctb_test]
267    fn test_first_char_of_utf8_string_lossless_only_invalid() {
268        let input = &[0xFF, 0xFE];
269        let (ch, (consumed, valid)) =
270            first_char_of_utf8_string_lossless(input).unwrap();
271        assert_eq!(ch, vec![0xFF]);
272        assert_eq!(consumed, 1);
273        assert!(!valid);
274    }
275}