ctb_formats_eite/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 point and sequence encoding helpers for EITE.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use anyhow::{Result, anyhow};
30
31use crate::formats::{dc_from_format, dc_to_format};
32use ctb_formats_utilities::FormatLog;
33
34/// Convert a single Unicode scalar (given as an integer) to Dc array (1 element) using 'unicode' mapping.
35/// JS: dcaFromUnicodeChar(intChar)
36pub fn dca_from_unicode_char(int_char: u32) -> Result<(Vec<u32>, FormatLog)> {
37    // In JS: dcFromFormat('unicode', anFromN(intChar)) then push first if exists.
38    // We treat int_char as a Unicode scalar, encode it to UTF-8, then call dc_from_format.
39    let ch =
40        char::from_u32(int_char).ok_or_else(|| anyhow!("Invalid codepoint"))?;
41    let mut buf = [0u8; 4];
42    let s = ch.encode_utf8(&mut buf);
43    let (dcs, log) = dc_from_format("unicode", s.as_bytes())?;
44    if dcs.is_empty() {
45        Ok((vec![], log))
46    } else {
47        Ok((
48            vec![*dcs.first().ok_or_else(|| anyhow!("dcs is empty"))?],
49            log,
50        ))
51    }
52}
53
54/// Convert a Dc to a Unicode codepoint array (1 element).
55/// JS: dcToUnicodeCharArray(intDc)
56pub fn dc_to_unicode_char_array(dc: u32) -> Result<(Vec<u32>, FormatLog)> {
57    // JS did: dcToFormat('unicode', intDc) -> returns UTF-8 bytes -> take firstCharOfUtf8String
58    let (utf8_bytes, log) = dc_to_format("unicode", dc)?;
59    if utf8_bytes.is_empty() {
60        return Ok((vec![], log));
61    }
62    // Decode first UTF-8 codepoint
63    let ch = std::str::from_utf8(&utf8_bytes)
64        .map_err(|e| anyhow!("Invalid UTF-8 from dc_to_format: {e}"))?
65        .chars()
66        .next()
67        .ok_or_else(|| anyhow!("Empty UTF-8 string from dc_to_format"))?;
68    Ok((vec![u32::from(ch)], log))
69}