ctb_formats_dceutils/
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//! DCE document format to Unicode mapping and normalized sequence conversions.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use anyhow::anyhow;
30use ctb_formats_hexdump::hex2bin;
31use ctb_formats_utilities::FormatLog;
32
33use crate::dce_convert_internal;
34use crate::dce3_01a::dc_map_send_simple;
35use crate::tables::get_tables;
36use crate::tools::explode_escaped;
37
38pub fn convert_utf8_to_dc(data: &[u8], log: &mut FormatLog) -> Result<String> {
39    let utf32_bytes = ctb_formats_encoding::unicode::utf8_to_utf32be(data)
40        .map_err(|e| {
41            log.error(&format!("Failed to convert UTF-8 to UTF-32: {e}"));
42            anyhow!("Failed to convert UTF-8 to UTF-32: {e}")
43        })?;
44
45    let tables = get_tables();
46    let mut txt = String::new();
47    let chunks = utf32_bytes.chunks_exact(4);
48
49    for chunk in chunks {
50        let bytes: [u8; 4] =
51            chunk.try_into().context("Invalid chunk size for u32 BE")?;
52        let cp = u32::from_be_bytes(bytes);
53        // PHP: strtoupper(ltrim(substr($hex, $counter, 8), '0'))
54        let hex_str = format!("{cp:X}");
55        if let Some(val) = tables.dc_map_unicode_lossy.get(&hex_str) {
56            if !val.is_empty() {
57                txt.push_str(val);
58                txt.push(',');
59            }
60        }
61    }
62    Ok(txt)
63}
64
65pub fn convert_utf32_to_dc(data: &[u8], log: &mut FormatLog) -> Result<String> {
66    let unicode_bytes = ctb_formats_encoding::unicode::utf32be_to_utf8(data)
67        .map_err(|_| {
68            log.error(
69                "This document is not stored using the specified format.",
70            );
71            anyhow!("This document is not stored using the specified format.")
72        })?;
73
74    if unicode_bytes.is_empty() {
75        log.error("This document is not stored using the specified format.");
76        bail!("This document is not stored using the specified format.");
77    }
78
79    let dc_bytes = dce_convert_internal(&unicode_bytes, "utf8", "dc", log)?;
80    Ok(String::from_utf8(dc_bytes)?)
81}
82
83pub fn convert_utf8_base64_to_dc(
84    data: &[u8],
85    log: &mut FormatLog,
86) -> Result<String> {
87    let data_str = std::str::from_utf8(data).map_err(|_| {
88        log.error("This document is not stored using the specified format.");
89        anyhow!("This document is not stored using the specified format.")
90    })?;
91    let decoded =
92        ctb_formats_base64::base64_decode(data_str).map_err(|_| {
93            log.error(
94                "This document is not stored using the specified format.",
95            );
96            anyhow!("This document is not stored using the specified format.")
97        })?;
98    let dc_bytes = dce_convert_internal(&decoded, "utf8", "dc", log)?;
99    Ok(String::from_utf8(dc_bytes)?)
100}
101
102pub fn convert_utf8_dc64_to_dc(
103    data: &[u8],
104    log: &mut FormatLog,
105) -> Result<String> {
106    let data_str = std::str::from_utf8(data).map_err(|_| {
107        log.error("This document is not stored using the specified format.");
108        anyhow!("This document is not stored using the specified format.")
109    })?;
110    // Replicate PHP: `if ((substr($data, 0, 3) > 126) && (substr($data, 0, 3) < 191))`
111    // Reason for fallback: if data_str is shorter than 3 bytes, full data_str is used as prefix.
112    let prefix = data_str.get(0..3).unwrap_or(data_str);
113    // Reason for fallback: non-numeric document prefix defaults to 0 so the range check (126..191) evaluates to false and falls back to standard processing.
114    let prefix_val = prefix.parse::<i32>().unwrap_or(0);
115    if prefix_val > 126 && prefix_val < 191 {
116        let dc_array = explode_escaped(',', data_str);
117        let tables = get_tables();
118        let mut dcb64 = String::new();
119        for dc_id in dc_array {
120            if let Some(c) = tables.dc_to_base64.get(&dc_id) {
121                dcb64.push_str(c);
122            }
123        }
124        let b64_bytes =
125            ctb_formats_base64::base64_decode(&dcb64).map_err(|_| {
126                log.error(
127                    "This document is not stored using the specified format.",
128                );
129                anyhow!(
130                    "This document is not stored using the specified format."
131                )
132            })?;
133        let dc_bytes = dce_convert_internal(&b64_bytes, "utf8", "dc", log)?;
134        Ok(String::from_utf8(dc_bytes)?)
135    } else {
136        log.error("This document is not stored using the specified format.");
137        bail!("This document is not stored using the specified format.");
138    }
139}
140
141pub fn convert_utf8_dc64_enc_to_dc(
142    data: &[u8],
143    log: &mut FormatLog,
144) -> Result<String> {
145    let data_str = std::str::from_utf8(data).map_err(|_| {
146        log.error("This document is not stored using the specified format.");
147        anyhow!("This document is not stored using the specified format.")
148    })?;
149    if data_str.starts_with("191,") && data_str.ends_with(",192") {
150        let inner = data_str
151            .get(4..data_str.len().saturating_sub(4))
152            .context("substring slice")?;
153        let dc_bytes =
154            dce_convert_internal(inner.as_bytes(), "utf8_dc64", "dc", log)?;
155        Ok(String::from_utf8(dc_bytes)?)
156    } else {
157        log.error("This document is not stored using the specified format.");
158        bail!("This document is not stored using the specified format.");
159    }
160}
161
162pub fn convert_utf8_dc64_bin_to_dc(
163    data: &[u8],
164    log: &mut FormatLog,
165) -> Result<String> {
166    let hex = bin2hex(data);
167    let tables = get_tables();
168    let mut dclist = String::new();
169    let mut i = 0_usize;
170    while i < hex.len() {
171        let next_two = i.saturating_add(2);
172        if next_two <= hex.len() {
173            if let Some(slice) = hex.get(i..next_two) {
174                let byte_hex = slice.to_uppercase();
175                if let Some(val) = tables.dc_map_dce3_01a_core.get(&byte_hex) {
176                    dclist.push_str(val);
177                    dclist.push(',');
178                }
179            }
180        }
181        i = i.saturating_add(2);
182    }
183    let dc_bytes =
184        dce_convert_internal(dclist.as_bytes(), "utf8_dc64", "dc", log)?;
185    Ok(String::from_utf8(dc_bytes)?)
186}
187
188pub fn convert_utf8_dc64_bin_hex_to_dc(
189    data: &[u8],
190    log: &mut FormatLog,
191) -> Result<String> {
192    let hex = std::str::from_utf8(data).map_err(|_| {
193        log.error("This document is not stored using the specified format.");
194        anyhow!("This document is not stored using the specified format.")
195    })?;
196    let tables = get_tables();
197    let mut dclist = String::new();
198    let mut i = 0_usize;
199    while i < hex.len() {
200        let next_two = i.saturating_add(2);
201        if next_two <= hex.len() {
202            if let Some(slice) = hex.get(i..next_two) {
203                let byte_hex = slice.to_uppercase();
204                if let Some(val) = tables.dc_map_dce3_01a_core.get(&byte_hex) {
205                    dclist.push_str(val);
206                    dclist.push(',');
207                }
208            }
209        }
210        i = i.saturating_add(2);
211    }
212    let dc_bytes =
213        dce_convert_internal(dclist.as_bytes(), "utf8_dc64", "dc", log)?;
214    Ok(String::from_utf8(dc_bytes)?)
215}
216
217pub fn convert_utf8_dc64_bin_enc_to_dc(
218    data: &[u8],
219    log: &mut FormatLog,
220) -> Result<String> {
221    let hex = bin2hex(data);
222    if hex.len() >= 4 {
223        let inner_hex = hex
224            .get(2..hex.len().saturating_sub(2))
225            .context("substring slice")?;
226        let inner_bytes = hex2bin(inner_hex).map_err(|_| {
227            log.error(
228                "This document is not stored using the specified format.",
229            );
230            anyhow!("This document is not stored using the specified format.")
231        })?;
232        let dc_bytes =
233            dce_convert_internal(&inner_bytes, "utf8_dc64_bin", "dc", log)?;
234        Ok(String::from_utf8(dc_bytes)?)
235    } else {
236        log.error("This document is not stored using the specified format.");
237        bail!("This document is not stored using the specified format.");
238    }
239}
240
241pub fn convert_utf8_dc64_bin_enc_hex_to_dc(
242    data: &[u8],
243    log: &mut FormatLog,
244) -> Result<String> {
245    let data_str = std::str::from_utf8(data).map_err(|_| {
246        log.error("This document is not stored using the specified format.");
247        anyhow!("This document is not stored using the specified format.")
248    })?;
249    if data_str.len() >= 4 {
250        let inner = data_str
251            .get(2..data_str.len().saturating_sub(2))
252            .context("substring slice")?;
253        let dc_bytes = dce_convert_internal(
254            inner.as_bytes(),
255            "utf8_dc64_bin_hex",
256            "dc",
257            log,
258        )?;
259        Ok(String::from_utf8(dc_bytes)?)
260    } else {
261        log.error("This document is not stored using the specified format.");
262        bail!("This document is not stored using the specified format.");
263    }
264}
265
266pub fn convert_dc_to_utf8_output(
267    data: &str,
268    log: &mut FormatLog,
269) -> Result<Vec<u8>> {
270    let dc_array = explode_escaped(',', data);
271    let tables = get_tables();
272    let mut txt = String::new();
273
274    for dc_id in dc_array {
275        if let Some(mapped) = tables.dc_map_send_unicode.get(&dc_id) {
276            if !mapped.is_empty() {
277                // Pad to 8 hex characters, lowercase
278                let padded = format!("{mapped:0>8}").to_lowercase();
279                txt.push_str(&padded);
280                continue;
281            }
282        }
283        if dc_id != "114" && dc_id != "115" {
284            txt.push_str("0000fffd");
285        }
286    }
287
288    let utf32_bytes = hex2bin(&txt).map_err(|e| {
289        log.error(&format!(
290            "Failed to decode hex in UTF-8 output conversion: {e}"
291        ));
292        anyhow!("Failed to decode hex in UTF-8 output conversion: {e}")
293    })?;
294    ctb_formats_encoding::unicode::utf32be_to_utf8(&utf32_bytes)
295}
296
297pub fn convert_dc_to_utf32_output(
298    data: &str,
299    log: &mut FormatLog,
300) -> Result<Vec<u8>> {
301    let utf8_res = dce_convert_internal(data.as_bytes(), "dc", "utf8", log)?;
302    ctb_formats_encoding::unicode::utf8_to_utf32be(&utf8_res)
303}
304
305pub fn convert_dc_to_utf8_base64_output(
306    data: &str,
307    log: &mut FormatLog,
308) -> Result<Vec<u8>> {
309    let utf8_res = dce_convert_internal(data.as_bytes(), "dc", "utf8", log)?;
310    let b64 = ctb_formats_base64::base64_encode(&utf8_res);
311    Ok(b64.into_bytes())
312}
313
314pub fn convert_dc_to_utf8_dc64_output(
315    data: &str,
316    log: &mut FormatLog,
317) -> Result<Vec<u8>> {
318    let b64_bytes =
319        dce_convert_internal(data.as_bytes(), "dc", "utf8_base64", log)?;
320    let b64_str = String::from_utf8(b64_bytes)?;
321    let tables = get_tables();
322    let mut dcb64 = String::new();
323    for c in b64_str.chars() {
324        let key = c.to_string();
325        if let Some(val) = tables.base64_to_dc.get(&key) {
326            dcb64.push(',');
327            dcb64.push_str(val);
328        }
329    }
330    if dcb64.is_empty() {
331        Ok(Vec::new())
332    } else {
333        let sub = dcb64.get(1..).context("substring slice")?;
334        Ok(sub.to_string().into_bytes())
335    }
336}
337
338pub fn convert_dc_to_utf8_dc64_enc_output(
339    data: &str,
340    log: &mut FormatLog,
341) -> Result<Vec<u8>> {
342    let inner = dce_convert_internal(data.as_bytes(), "dc", "utf8_dc64", log)?;
343    let inner_str = String::from_utf8(inner)?;
344    Ok(format!("191,{inner_str},192").into_bytes())
345}
346
347pub fn convert_dc_to_utf8_dc64_bin_output(
348    data: &str,
349    log: &mut FormatLog,
350) -> Result<Vec<u8>> {
351    let dc64 = dce_convert_internal(data.as_bytes(), "dc", "utf8_dc64", log)?;
352    let dc64_str = String::from_utf8(dc64)?;
353    let hex_val = dc_map_send_simple(&dc64_str);
354    hex2bin(&hex_val)
355}
356
357pub fn convert_dc_to_utf8_dc64_bin_hex_output(
358    data: &str,
359    log: &mut FormatLog,
360) -> Result<Vec<u8>> {
361    let dc64 = dce_convert_internal(data.as_bytes(), "dc", "utf8_dc64", log)?;
362    let dc64_str = String::from_utf8(dc64)?;
363    let hex_val = dc_map_send_simple(&dc64_str);
364    Ok(hex_val.to_uppercase().into_bytes())
365}
366
367pub fn convert_dc_to_utf8_dc64_bin_enc_output(
368    data: &str,
369    log: &mut FormatLog,
370) -> Result<Vec<u8>> {
371    let bin =
372        dce_convert_internal(data.as_bytes(), "dc", "utf8_dc64_bin", log)?;
373    let hex_str = format!("c3{}c4", bin2hex(bin));
374    hex2bin(&hex_str)
375}
376
377pub fn convert_dc_to_utf8_dc64_bin_enc_hex_output(
378    data: &str,
379    log: &mut FormatLog,
380) -> Result<Vec<u8>> {
381    let bin =
382        dce_convert_internal(data.as_bytes(), "dc", "utf8_dc64_bin", log)?;
383    let hex_str = format!("c3{}c4", bin2hex(bin)).to_uppercase();
384    Ok(hex_str.into_bytes())
385}