ctb_formats_eite/formats/
sems.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//! SEMS format parser and exporter for EITE compatibility.
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::formats::FormatLog;
33use crate::formats::dcbasenb::dca_to_dcbnb_utf8;
34use crate::formats::utf8::{UTF8FormatSettings, dca_from_utf8};
35use crate::util::ascii::{ascii_is_digit, ascii_is_newline, crlf};
36
37#[derive(ConstDefault, Default, Debug, Clone)]
38pub struct SEMSFormatSettings {
39    pub strict: bool,
40}
41
42fn get_index(res: &[u32]) -> u64 {
43    // Reason for fallback: usize fits within u64 on 32-bit and 64-bit systems, so try_from conversion never overflows.
44    u64::try_from(res.len()).unwrap_or(0)
45}
46
47/// Parse SEMS format (space-delimited integers with `#` comments).
48/// Comments are bracketed with Dc 246 (begin single-line comment) and Dc 248 (end).
49pub fn dca_from_sems(
50    content: &[u8],
51    settings: &SEMSFormatSettings,
52) -> Result<(Vec<u32>, FormatLog)> {
53    // Strict mode?
54    let bool_strict = settings.strict;
55
56    let mut log: FormatLog = FormatLog::default();
57    let mut res: Vec<u32> = Vec::new();
58    let mut parser_state = "dc";
59    let mut current_dc = String::new();
60
61    let mut idx = 0usize;
62    while let Some(&b) = content.get(idx) {
63        match parser_state {
64            "dc" => {
65                if ascii_is_digit(b) {
66                    current_dc.push(char::from(b));
67                } else if b == b' ' || b == b'\n' || b == b'\r' {
68                    if !current_dc.is_empty() {
69                        // Error here would indicate a parser bug
70                        let val = current_dc.parse::<u32>()?;
71                        res.push(val);
72                        current_dc.clear();
73                    }
74                } else if b == b'#' {
75                    if !current_dc.is_empty() {
76                        // Warning for missing trailing space before comment
77                        if bool_strict {
78                            log.import_error(get_index(&res), "No trailing space before comment present in sems format while importing. This is not allowed in strict mode.");
79                            return Ok((res, log));
80                        }
81                        log.import_warning(get_index(&res), "No trailing space before comment present in sems format while importing.");
82                        let val = current_dc.parse::<u32>()?;
83                        res.push(val);
84                        current_dc.clear();
85                    }
86                    // Push begin comment sentinel
87                    res.push(246);
88                    parser_state = "comment";
89                } else {
90                    log.import_error(
91                        get_index(&res),
92                        "Invalid character in sems format while importing.",
93                    );
94                    return Ok((res, log));
95                }
96            }
97            "comment" => {
98                // Append mapped Dc(s) from this unicode char byte
99                // (The original code treated bytes as Unicode scalar values)
100                let mut until_next_newline = Vec::new();
101                let mut i = 0usize;
102                while idx.saturating_add(i) < content.len() {
103                    let offset = idx.saturating_add(i);
104                    let b = content
105                        .get(offset)
106                        .copied()
107                        .ok_or_else(|| anyhow!("Index out of bounds"))?;
108                    if ascii_is_newline(b) {
109                        parser_state = "dc";
110                        // don't consume and advance past the newline here; give
111                        // it back to the outer loop
112                        break;
113                    }
114                    until_next_newline.push(b);
115                    i = i.saturating_add(1);
116                    if idx.saturating_add(i) == content.len() {
117                        // End of content reached; will handle end-of-file below
118                        break;
119                    }
120                }
121                let (mapped, inner_log) = dca_from_utf8(
122                    &until_next_newline,
123                    &UTF8FormatSettings::default(),
124                )?;
125                res.extend(mapped);
126                log.merge(&inner_log);
127                // End comment sentinel
128                res.push(248);
129                idx = idx.saturating_add(i);
130            }
131            _ => bail!(
132                "Internal error: unexpected parser state while parsing SEMS document"
133            ),
134        }
135
136        idx = idx.saturating_add(1);
137    }
138
139    // End-of-file handling
140    if parser_state == "comment" {
141        if !current_dc.is_empty() {
142            log.import_error(
143                get_index(&res),
144                format!(
145                    "Internal error while parsing sems document: Unconsumed characters at end: {current_dc}."
146                )
147                .as_str(),
148            );
149            return Ok((res, log));
150        }
151    } else if !current_dc.is_empty() {
152        if bool_strict {
153            log.import_error(
154                get_index(&res),
155                "No trailing space present in sems format while importing. This is not allowed in strict mode.",
156            );
157            return Ok((res, log));
158        }
159        log.import_warning(
160            get_index(&res),
161            "No trailing space present in sems format while importing.",
162        );
163        // Error here would indicate a parser bug
164        let val = current_dc.parse::<u32>()?;
165        res.push(val);
166    }
167
168    Ok((res, log))
169}
170
171/// Export Dc array to SEMS format.
172///
173/// - Dc 246 begins a single-line comment region
174/// - Dc 248 ends the comment region
175///
176/// Comment contents are encoded with `dca_to_dcbnb_utf8`.
177pub fn dca_to_sems(dc_array: &[u32]) -> Result<(Vec<u8>, FormatLog)> {
178    let mut log: FormatLog = FormatLog::default();
179    let mut out: Vec<u8> = Vec::new();
180
181    let mut in_comment = false;
182    let mut at_comment_end = false;
183    let mut current_comment: Vec<u32> = Vec::new();
184
185    for &dc in dc_array {
186        if at_comment_end {
187            at_comment_end = false;
188        }
189        if dc == 246 {
190            in_comment = true;
191            out.push(b'#');
192        } else if dc == 248 {
193            in_comment = false;
194            at_comment_end = true;
195            let (enc, dcbnb_log) = dca_to_dcbnb_utf8(
196                &current_comment,
197                &UTF8FormatSettings::default(),
198            )?;
199            log.merge(&dcbnb_log);
200            out.extend(enc);
201            current_comment.clear();
202            out.extend(crlf());
203        } else if in_comment {
204            current_comment.push(dc);
205        } else {
206            out.extend(dc.to_string().as_bytes());
207            out.push(b' ');
208        }
209    }
210
211    if !at_comment_end {
212        out.extend(crlf());
213    }
214
215    Ok((out, log))
216}
217
218#[cfg(test)]
219#[allow(
220    clippy::panic,
221    clippy::expect_used,
222    clippy::unwrap_used,
223    clippy::unwrap_in_result,
224    clippy::panic_in_result_fn,
225    clippy::indexing_slicing,
226    clippy::arithmetic_side_effects,
227    reason = "Standard repository test boilerplate"
228)]
229mod tests {
230    use crate::utilities::assert_vec_u32_eq;
231    use crate::{
232        assert_vec_dc_ok_eq_no_errors, assert_vec_dc_ok_eq_no_warnings,
233    };
234    use ctb_formats_utilities::assert_vec_u8_ok_eq_no_warnings;
235
236    use super::*;
237
238    const SETTINGS: SEMSFormatSettings =
239        <SEMSFormatSettings as ConstDefault>::DEFAULT;
240
241    // Tests translated from original JS runTestsFormatSems / runTestsFormatAscii.
242    //
243    // Original JS snippet (for reference):
244    // runTestsFormatSems(boolV) { ... }
245    // runTestsFormatAscii(boolV) { ... }
246    //
247    // Notes:
248    // - The original harness used runTest / arrEq / debug helpers and a boolV verbosity flag.
249    //   Here we use standard Rust #[crate::ctb_test] functions with direct assertions.
250    // - A commented (not yet implemented) failure case in the original JS for
251    //   double-space separation (`49 32 32 50`) is preserved as a TODO.
252    // - The "Currently does not output the 65 ..." FIXME from the source is kept
253    //   as a comment; the expected value (including 65) is asserted to match the
254    //   source test vector.
255    //
256    // Required public functions (expected to exist elsewhere in crate::):
257    //   - dca_from_sems(content: &[u8]) -> Result<Vec<i32>>
258    //   - dca_to_sems(dc_array: &[u32]) -> Result<Vec<u8>>   (assumed, based on JS test dcaToSems)
259    //   - dca_from_ascii(content: &[u8]) -> Result<Vec<i32>>
260    //   - dca_to_ascii(state: &EiteState, dc_array: &[u32]) -> Result<Vec<u8>>
261    //
262    // If any of these are not yet implemented, these tests will fail to compile;
263    // implement them (or adjust module paths) accordingly.
264
265    // ---------------------------
266    // Sems format tests
267    // ---------------------------
268
269    #[crate::ctb_test]
270    fn test_dca_from_sems_basic_no_trailing_space() {
271        // Input bytes: '1', ' ', '2'
272        let input = [49u8, 32, 50];
273        let expected = [1, 2];
274        let (actual, _log) =
275            dca_from_sems(&input, &SEMSFormatSettings::default())
276                .expect("dca_from_sems failed");
277        assert_vec_u32_eq(&expected, &actual);
278    }
279
280    // Original JS had (commented out):
281    // /* Should fail but I do not yet have a failure assertion:
282    //    runTest b/v arrEq ( 1 2 ) dcaFromSems ( 49 32 32 50 ) */
283    // Keeping as a TODO.
284    //
285    // #[crate::ctb_test]
286    // fn test_dca_from_sems_double_space_should_fail() {
287    //     let input = [49u8, 32, 32, 50];
288    //     // Decide expected behavior once implementation defines error vs. leniency.
289    // }
290
291    #[crate::ctb_test]
292    fn test_dca_to_sems_basic_trailing_space_crlf() {
293        // Expected bytes: '1', ' ', '2', ' ', '\r', '\n'
294        let input = [1, 2];
295        let expected = [49u8, 32, 50, 32, 13, 10];
296        assert_vec_u8_ok_eq_no_warnings(&expected, dca_to_sems(&input));
297    }
298
299    #[crate::ctb_test]
300    fn test_dca_from_sems_comment_preservation() {
301        // Input bytes: '1',' ','2','#','A'
302        let input = [49u8, 32, 50, 35, 65];
303        let expected = [1u32, 2, 246, 50, 248];
304        let (_out, log) = assert_vec_dc_ok_eq_no_errors(
305            &expected,
306            dca_from_sems(&input, &SETTINGS),
307        );
308        assert!(log.has_warnings());
309    }
310
311    #[crate::ctb_test]
312    fn test_dca_to_sems_comment_preservation() {
313        // Expected bytes: '1',' ','2',' ','#','A','\r','\n'
314        // Original snippet note:
315        // /* Currently does not output the 65 from the desired result (FIXME not implemented) */
316        // The test still expects 65 ( 'A' ) per original arrEq.
317        let input = [1, 2, 246, 50, 248];
318        let expected = [49u8, 32, 50, 32, 35, 65, 13, 10];
319        assert_vec_u8_ok_eq_no_warnings(&expected, dca_to_sems(&input));
320    }
321
322    #[crate::ctb_test]
323    fn test_dca_from_sems_utf8_comments() {
324        // Long UTF-8-with-comments input:
325        // This is the following two 0x0A-delimited lines:
326        // 256 258 260 262 264 263 57 86 93 93 96 30 18 286 72 96 99 93 85 287 19 18 284 261 259 # say "Hello, /World/! ⚽"
327        // 1 2 # ⚽
328        let input: Vec<u8> = vec![
329            50, 53, 54, 32, 50, 53, 56, 32, 50, 54, 48, 32, 50, 54, 50, 32, 50,
330            54, 52, 32, 50, 54, 51, 32, 53, 55, 32, 56, 54, 32, 57, 51, 32, 57,
331            51, 32, 57, 54, 32, 51, 48, 32, 49, 56, 32, 50, 56, 54, 32, 55, 50,
332            32, 57, 54, 32, 57, 57, 32, 57, 51, 32, 56, 53, 32, 50, 56, 55, 32,
333            49, 57, 32, 49, 56, 32, 50, 56, 52, 32, 50, 54, 49, 32, 50, 53, 57,
334            32, 35, 32, 115, 97, 121, 32, 34, 72, 101, 108, 108, 111, 44, 32,
335            47, 87, 111, 114, 108, 100, 47, 33, 32, 226, 154, 189, 34, 10, 49,
336            32, 50, 32, 35, 32, 226, 154, 189, 10,
337        ];
338
339        let expected: Vec<u32> = vec![
340            256, 258, 260, 262, 264, 263, 57, 86, 93, 93, 96, 30, 18, 286, 72,
341            96, 99, 93, 85, 287, 19, 18, 284, 261, 259, 246, 18, 100, 82, 106,
342            18, 20, 57, 86, 93, 93, 96, 30, 18, 33, 72, 96, 99, 93, 85, 33, 19,
343            18, 281, 20, 248, 1, 2, 246, 18, 281, 248,
344        ];
345
346        assert_vec_dc_ok_eq_no_warnings(
347            &expected,
348            dca_from_sems(&input, &SEMSFormatSettings::default()),
349        );
350    }
351
352    #[crate::ctb_test]
353    fn test_sems_comment_basic() {
354        // "12 34 #comment\n56 "
355        let input = b"12 34 #hello\n56 ";
356        let (dca, _log) =
357            dca_from_sems(input, &SEMSFormatSettings::default()).unwrap();
358        // Should contain 12,34,246,<comment content...>,248,56
359        assert!(dca.starts_with(&[12, 34, 246]));
360        assert!(dca.contains(&248));
361        assert!(dca.ends_with(&[56]));
362    }
363}