ctb_formats_dceutils/
cdce.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//! CDCE character set decoder and data conversion utilities.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use anyhow::anyhow;
30
31use ctb_formats_utilities::FormatLog;
32
33use crate::dce_convert_internal;
34use crate::tables::get_tables;
35use crate::tools::explode_escaped;
36
37pub fn convert_legacy_cdce_to_dc(
38    data: &[u8],
39    strict: bool,
40    log: &mut FormatLog,
41) -> Result<String> {
42    let utf32_bytes = ctb_formats_encoding::unicode::utf8_to_utf32be(data)
43        .map_err(|e| {
44            log.error(&format!("iconv conversion failed: {e}"));
45            anyhow!("iconv conversion failed: {e}")
46        })?;
47
48    let chunks = utf32_bytes.chunks_exact(4);
49    if !chunks.remainder().is_empty() {
50        log.error("UTF-32BE payload length is not a multiple of 4");
51        bail!("UTF-32BE payload length is not a multiple of 4");
52    }
53
54    let codepoints: Vec<u32> = chunks
55        .map(|chunk| {
56            let Ok(bytes) = <[u8; 4]>::try_from(chunk) else {
57                unreachable!("chunks_exact(4) guarantees 4-byte chunks");
58            };
59            u32::from_be_bytes(bytes)
60        })
61        .collect();
62
63    let tables = get_tables();
64    let mut txt = String::new();
65    let mut i = 0_usize;
66
67    while i < codepoints.len() {
68        let cp = *codepoints
69            .get(i)
70            .context("codepoints index out of bounds")?;
71        if cp == 0x40 {
72            // '@'
73            // 1-character CDCE condition
74            let mut matched_1char = false;
75            let i_plus_2 = i.saturating_add(2);
76            if i_plus_2 < codepoints.len()
77                && codepoints.get(i_plus_2) == Some(&0x40)
78            {
79                let next_cp = *codepoints
80                    .get(i.saturating_add(1))
81                    .context("codepoints index out of bounds")?;
82                if (0x31..=0x39).contains(&next_cp) {
83                    // '1'..='9'
84                    let digit_char =
85                        char::from_u32(next_cp).ok_or_else(|| {
86                            anyhow::anyhow!("Invalid codepoint 0x{next_cp:X}")
87                        })?;
88                    txt.push_str(&format!("{digit_char},"));
89                    i = i.saturating_add(3);
90                    matched_1char = true;
91                }
92            }
93
94            if !matched_1char {
95                // 2-character CDCE condition
96                let mut matched_2char = false;
97                let i_plus_3 = i.saturating_add(3);
98                if i_plus_3 < codepoints.len()
99                    && codepoints.get(i_plus_3) == Some(&0x40)
100                {
101                    let cp1 = *codepoints
102                        .get(i.saturating_add(1))
103                        .context("codepoints index out of bounds")?;
104                    let cp2 = *codepoints
105                        .get(i.saturating_add(2))
106                        .context("codepoints index out of bounds")?;
107                    if (0x30..=0x39).contains(&cp1)
108                        && (0x30..=0x39).contains(&cp2)
109                    {
110                        let d1 = u8::try_from(cp1.saturating_sub(0x30))?;
111                        let d2 = u8::try_from(cp2.saturating_sub(0x30))?;
112                        let val = d1.saturating_mul(10).saturating_add(d2);
113                        if val > 0 && val < 13 {
114                            txt.push_str(&format!("{val},"));
115                            i = i.saturating_add(4);
116                            matched_2char = true;
117                        }
118                    }
119                }
120
121                if !matched_2char {
122                    if strict {
123                        log.error(&format!(
124                            "CDCE decoding error: invalid escape sequence at codepoint index {i}"
125                        ));
126                        // format txt like PHP did, then return decoding error
127                        let mut cleaned = txt.trim_end_matches(',').to_string();
128                        while cleaned.contains(",,") {
129                            cleaned = cleaned.replace(",,", ",0,");
130                        }
131                        return Ok(format!("{cleaned}… CDCE decoding error!"));
132                    }
133                    log.warn(&format!(
134                        "Warning: Unicode recovery attempted for corrupted CDCE sequence at codepoint index {i}"
135                    ));
136                    // Recover using Lossy Unicode map for '@' (0x40)
137                    if let Some(val) = tables.dc_map_unicode_lossy.get("40") {
138                        txt.push_str(&format!("{val},"));
139                    }
140                    i = i.saturating_add(1);
141                }
142            }
143        } else {
144            let key = format!("{cp:X}");
145            if let Some(val) = tables.dc_map_unicode_lossy.get(&key) {
146                if !val.is_empty() {
147                    txt.push_str(&format!("{val},"));
148                }
149            }
150            i = i.saturating_add(1);
151        }
152    }
153
154    Ok(txt)
155}
156
157pub fn convert_dc_to_legacy_cdce_output(
158    data: &str,
159    log: &mut FormatLog,
160) -> Result<Vec<u8>> {
161    let dc_array = explode_escaped(',', data);
162    let tables = get_tables();
163    let mut txt = String::new();
164
165    for dc_id in dc_array {
166        if tables.cdce_html_legacy.contains_key(&dc_id) {
167            txt.push_str(&format!("@{dc_id}@"));
168        } else {
169            let utf8_res =
170                dce_convert_internal(dc_id.as_bytes(), "dc", "utf8", log)?;
171            let utf8_str = String::from_utf8(utf8_res)
172                .context("invalid UTF-8 from conversion")?;
173            txt.push_str(&utf8_str);
174        }
175    }
176
177    Ok(txt.into_bytes())
178}