ctb_formats_eite/formats/
integer_list.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//! Integer list formatting and delimited sequence encoder 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;
30
31use crate::formats::FormatLog;
32use crate::util::ascii::ascii_is_digit;
33
34#[derive(Default)]
35pub struct IntegerListFormatSettings {
36    pub strict: bool,
37}
38
39/// Import an integer list (space-delimited decimal integers).
40/// Same as SEMS without comments.
41pub fn dca_from_integer_list(
42    content: &[u8],
43    settings: &IntegerListFormatSettings,
44) -> Result<(Vec<u32>, FormatLog)> {
45    let mut log = FormatLog::default();
46    let mut res: Vec<u32> = Vec::new();
47    let mut current = String::new();
48
49    for &b in content {
50        if ascii_is_digit(b) {
51            current.push(char::from(b));
52        } else if b == b' ' || b == b'\n' || b == b'\r' {
53            if !current.is_empty() {
54                res.push(current.parse::<u32>()?);
55                current.clear();
56            }
57        } else {
58            log.error("Unexpected parser state in integerList document.");
59            return Ok((res, log));
60        }
61    }
62
63    if !current.is_empty() {
64        let message = "No trailing space present in integerList format while importing. This is not allowed in strict mode.";
65        if settings.strict {
66            log.error(message);
67        } else {
68            log.warn(message);
69        }
70        // Strict setting (if desired) can be applied here; original code gates on
71        // getSettingForFormat('integerList','in','strict') == 'true'
72        // For now, we mirror original loose handling (warning could be added).
73        res.push(current.parse::<u32>()?);
74    }
75
76    Ok((res, log))
77}
78
79/// Export Dc array as a space-delimited integer list (trailing space retained).
80pub fn dca_to_integer_list(dc_array: &[u32]) -> Vec<u8> {
81    let mut out: Vec<u8> = Vec::new();
82    for &dc in dc_array {
83        out.extend(dc.to_string().as_bytes());
84        out.push(b' ');
85    }
86    out
87}
88
89#[cfg(test)]
90#[allow(
91    clippy::panic,
92    clippy::expect_used,
93    clippy::unwrap_used,
94    clippy::unwrap_in_result,
95    clippy::panic_in_result_fn,
96    clippy::indexing_slicing,
97    clippy::arithmetic_side_effects,
98    reason = "Standard repository test boilerplate"
99)]
100mod tests {
101    use super::*;
102
103    #[crate::ctb_test]
104    fn test_format_integer_list() {
105        let permissive = IntegerListFormatSettings::default();
106        // dcaFromIntegerList([49, 32, 50]) => [1,2]
107        let input_bytes = [49u8, 32, 50]; // "1 2"
108        let (parsed, warnings) =
109            dca_from_integer_list(&input_bytes, &permissive)
110                .expect("dca_from_integer_list should succeed");
111        assert_eq!(parsed, vec![1, 2]);
112        assert!(warnings.has_warnings()); // No trailing space
113        assert!(!warnings.has_errors());
114
115        let input_bytes = [49u8, 10, 50]; // "1\n2"
116        let (parsed, warnings) =
117            dca_from_integer_list(&input_bytes, &permissive)
118                .expect("dca_from_integer_list should succeed");
119        assert_eq!(parsed, vec![1, 2]);
120        assert!(warnings.has_warnings()); // No trailing space
121        assert!(!warnings.has_errors());
122
123        // dcaToIntegerList([1,2]) => [49, 32, 50, 32]  ("1 2 ")
124        let back = dca_to_integer_list(&[1, 2]);
125        assert_eq!(back, vec![49u8, 32, 50, 32]);
126
127        let input = b"10 20 30 40 290 ";
128        let (dca, warnings) =
129            dca_from_integer_list(input, &permissive).unwrap();
130        assert!(!warnings.has_warnings());
131        assert_eq!(dca, vec![10, 20, 30, 40, 290]);
132
133        let exported = dca_to_integer_list(&dca);
134        assert_eq!(std::str::from_utf8(&exported).unwrap(), "10 20 30 40 290 ");
135
136        // Test strict mode
137        let strict = IntegerListFormatSettings { strict: true };
138
139        let (dca, warnings) = dca_from_integer_list(input, &strict).unwrap();
140        assert_eq!(dca, vec![10, 20, 30, 40, 290]);
141        assert!(!warnings.has_warnings());
142
143        let input_no_trailing_space = b"10 20 30 40 290";
144        let (dca, warnings) =
145            dca_from_integer_list(input_no_trailing_space, &strict).unwrap();
146        assert_eq!(dca, vec![10, 20, 30, 40, 290]);
147        assert!(warnings.has_errors());
148    }
149}