ctb_formats_encoding/
unicode.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//! Unicode transformation and byte-sequence conversion utilities.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29pub fn utf8_to_utf32be(input: &[u8]) -> Result<Vec<u8>> {
30    let s = std::str::from_utf8(input).context("invalid UTF-8 sequence")?;
31    let mut result = Vec::with_capacity(s.len().saturating_mul(4));
32    for c in s.chars() {
33        result.extend_from_slice(&u32::from(c).to_be_bytes());
34    }
35    Ok(result)
36}
37
38pub fn utf32be_to_utf8(input: &[u8]) -> Result<Vec<u8>> {
39    if !input.len().is_multiple_of(4) {
40        bail!("input length must be a multiple of 4");
41    }
42    let mut result = Vec::with_capacity(input.len());
43    for chunk in input.chunks_exact(4) {
44        let bytes: [u8; 4] = chunk.try_into().context("invalid chunk size")?;
45        let code_point = u32::from_be_bytes(bytes);
46        let c =
47            char::from_u32(code_point).context("invalid unicode code point")?;
48        let mut buf = [0u8; 4];
49        let utf8_str = c.encode_utf8(&mut buf);
50        result.extend_from_slice(utf8_str.as_bytes());
51    }
52    Ok(result)
53}
54
55#[cfg(test)]
56#[allow(
57    clippy::panic,
58    clippy::expect_used,
59    clippy::unwrap_used,
60    clippy::unwrap_in_result,
61    clippy::panic_in_result_fn,
62    clippy::indexing_slicing,
63    clippy::arithmetic_side_effects,
64    reason = "Standard repository test boilerplate"
65)]
66mod tests {
67    use super::*;
68
69    #[crate::ctb_test]
70    fn test_utf_conversions() {
71        let original_str = "Hello, World! 🌄 ñ ü á";
72        let original_bytes = original_str.as_bytes();
73
74        let utf32 = utf8_to_utf32be(original_bytes).unwrap();
75        let decoded = utf32be_to_utf8(&utf32).unwrap();
76
77        assert_eq!(std::str::from_utf8(&decoded).unwrap(), original_str);
78
79        // Test specific literal bytes example: U+004D, U+0061, and U+10000
80        let spec_utf8 = "Ma\u{10000}".as_bytes();
81        let spec_expected_utf32 = [
82            0x00, 0x00, 0x00, 0x4D, // U+004D
83            0x00, 0x00, 0x00, 0x61, // U+0061
84            0x00, 0x01, 0x00, 0x00, // U+10000
85        ];
86        let spec_utf32 = utf8_to_utf32be(spec_utf8).unwrap();
87        assert_eq!(spec_utf32, spec_expected_utf32);
88
89        let spec_decoded = utf32be_to_utf8(&spec_expected_utf32).unwrap();
90        assert_eq!(spec_decoded, spec_utf8);
91
92        // Test invalid inputs
93        utf8_to_utf32be(&[0xff, 0xff]).unwrap_err();
94        utf32be_to_utf8(&[0, 0, 0]).unwrap_err();
95        utf32be_to_utf8(&[0xff, 0xff, 0xff, 0xff]).unwrap_err(); // invalid code point
96    }
97}