ctb_formats_dcstring/converters/
eite.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//! Conversion between EITE formats (`IntegerList`, SEMS, Ascii, `AsciiSafeSubset`) and `DcMstring`.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use anyhow::{Context, Result};
30use ctb_formats_utilities::FormatLog;
31
32use super::dctext::{dcarray_to_dclist, dclist_to_dcarray, dclist_to_dctf};
33use crate::{DcMstring, DcStr};
34
35fn dca_to_dcmstring(
36    dca: &[u32],
37    accumulated_log: &mut FormatLog,
38) -> Result<DcMstring> {
39    let conv = dcarray_to_dclist(dca)?;
40    accumulated_log.merge(&conv.log);
41    let dctf_bytes = dclist_to_dctf(&conv.result);
42    let dc_str = DcStr::from_bytes(&dctf_bytes)
43        .context("Converting dclist to valid DcTF DcStr")?;
44    DcMstring::from_dc_str(dc_str)
45}
46
47fn dcmstring_to_dca(doc: &DcMstring) -> Result<(Vec<u32>, FormatLog)> {
48    let dc_string = super::document_dc_string(doc)?;
49    let dclist = dc_string.to_dclist();
50    let conv = dclist_to_dcarray(&dclist)?;
51    Ok((conv.result, conv.log))
52}
53
54/// Converts a `DcIntegerList` document (`.dcil`) to `DcMstring`.
55pub fn dcil_to_dcmstring(bytes: &[u8]) -> Result<(DcMstring, FormatLog)> {
56    dcil_to_dcmstring_with_options(bytes, false)
57}
58
59/// Converts a `DcIntegerList` document (`.dcil`) to `DcMstring`, optionally in permissive mode.
60pub fn dcil_to_dcmstring_with_options(
61    bytes: &[u8],
62    permissive: bool,
63) -> Result<(DcMstring, FormatLog)> {
64    let (dca, raw_log) = ctb_formats_eite::formats::integer_list::dca_from_integer_list(
65        bytes,
66        &ctb_formats_eite::formats::integer_list::IntegerListFormatSettings::default(),
67    )?;
68    if !permissive && raw_log.has_errors() {
69        let errs = raw_log.get_errors().join("; ");
70        bail!(
71            "Input does not conform to valid DcIntegerList (.dcil) format: {errs}"
72        );
73    }
74    let mut log = if permissive && raw_log.has_errors() {
75        let mut downgraded = FormatLog::default();
76        for w in raw_log.get_warnings() {
77            downgraded.warn(&w);
78        }
79        for err in raw_log.get_errors() {
80            downgraded.warn(&err);
81        }
82        downgraded
83    } else {
84        raw_log
85    };
86    let doc = dca_to_dcmstring(&dca, &mut log)?;
87    Ok((doc, log))
88}
89
90/// Converts an ELAD (`.elad` / `.emd`) document into a [`DcMstring`].
91pub fn elad_to_dcmstring_with_options(
92    bytes: &[u8],
93    permissive: bool,
94) -> Result<(DcMstring, FormatLog)> {
95    let (dca, raw_log) = ctb_formats_eite::formats::elad::dca_from_elad(bytes)?;
96    if !permissive && raw_log.has_errors() {
97        let errs = raw_log.get_errors().join("; ");
98        bail!(
99            "Input does not conform to valid ELAD (.elad / .emd) format: {errs}"
100        );
101    }
102    let mut log = if permissive && raw_log.has_errors() {
103        let mut downgraded = FormatLog::default();
104        for w in raw_log.get_warnings() {
105            downgraded.warn(&w);
106        }
107        for err in raw_log.get_errors() {
108            downgraded.warn(&err);
109        }
110        downgraded
111    } else {
112        raw_log
113    };
114    let doc = dca_to_dcmstring(&dca, &mut log)?;
115    Ok((doc, log))
116}
117
118/// Converts a `DcMstring` to `DcIntegerList` document bytes (`.dcil`).
119pub fn dcmstring_to_dcil(doc: &DcMstring) -> Result<(Vec<u8>, FormatLog)> {
120    let (dca, log) = dcmstring_to_dca(doc)?;
121    let bytes =
122        ctb_formats_eite::formats::integer_list::dca_to_integer_list(&dca);
123    Ok((bytes, log))
124}
125
126/// Converts a SEMS document (`.sems`) to `DcMstring`.
127pub fn sems_to_dcmstring(bytes: &[u8]) -> Result<(DcMstring, FormatLog)> {
128    sems_to_dcmstring_with_options(bytes, false)
129}
130
131/// Converts a SEMS document (`.sems`) to `DcMstring`, optionally in permissive mode.
132pub fn sems_to_dcmstring_with_options(
133    bytes: &[u8],
134    permissive: bool,
135) -> Result<(DcMstring, FormatLog)> {
136    let (dca, raw_log) = ctb_formats_eite::formats::sems::dca_from_sems(
137        bytes,
138        &ctb_formats_eite::formats::sems::SEMSFormatSettings::default(),
139    )?;
140    if !permissive && raw_log.has_errors() {
141        let errs = raw_log.get_errors().join("; ");
142        bail!("Input does not conform to valid SEMS (.sems) format: {errs}");
143    }
144    let mut log = if permissive && raw_log.has_errors() {
145        let mut downgraded = FormatLog::default();
146        for w in raw_log.get_warnings() {
147            downgraded.warn(&w);
148        }
149        for err in raw_log.get_errors() {
150            downgraded.warn(&err);
151        }
152        downgraded
153    } else {
154        raw_log
155    };
156    let doc = dca_to_dcmstring(&dca, &mut log)?;
157    Ok((doc, log))
158}
159
160/// Converts a `DcMstring` to SEMS document bytes (`.sems`).
161pub fn dcmstring_to_sems(doc: &DcMstring) -> Result<(Vec<u8>, FormatLog)> {
162    let (dca, mut log) = dcmstring_to_dca(doc)?;
163    let (bytes, sems_log) = ctb_formats_eite::formats::sems::dca_to_sems(&dca)?;
164    log.merge(&sems_log);
165    Ok((bytes, log))
166}
167
168/// Converts a `DcMstring` to an HTML document (`.html`).
169pub fn dcmstring_to_html(doc: &crate::DcMstr) -> Result<(Vec<u8>, FormatLog)> {
170    let (fragment, log) = dcmstring_to_html_fragment(doc)?;
171    let mut bytes = b"<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title></title></head><body>".to_vec();
172    bytes.extend_from_slice(&fragment);
173    bytes.extend_from_slice(b"</body></html>");
174    Ok((bytes, log))
175}
176
177/// Converts a `DcMstring` to an HTML fragment (`.htmfrag`).
178pub fn dcmstring_to_html_fragment(
179    doc: &crate::DcMstr,
180) -> Result<(Vec<u8>, FormatLog)> {
181    let (text, log) = super::utf8::dcmstring_to_utf8(doc)?;
182    let escaped =
183        ctb_formats_html::entities::escape_text(std::str::from_utf8(&text)?);
184    let bytes = format!("<div style=\"white-space:pre-wrap\">{escaped}</div>")
185        .into_bytes();
186    Ok((bytes, log))
187}
188
189/// Converts a `DcMstring` to a color-coded HTML integer list document.
190pub fn dcmstring_to_eite_colorcoded(
191    doc: &DcMstring,
192) -> Result<(Vec<u8>, FormatLog)> {
193    let (dca, log) = dcmstring_to_dca(doc)?;
194    let bytes = ctb_formats_eite::formats::html::dca_to_colorcoded(&dca)?;
195    Ok((bytes, log))
196}
197
198pub use crate::converters::ascii::{
199    ascii_safe_subset_to_dcmstring, ascii_to_dcmstring, dcmstring_to_ascii,
200    dcmstring_to_ascii_safe_subset,
201};
202
203#[cfg(test)]
204#[allow(
205    clippy::panic,
206    clippy::expect_used,
207    clippy::unwrap_used,
208    clippy::unwrap_in_result,
209    clippy::panic_in_result_fn,
210    clippy::indexing_slicing,
211    clippy::arithmetic_side_effects,
212    reason = "Standard repository test boilerplate"
213)]
214mod tests {
215    use super::*;
216
217    #[crate::ctb_test]
218    fn test_dcil_conversion_preserves_legacy_dcs() -> Result<()> {
219        let input = b"313 275 275 65 312 66 314 265 514 65 312 66 515 999";
220        let (doc, _) = dcil_to_dcmstring(input)?;
221        let (utf, _) = crate::converters::utf8::dcmstring_to_dcutf(&doc)?;
222        let (restored, _) = crate::converters::utf8::dcutf_to_dcmstring(&utf)?;
223        let (output, _) = dcmstring_to_dcil(&restored)?;
224        assert_eq!(
225            std::str::from_utf8(&output)?.trim(),
226            std::str::from_utf8(input)?
227        );
228        Ok(())
229    }
230
231    #[crate::ctb_test]
232    fn test_dcil_roundtrip() {
233        let input = b"65 66 67 ";
234        let (doc, _) = dcil_to_dcmstring(input).expect("parse dcil");
235        assert_eq!(
236            doc.to_dc_string().unwrap().to_dclist(),
237            vec![
238                ctb_formats_dcdata::dc::SHORT_DC_REGION_START
239                    .saturating_add(65),
240                ctb_formats_dcdata::dc::SHORT_DC_REGION_START
241                    .saturating_add(66),
242                ctb_formats_dcdata::dc::SHORT_DC_REGION_START
243                    .saturating_add(67),
244            ]
245        );
246
247        let (out_bytes, _) = dcmstring_to_dcil(&doc).expect("serialize dcil");
248        assert_eq!(std::str::from_utf8(&out_bytes).unwrap().trim(), "65 66 67");
249    }
250}