ctb_formats_eite/formats/
ascii.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//! ASCII text formatter and token serialization 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, bail};
30use const_default::ConstDefault;
31
32use crate::dc::dc_is_newline;
33use crate::formats::FormatLog;
34use crate::formats::{dc_from_format, dc_to_format};
35use crate::util::ascii::{ascii_is_newline, ascii_is_printable, crlf};
36
37#[derive(ConstDefault, Default, Debug, Clone)]
38pub struct AsciiSafeSubsetFormatSettings {
39    pub strict: bool,
40}
41
42/// (Original JS called dcFromFormat('ascii', singleByteArray).
43pub fn dca_from_ascii(content: &[u8]) -> Result<(Vec<u32>, FormatLog)> {
44    let mut log = FormatLog::default();
45    let mut out = Vec::with_capacity(content.len());
46    let mut c = 0;
47    while c < content.len() {
48        let b = content
49            .get(c)
50            .copied()
51            .ok_or_else(|| anyhow!("Index out of bounds"))?;
52        let result = dc_from_format("ascii", &[b])
53            .context("all ASCII bytes should be able to map to Dc")?;
54        let (mut dc, dc_log) = result;
55        out.append(&mut dc);
56        log.merge(&dc_log);
57        c = c.saturating_add(1);
58    }
59
60    Ok((out, log))
61}
62
63/// ASCII export: attempt to map each Dc to a single ASCII byte. If the Dc encodes to a
64/// multi-byte UTF-8 or a non-ASCII scalar, it is skipped (original emitted a warning).
65/// This mirrors the permissive behavior, skipping non-mappable Dcs.
66pub fn dca_to_ascii(dc_array: &[u32]) -> Result<(Vec<u8>, FormatLog)> {
67    let mut out = Vec::new();
68    let mut log = FormatLog::default();
69    for (idx, &dc) in dc_array.iter().enumerate() {
70        let (utf8, dc_log) = if let Ok(res) = dc_to_format("utf8", dc) {
71            res
72        } else {
73            let idx_u64 =
74                u64::try_from(idx).context("Index out of u64 bounds")?;
75            log.export_warning_unmappable(idx_u64, dc, "ascii");
76            continue;
77        };
78        log.merge(&dc_log);
79        // Reason for fallback: when utf8 byte vector is empty, first_byte is 0, which fails utf8.len() == 1 check and logs unmappable warning.
80        let first_byte = utf8.first().copied().unwrap_or(0);
81        if utf8.len() == 1 && first_byte <= 0x7F {
82            out.push(first_byte);
83        } else {
84            let idx_u64 =
85                u64::try_from(idx).context("Index out of u64 bounds")?;
86            log.export_warning_unmappable(idx_u64, dc, "ascii");
87            continue;
88        }
89    }
90    Ok((out, log))
91}
92
93/// Predicate: ASCII safe subset char (printable or newline).
94pub fn is_ascii_safe_subset_char(b: u8) -> bool {
95    ascii_is_printable(b) || ascii_is_newline(b)
96}
97
98/// Import from ASCII safe subset.
99/// Collapses CRLF sequences to two bytes, then delegates to `dca_from_ascii`.
100pub fn dca_from_ascii_safe_subset(
101    content: &[u8],
102    settings: &AsciiSafeSubsetFormatSettings,
103) -> Result<(Vec<u32>, FormatLog)> {
104    let bool_strict = settings.strict;
105
106    let mut prefilter: Vec<u8> = Vec::new();
107    let mut state_name = "normal";
108    let mut i = 0usize;
109
110    while i < content.len() {
111        let b = content
112            .get(i)
113            .copied()
114            .ok_or_else(|| anyhow!("Index out of bounds"))?;
115        if !is_ascii_safe_subset_char(b) {
116            bail!("Invalid ASCII Safe Subset byte: {b}");
117        }
118        if state_name == "normal" && b == b'\n' {
119            if bool_strict {
120                bail!(
121                    "LF without preceding CR not allowed in asciiSafeSubset strict mode."
122                );
123            }
124        } else if state_name == "normal" && b == b'\r' {
125            state_name = "crlf";
126        } else if state_name == "crlf" {
127            state_name = "normal";
128            // Always append CRLF sequence
129            prefilter.extend(crlf());
130            if b != b'\n' {
131                if bool_strict {
132                    bail!(
133                        "CR followed by non-LF byte not allowed in asciiSafeSubset strict mode."
134                    );
135                }
136                // Reprocess this byte
137                continue;
138            }
139        } else {
140            prefilter.push(b);
141        }
142        i = i.saturating_add(1);
143    }
144
145    // Delegate to ASCII importer
146    dca_from_ascii(&prefilter)
147}
148
149/// Export to ASCII safe subset.
150/// - Newlines are rendered as CRLF
151/// - Only printable ASCII + newline allowed; others trigger export warning
152/// - Attempts to disambiguate sequences (legacy handling of sentinel Dcs 121/120)
153pub fn dca_to_ascii_safe_subset(
154    dc_array: &[u32],
155) -> Result<(Vec<u8>, FormatLog)> {
156    let mut log: FormatLog = FormatLog::default();
157    let len = dc_array.len();
158    let mut out: Vec<u8> = Vec::new();
159    let mut input_index = 0usize;
160
161    fn warn_unmappable(
162        log: &mut FormatLog,
163        input_index: usize,
164        dc: u32,
165    ) -> Result<()> {
166        let index = u64::try_from(input_index)
167            .map_err(|e| anyhow!("Failed to convert input_index: {e}"))?;
168        log.export_warning_unmappable(index, dc, "asciiSafeSubset");
169        Ok(())
170    }
171
172    while input_index < len {
173        let dc = *dc_array
174            .get(input_index)
175            .ok_or_else(|| anyhow!("Index out of bounds"))?;
176
177        // Found ambiguous cr, lf in a row, so only output one crlf
178        if dc == 121 {
179            let next_dc = if input_index.saturating_add(1) < len {
180                #[expect(
181                    clippy::expect_used,
182                    reason = "input_index + 1 < len check guarantees in-bounds access"
183                )]
184                dc_array.get(input_index.saturating_add(1)).copied().expect(
185                    "input_index + 1 < len check guarantees in-bounds access",
186                )
187            } else {
188                0
189            };
190            if next_dc == 120 {
191                out.extend(crlf());
192                input_index = input_index.saturating_add(2);
193                if input_index >= len {
194                    break;
195                }
196                continue;
197            }
198        }
199
200        if dc_is_newline(dc) {
201            out.extend(crlf());
202        } else {
203            // Map Dc to UTF-8 (one or more bytes)
204            let (enc, dc_log) = if let Ok(res) = dc_to_format("utf8", dc) {
205                res
206            } else {
207                warn_unmappable(&mut log, input_index, dc)?;
208                input_index = input_index.saturating_add(1);
209                continue;
210            };
211            log.merge(&dc_log);
212            if enc.is_empty() {
213                warn_unmappable(&mut log, input_index, dc)?;
214                input_index = input_index.saturating_add(1);
215                continue;
216            }
217            #[expect(
218                clippy::expect_used,
219                reason = "enc.is_empty() check on line 185 guarantees enc is non-empty"
220            )]
221            let first_enc =
222                *enc.first().expect("enc is non-empty checked on line 185");
223            if enc.len() == 1
224                && is_ascii_safe_subset_char(first_enc)
225                && !dc_is_newline(dc)
226            {
227                out.push(first_enc);
228            } else if enc.len() == 1 && dc_is_newline(dc) {
229                out.extend(crlf());
230            } else {
231                // Non-printable or multi-byte is not mappable in this subset
232                warn_unmappable(&mut log, input_index, dc)?;
233            }
234        }
235        input_index = input_index.saturating_add(1);
236    }
237
238    Ok((out, log))
239}
240
241#[cfg(test)]
242#[allow(
243    clippy::panic,
244    clippy::expect_used,
245    clippy::unwrap_used,
246    clippy::unwrap_in_result,
247    clippy::panic_in_result_fn,
248    clippy::indexing_slicing,
249    clippy::arithmetic_side_effects,
250    reason = "Standard repository test boilerplate"
251)]
252mod tests {
253    use crate::utilities::assert_vec_u32_eq;
254    use ctb_formats_utilities::{
255        assert_vec_u8_ok_eq_no_errors, assert_vec_u8_ok_eq_no_warnings,
256        assert_vec_u32_ok_eq_no_warnings,
257    };
258
259    use super::*;
260    const SETTINGS: AsciiSafeSubsetFormatSettings =
261        <AsciiSafeSubsetFormatSettings as ConstDefault>::DEFAULT;
262
263    #[crate::ctb_test]
264    fn test_ascii_roundtrip_simple() {
265        let sample = b"Hello!";
266        let (dc, _log) = dca_from_ascii(sample).expect("from ascii");
267        // Dc array should be identical numerically.
268        assert_vec_u32_eq(&[57, 86, 93, 93, 96, 19], &dc);
269        // Returns a tuple Vec<u8>, Vec<String> with the strings being warnings, so unwrap the u8
270        let out = dca_to_ascii(&dc);
271        assert_vec_u8_ok_eq_no_warnings(sample, out);
272    }
273
274    #[crate::ctb_test]
275    fn test_dca_from_ascii_basic() {
276        // Input ASCII bytes
277        let input = [0u8, 5, 10, 15, 20, 25, 30, 35, 40];
278        // Expected internal Dc array from original JS
279        let expected = [0, 212, 120, 216, 221, 226, 231, 21, 26];
280        let (actual, _log) =
281            dca_from_ascii(&input).expect("dca_from_ascii failed");
282        assert_vec_u32_eq(&expected, &actual);
283    }
284
285    #[crate::ctb_test]
286    fn test_dca_to_ascii_ignores_not_mappable_dc() {
287        // Includes Dc 291, which is not mappable to ASCII and so is omitted,
288        // and a warning logged.
289        let input = [0, 212, 120, 216, 291, 221, 226, 231, 21, 26];
290        let expected = [0u8, 5, 10, 15, 20, 25, 30, 35, 40];
291        let actual = dca_to_ascii(&input);
292        let (_res, log) = assert_vec_u8_ok_eq_no_errors(&expected, actual);
293        assert!(log.has_warnings());
294    }
295
296    #[crate::ctb_test]
297    fn test_format_ascii_safe_subset() {
298        // dcaFromAsciiSafeSubset([13,10,35,40]) -> [121,120,21,26]
299        assert_vec_u32_ok_eq_no_warnings(
300            &[121, 120, 21, 26],
301            dca_from_ascii_safe_subset(&[13, 10, 35, 40], &SETTINGS),
302        );
303
304        // dcaToAsciiSafeSubset([...]) -> [13,10,35,13,10,40]
305        let input = [
306            0,   // Null
307            212, // Enquiry
308            120, // Ambiguous LF
309            216, // Shift In
310            291, // Yellow
311            221, // DC4
312            226, // End of medium
313            231, // IS2
314            21,  // Number sign
315            121, // Ambiguous CR
316            120, // Ambiguous LF
317            26,  // Left parenthesis
318        ];
319        let (_result, log) = assert_vec_u8_ok_eq_no_errors(
320            &[13, 10, 35, 13, 10, 40],
321            dca_to_ascii_safe_subset(&input),
322        );
323        assert!(log.has_warnings());
324    }
325
326    #[crate::ctb_test]
327    fn test_is_ascii_safe_subset_char() {
328        assert!(is_ascii_safe_subset_char(b'A'));
329        assert!(is_ascii_safe_subset_char(b' '));
330        assert!(is_ascii_safe_subset_char(b'\n'));
331        assert!(!is_ascii_safe_subset_char(0x7F));
332    }
333}