ctb_formats_conversion/
convert_bytes.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//! In-memory document conversions between `DcMstring` and supported document formats.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use std::path::Path;
30
31use anyhow::{Context, Result, bail};
32pub use ctb_formats_dcstring::DcNormalizationMode;
33use ctb_formats_dcstring::DcMstring;
34use ctb_formats_utilities::FormatLog;
35use ctb_utilities::FormatId;
36use ctb_utilities::format_support::{
37    SupportedDcInputFormat, SupportedDcOutputFormat, SupportedDcTransformation,
38};
39
40pub use ctb_io_csc::journal::convert_cscjournal_to_dcmstring;
41
42/// Specification for input format: explicit format or automatic detection.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
44pub enum FormatSpec {
45    /// Autodetect format from magic bytes, filename extension, and content sniffing.
46    #[default]
47    Auto,
48    /// Expect a specific supported Dc input format.
49    Format(SupportedDcInputFormat),
50    /// Expect an arbitrary `FormatId`.
51    FormatId(FormatId),
52}
53
54impl From<SupportedDcInputFormat> for FormatSpec {
55    fn from(fmt: SupportedDcInputFormat) -> Self {
56        Self::Format(fmt)
57    }
58}
59
60impl From<FormatId> for FormatSpec {
61    fn from(id: FormatId) -> Self {
62        Self::FormatId(id)
63    }
64}
65
66/// Options controlling conversion to `DcMstring`.
67#[derive(Debug, Clone, PartialEq, Eq, Default)]
68pub struct DcConversionOptions {
69    /// Input format specification (default: Auto).
70    pub format: FormatSpec,
71    /// If format cannot be decoded as a known Dc/text document, encapsulate raw
72    /// bytes directly as `DcMixed::Binary`.
73    pub allow_binary_encapsulation: bool,
74    /// Parse input in permissive/forgiving mode (recovering from invalid headers,
75    /// characters, or checksums with warnings instead of returning an error).
76    pub permissive: bool,
77}
78
79/// Result of a format conversion including the parsed `DcMstring`, detected format,
80/// and accumulated diagnostic log.
81#[derive(Debug)]
82pub struct DcConversionResult {
83    /// The decoded `DcMstring` document.
84    pub document: DcMstring,
85    /// The detected or specified input `FormatId`.
86    pub detected_format: FormatId,
87    /// Format conversion log containing warnings, errors, and debug notices.
88    pub log: FormatLog,
89}
90
91/// Options controlling conversion from `DcMstring` to other document formats.
92#[derive(Debug, Clone, PartialEq, Eq, Default)]
93pub struct DcExportOptions {
94    /// Target output format (default: Utf8).
95    pub format: SupportedDcOutputFormat,
96    /// Export document in permissive/forgiving mode (canonicalizing equivalent
97    /// characters and recovering with warnings instead of failing or logging errors).
98    pub permissive: bool,
99    /// Optional explicit normalization policy override.
100    /// When `None`, defaults to `DcNormalizationMode::RequiredByTarget` in permissive mode
101    /// and `DcNormalizationMode::None` in strict mode.
102    pub normalization: Option<DcNormalizationMode>,
103    /// Optional ordered list of document transformations to apply before export.
104    pub transformations: Vec<SupportedDcTransformation>,
105}
106
107impl DcExportOptions {
108    /// Returns the effective normalization policy (`RequiredByTarget` by default
109    /// in permissive mode, `None` by default in strict mode, or the explicit override).
110    #[must_use]
111    pub const fn effective_normalization(&self) -> DcNormalizationMode {
112        if let Some(mode) = self.normalization {
113            mode
114        } else if self.permissive {
115            DcNormalizationMode::RequiredByTarget
116        } else {
117            DcNormalizationMode::None
118        }
119    }
120}
121
122/// Result of an export conversion from `DcMstring` to output format bytes.
123#[derive(Debug)]
124pub struct DcExportResult {
125    /// Serialized output bytes.
126    pub bytes: Vec<u8>,
127    /// Target format ID.
128    pub target_format: FormatId,
129    /// Diagnostic conversion log.
130    pub log: FormatLog,
131}
132
133fn single_byte_encoding_to_dcmstring(
134    id: FormatId,
135    bytes: &[u8],
136) -> Result<(DcMstring, FormatLog)> {
137    let enc = ctb_formats_encoding::CharEncoding::from_format_id(id)
138        .ok_or_else(|| {
139            anyhow::anyhow!("Unsupported single-byte encoding: {id:?}")
140        })?;
141    let text = ctb_formats_encoding::decode(enc, bytes)?;
142    let mut doc = DcMstring::with_capacity(text.len());
143    doc.push_str(&text);
144    Ok((doc, FormatLog::default()))
145}
146
147fn dcmstring_to_single_byte_encoding(
148    id: FormatId,
149    doc: &DcMstring,
150    permissive: bool,
151    normalization: DcNormalizationMode,
152) -> Result<(Vec<u8>, FormatLog)> {
153    let enc = ctb_formats_encoding::CharEncoding::from_format_id(id)
154        .ok_or_else(|| {
155            anyhow::anyhow!("Unsupported single-byte encoding: {id:?}")
156        })?;
157    let (utf8_bytes, mut log) =
158        ctb_formats_dcstring::converters::utf8::dcmstring_to_utf8_with_normalization(
159            doc,
160            permissive,
161            normalization,
162        )?;
163    let text = std::str::from_utf8(&utf8_bytes)
164        .context("Internal UTF-8 conversion produced invalid UTF-8")?;
165    let bytes = match ctb_formats_encoding::encode(enc, text) {
166        Ok(b) => b,
167        Err(err)
168            if normalization == DcNormalizationMode::RequiredByTarget
169                && !ctb_formats_unicode::is_nfc_normalized(text) =>
170        {
171            let nfc_text = ctb_formats_unicode::normalize_nfc(text);
172            let encoded =
173                ctb_formats_encoding::encode(enc, &nfc_text).map_err(|_| err)?;
174            if permissive {
175                log.export_warning(
176                    0,
177                    "Normalized Unicode text sequence to NFC as required by target encoding",
178                );
179            }
180            encoded
181        }
182        Err(err) => return Err(err),
183    };
184    Ok((bytes, log))
185}
186
187/// Formats the categorized list of supported input document formats for error and help messages.
188#[must_use]
189pub fn format_supported_input_formats_table(header: &str) -> String {
190    ctb_formats_utilities::format_categorized_help_table(
191        header,
192        SupportedDcInputFormat::ALL_FORMAT_IDS,
193    )
194}
195
196/// Formats the categorized list of supported output document formats for error and help messages.
197#[must_use]
198pub fn format_supported_output_formats_table(header: &str) -> String {
199    ctb_formats_utilities::format_categorized_help_table(
200        header,
201        SupportedDcOutputFormat::ALL_FORMAT_IDS,
202    )
203}
204
205/// Formats the categorized list of supported document transformations for error and help messages.
206#[must_use]
207pub fn format_supported_transformations_table(header: &str) -> String {
208    ctb_formats_utilities::format_categorized_help_table(
209        header,
210        SupportedDcTransformation::ALL_FORMAT_IDS,
211    )
212}
213
214/// Converts in-memory bytes with an optional filename hint to a `DcMstring`.
215pub fn convert_bytes_to_dcmstring(
216    bytes: &[u8],
217    filename_hint: Option<&str>,
218    options: &DcConversionOptions,
219) -> Result<DcConversionResult> {
220    let resolved_format: SupportedDcInputFormat = match options.format {
221        FormatSpec::Format(fmt) => fmt,
222        FormatSpec::FormatId(id) => {
223            if let Some(supported) = SupportedDcInputFormat::from_format_id(id)
224            {
225                supported
226            } else {
227                bail!(
228                    "{}",
229                    format_supported_input_formats_table(&format!(
230                        "Format {id:?} is not supported for conversion to DcMstring. Specify --from with one of:"
231                    ))
232                );
233            }
234        }
235        FormatSpec::Auto => {
236            let fid = ctb_formats_detection::detect_format_id_in_categories(
237                Some(bytes),
238                filename_hint,
239                &[
240                    ctb_utilities::FormatCategory::Document,
241                    ctb_utilities::FormatCategory::Encoding,
242                    ctb_utilities::FormatCategory::Database,
243                ],
244            );
245            let detected = match fid {
246                Some(FormatId::Text) => Some(SupportedDcInputFormat::Utf8),
247                Some(id) => SupportedDcInputFormat::from_format_id(id),
248                None => None,
249            };
250            if let Some(fmt) = detected {
251                fmt
252            } else if bytes.is_empty() {
253                SupportedDcInputFormat::Utf8
254            } else if options.allow_binary_encapsulation {
255                let mut doc = DcMstring::new();
256                doc.push_binary(bytes);
257                return Ok(DcConversionResult {
258                    document: doc,
259                    detected_format: FormatId::DcMixed,
260                    log: FormatLog::default(),
261                });
262            } else {
263                bail!(
264                    "{}",
265                    format_supported_input_formats_table(
266                        "Unable to autodetect document format for input. Specify --from with one of:"
267                    )
268                );
269            }
270        }
271    };
272
273    let dcmm_opts = ctb_formats_dcstring::DcmmStreamOptions {
274        best_effort: options.permissive,
275    };
276
277    let (document, log) = match resolved_format {
278        SupportedDcInputFormat::Utf8 => {
279            ctb_formats_dcstring::converters::utf8::utf8_to_dcmstring_with_options(
280                bytes,
281                options.permissive,
282            )
283            .context(
284                "NOTE: Parsing as UTF-8. If you want DcText, pass `--from dctext` on the command line.",
285            )?
286        }
287        SupportedDcInputFormat::DcText => {
288            ctb_formats_dcstring::converters::dctext::dctext_to_dcmstring_with_options(
289                bytes,
290                options.permissive,
291            )?
292        }
293        SupportedDcInputFormat::Dcts => {
294            ctb_formats_dcstring::converters::dcts::dcts_to_dcmstring_with_options(
295                bytes,
296                options.permissive,
297            )?
298        }
299        SupportedDcInputFormat::Dcal => {
300            ctb_formats_dcstring::converters::dcal::dcal_to_dcmstring_with_options(
301                bytes,
302                options.permissive,
303            )?
304        }
305        SupportedDcInputFormat::Csdl => {
306            ctb_formats_dcstring::converters::dcal::csdl_to_dcmstring_with_options(
307                bytes,
308                options.permissive,
309            )?
310        }
311        SupportedDcInputFormat::Dcsh => {
312            ctb_formats_dcstring::converters::dcal::dcsh_to_dcmstring_with_options(
313                bytes,
314                options.permissive,
315            )?
316        }
317        SupportedDcInputFormat::CtbNodeIncoming => {
318            ctb_formats_dcstring::converters::dcal::ctbnode_incoming_to_dcmstring_with_options(
319                bytes,
320                options.permissive,
321            )?
322        }
323        SupportedDcInputFormat::CtbNodes => {
324            ctb_formats_dcstring::converters::dcal::ctbnodes_to_dcmstring_with_options(
325                bytes,
326                options.permissive,
327            )?
328        }
329        SupportedDcInputFormat::CtbNodeBundle => {
330            ctb_formats_dcstring::converters::dcal::ctbnbdl_to_dcmstring_with_options(
331                bytes,
332                options.permissive,
333            )?
334        }
335        SupportedDcInputFormat::CtbNodeBundle1 => {
336            ctb_formats_dcstring::converters::dcal::ctbnbdl1_to_dcmstring_with_options(
337                bytes,
338                options.permissive,
339            )?
340        }
341        SupportedDcInputFormat::CtbNodeBundle2 => {
342            ctb_formats_dcstring::converters::dcal::ctbnbdl2_to_dcmstring_with_options(
343                bytes,
344                options.permissive,
345            )?
346        }
347        SupportedDcInputFormat::DcIntegerList => {
348            ctb_formats_dcstring::converters::eite::dcil_to_dcmstring_with_options(
349                bytes,
350                options.permissive,
351            )?
352        }
353        SupportedDcInputFormat::DcMixed => {
354            ctb_formats_dcstring::dc_mixed::dcmm_to_dcmstring_with_options(bytes, &dcmm_opts)?
355        }
356        SupportedDcInputFormat::DcMixed1 => {
357            ctb_formats_dcstring::dc_mixed::dcmm1_to_dcmstring_with_options(bytes, &dcmm_opts)?
358        }
359        SupportedDcInputFormat::DcMixed2 => {
360            ctb_formats_dcstring::dc_mixed::dcmm2_to_dcmstring_with_options(bytes, &dcmm_opts)?
361        }
362        SupportedDcInputFormat::DcTf => {
363            ctb_formats_dcstring::converters::utf8::dctf_to_dcmstring_with_options(
364                bytes,
365                options.permissive,
366            )?
367        }
368        SupportedDcInputFormat::DcUtf => {
369            ctb_formats_dcstring::converters::utf8::dcutf_to_dcmstring_with_options(
370                bytes,
371                options.permissive,
372            )?
373        }
374        SupportedDcInputFormat::Sems => {
375            ctb_formats_dcstring::converters::eite::sems_to_dcmstring_with_options(
376                bytes,
377                options.permissive,
378            )?
379        }
380        SupportedDcInputFormat::Ascii => {
381            ctb_formats_dcstring::converters::ascii::ascii_to_dcmstring_with_settings(
382                bytes,
383                &ctb_formats_dcstring::converters::ascii::AsciiSettings {
384                    strict_import: !options.permissive,
385                    ..Default::default()
386                },
387            )?
388        }
389        SupportedDcInputFormat::AsciiSafeSubset => {
390            ctb_formats_dcstring::converters::ascii::ascii_safe_subset_to_dcmstring_with_settings(
391                bytes,
392                &ctb_formats_dcstring::converters::ascii::AsciiSettings {
393                    strict_import: !options.permissive,
394                    ..Default::default()
395                },
396            )?
397        }
398        SupportedDcInputFormat::CscJournal => {
399            ctb_io_csc::journal::convert_cscjournal_to_dcmstring_with_options(
400                bytes,
401                &ctb_formats_dcstring::DcProjectionPolicy::forgiving(),
402                options.permissive,
403            )?
404        }
405        SupportedDcInputFormat::CscArchive => {
406            let policy = if options.permissive {
407                ctb_formats_dcstring::DcProjectionPolicy::forgiving()
408            } else {
409                ctb_formats_dcstring::DcProjectionPolicy::strict()
410            };
411            ctb_io_csc::journal::convert_cscarchive_to_dcmstring_with_policy(bytes, &policy)?
412        }
413        SupportedDcInputFormat::CscArchive1 => {
414            let policy = if options.permissive {
415                ctb_formats_dcstring::DcProjectionPolicy::forgiving()
416            } else {
417                ctb_formats_dcstring::DcProjectionPolicy::strict()
418            };
419            ctb_io_csc::journal::convert_cscarchive1_to_dcmstring_with_policy(bytes, &policy)?
420        }
421        SupportedDcInputFormat::CscArchive2 => {
422            let policy = if options.permissive {
423                ctb_formats_dcstring::DcProjectionPolicy::forgiving()
424            } else {
425                ctb_formats_dcstring::DcProjectionPolicy::strict()
426            };
427            ctb_io_csc::journal::convert_cscarchive2_to_dcmstring_with_policy(bytes, &policy)?
428        }
429        SupportedDcInputFormat::Cp437
430        | SupportedDcInputFormat::MacRoman
431        | SupportedDcInputFormat::Win1252
432        | SupportedDcInputFormat::Iso88591
433        | SupportedDcInputFormat::AlphaSmartNeo
434        | SupportedDcInputFormat::AlphaSmartNeoLowGrUs
435        | SupportedDcInputFormat::AlphaSmartNeoLowGrUaMac
436        | SupportedDcInputFormat::AlphaSmartNeoLowGrUaPc
437        | SupportedDcInputFormat::AlphaSmartNeoLowCtlUs
438        | SupportedDcInputFormat::AlphaSmartNeoLowCtlUaMac
439        | SupportedDcInputFormat::AlphaSmartNeoLowCtlUaPc => {
440            single_byte_encoding_to_dcmstring(resolved_format.to_format_id(), bytes)?
441        }
442        SupportedDcInputFormat::CdceLegacy
443        | SupportedDcInputFormat::CdceLegacyStrict
444        | SupportedDcInputFormat::DcIdList
445        | SupportedDcInputFormat::Dce
446        | SupportedDcInputFormat::DceHex
447        | SupportedDcInputFormat::Dce_3_0a
448        | SupportedDcInputFormat::Dce_3_0a_raw
449        | SupportedDcInputFormat::Dce_3_0a_hex
450        | SupportedDcInputFormat::Dce_3_0a_raw_hex
451        | SupportedDcInputFormat::Dce_3_01a
452        | SupportedDcInputFormat::Dce_3_01a_raw
453        | SupportedDcInputFormat::Dce_3_01a_hex
454        | SupportedDcInputFormat::Dce_3_01a_raw_hex
455        | SupportedDcInputFormat::Utf8_Dc64
456        | SupportedDcInputFormat::Utf8_Dc64_enc
457        | SupportedDcInputFormat::Utf8_Dc64_bin
458        | SupportedDcInputFormat::Utf8_Dc64_bin_hex
459        | SupportedDcInputFormat::Utf8_Dc64_bin_enc
460        | SupportedDcInputFormat::Utf8_Dc64_bin_enc_hex => {
461            ctb_formats_dceutils::document::dceutils_to_dcmstring_with_options(
462                bytes,
463                resolved_format.primary_cli_name(),
464                options.permissive,
465            )?
466        }
467    };
468
469    Ok(DcConversionResult {
470        document,
471        detected_format: resolved_format.to_format_id(),
472        log,
473    })
474}
475
476/// Converts a `DcMstring` document to serialized bytes in the specified output format.
477pub fn convert_dcmstring_to_bytes(
478    doc: &DcMstring,
479    format: SupportedDcOutputFormat,
480    options: &DcExportOptions,
481) -> Result<DcExportResult> {
482    let normalization = options.effective_normalization();
483    let mut pre_log = FormatLog::default();
484    let owned_transformed_doc;
485    let doc: &DcMstring = if !options.transformations.is_empty() {
486        let (tr_doc, tr_log) = ctb_formats_dcstring::apply_dc_transformations(
487            doc,
488            &options.transformations,
489        )?;
490        pre_log.merge(&tr_log);
491        owned_transformed_doc = tr_doc;
492        &owned_transformed_doc
493    } else {
494        doc
495    };
496    let owned_normalized_doc;
497    let doc: &DcMstring = if normalization == DcNormalizationMode::All
498        && !matches!(format, SupportedDcOutputFormat::Utf8)
499    {
500        let (norm_doc, norm_log) =
501            ctb_formats_dcstring::normalize_dcmstring_all(
502                doc,
503                options.permissive,
504            )?;
505        pre_log.merge(&norm_log);
506        owned_normalized_doc = norm_doc;
507        &owned_normalized_doc
508    } else {
509        doc
510    };
511
512    let (bytes, export_log) = match format {
513        SupportedDcOutputFormat::Utf8 => {
514            ctb_formats_dcstring::converters::utf8::dcmstring_to_utf8_with_normalization(
515                doc,
516                options.permissive,
517                normalization,
518            )?
519        }
520        SupportedDcOutputFormat::DcText => {
521            ctb_formats_dcstring::converters::dctext::dcmstring_to_dctext(doc)?
522        }
523        SupportedDcOutputFormat::Dcts => {
524            ctb_formats_dcstring::converters::dcts::dcmstring_to_dcts(doc)?
525        }
526        SupportedDcOutputFormat::Dcal => {
527            ctb_formats_dcstring::converters::dcal::dcmstring_to_dcal(doc)?
528        }
529        SupportedDcOutputFormat::Csdl => {
530            ctb_formats_dcstring::converters::dcal::dcmstring_to_csdl(doc)?
531        }
532        SupportedDcOutputFormat::Dcsh => {
533            ctb_formats_dcstring::converters::dcal::dcmstring_to_dcsh(doc)?
534        }
535        SupportedDcOutputFormat::CtbNodes => {
536            ctb_formats_dcstring::converters::dcal::dcmstring_to_ctbnodes(doc)?
537        }
538        SupportedDcOutputFormat::CtbNodeBundle => {
539            ctb_formats_dcstring::converters::dcal::dcmstring_to_ctbnbdl(doc)?
540        }
541        SupportedDcOutputFormat::CtbNodeBundle1 => {
542            ctb_formats_dcstring::converters::dcal::dcmstring_to_ctbnbdl1(doc)?
543        }
544        SupportedDcOutputFormat::CtbNodeBundle2 => {
545            ctb_formats_dcstring::converters::dcal::dcmstring_to_ctbnbdl2(doc)?
546        }
547        SupportedDcOutputFormat::DcIntegerList => {
548            ctb_formats_dcstring::converters::eite::dcmstring_to_dcil(doc)?
549        }
550        SupportedDcOutputFormat::Sems => {
551            ctb_formats_dcstring::converters::eite::dcmstring_to_sems(doc)?
552        }
553        SupportedDcOutputFormat::Html => {
554            ctb_formats_dcstring::converters::eite::dcmstring_to_html(doc)?
555        }
556        SupportedDcOutputFormat::HtmlFragment => {
557            ctb_formats_dcstring::converters::eite::dcmstring_to_html_fragment(doc)?
558        }
559        SupportedDcOutputFormat::EiteColorCoded => {
560            ctb_formats_dcstring::converters::eite::dcmstring_to_eite_colorcoded(doc)?
561        }
562        SupportedDcOutputFormat::DcMixed => {
563            ctb_formats_dcstring::dc_mixed::dcmstring_to_dcmm(doc)?
564        }
565        SupportedDcOutputFormat::DcMixed1 => {
566            ctb_formats_dcstring::dc_mixed::dcmstring_to_dcmm1(doc)?
567        }
568        SupportedDcOutputFormat::DcMixed2 => {
569            ctb_formats_dcstring::dc_mixed::dcmstring_to_dcmm2(doc)?
570        }
571        SupportedDcOutputFormat::DcTf => {
572            ctb_formats_dcstring::converters::utf8::dcmstring_to_dctf(doc)?
573        }
574        SupportedDcOutputFormat::DcUtf => {
575            ctb_formats_dcstring::converters::utf8::dcmstring_to_dcutf(doc)?
576        }
577        SupportedDcOutputFormat::Ascii => {
578            ctb_formats_dcstring::converters::ascii::dcmstring_to_ascii_with_settings(
579                doc,
580                &ctb_formats_dcstring::converters::ascii::AsciiSettings {
581                    strict_import: !options.permissive,
582                    normalization: Some(normalization),
583                    ..Default::default()
584                },
585            )?
586        }
587        SupportedDcOutputFormat::AsciiSafeSubset => {
588            ctb_formats_dcstring::converters::ascii::dcmstring_to_ascii_safe_subset_with_settings(
589                doc,
590                &ctb_formats_dcstring::converters::ascii::AsciiSettings {
591                    strict_import: !options.permissive,
592                    normalization: Some(normalization),
593                    ..Default::default()
594                },
595            )?
596        }
597        SupportedDcOutputFormat::CscJournal => {
598            ctb_io_csc::journal::dcmstring_to_cscjournal(doc)?
599        }
600        SupportedDcOutputFormat::CscArchive => {
601            ctb_io_csc::journal::dcmstring_to_cscarchive(doc)?
602        }
603        SupportedDcOutputFormat::CscArchive1 => {
604            ctb_io_csc::journal::dcmstring_to_cscarchive1(doc)?
605        }
606        SupportedDcOutputFormat::CscArchive2 => {
607            ctb_io_csc::journal::dcmstring_to_cscarchive2(doc)?
608        }
609        SupportedDcOutputFormat::Cp437
610        | SupportedDcOutputFormat::MacRoman
611        | SupportedDcOutputFormat::Win1252
612        | SupportedDcOutputFormat::Iso88591
613        | SupportedDcOutputFormat::AlphaSmartNeo
614        | SupportedDcOutputFormat::AlphaSmartNeoLowGrUs
615        | SupportedDcOutputFormat::AlphaSmartNeoLowGrUaMac
616        | SupportedDcOutputFormat::AlphaSmartNeoLowGrUaPc
617        | SupportedDcOutputFormat::AlphaSmartNeoLowCtlUs
618        | SupportedDcOutputFormat::AlphaSmartNeoLowCtlUaMac
619        | SupportedDcOutputFormat::AlphaSmartNeoLowCtlUaPc => {
620            dcmstring_to_single_byte_encoding(
621                format.to_format_id(),
622                doc,
623                options.permissive,
624                normalization,
625            )?
626        }
627        SupportedDcOutputFormat::CdceLegacy
628        | SupportedDcOutputFormat::DcIdList
629        | SupportedDcOutputFormat::Dce
630        | SupportedDcOutputFormat::DceHex
631        | SupportedDcOutputFormat::Dce_3_0a
632        | SupportedDcOutputFormat::Dce_3_0a_raw
633        | SupportedDcOutputFormat::Dce_3_0a_hex
634        | SupportedDcOutputFormat::Dce_3_0a_raw_hex
635        | SupportedDcOutputFormat::Dce_3_01a
636        | SupportedDcOutputFormat::Dce_3_01a_raw
637        | SupportedDcOutputFormat::Dce_3_01a_hex
638        | SupportedDcOutputFormat::Dce_3_01a_raw_hex
639        | SupportedDcOutputFormat::HtmlLegacyCdce
640        | SupportedDcOutputFormat::HtmlLegacyCdceSnippet
641        | SupportedDcOutputFormat::Utf8_Dc64
642        | SupportedDcOutputFormat::Utf8_Dc64_enc
643        | SupportedDcOutputFormat::Utf8_Dc64_bin
644        | SupportedDcOutputFormat::Utf8_Dc64_bin_hex
645        | SupportedDcOutputFormat::Utf8_Dc64_bin_enc
646        | SupportedDcOutputFormat::Utf8_Dc64_bin_enc_hex => {
647            ctb_formats_dceutils::document::dcmstr_to_dceutils_with_options(
648                doc,
649                format.primary_cli_name(),
650                options.permissive,
651            )?
652        }
653        SupportedDcOutputFormat::Elad => {
654            bail!("Export to format {format:?} is not yet implemented");
655        }
656    };
657
658    pre_log.merge(&export_log);
659
660    Ok(DcExportResult {
661        bytes,
662        target_format: format.to_format_id(),
663        log: pre_log,
664    })
665}
666
667/// Converts a file on disk (or '-' for stdin) to a `DcMstring`.
668pub fn convert_file_to_dcmstring(
669    path: &Path,
670    options: &DcConversionOptions,
671) -> Result<DcConversionResult> {
672    let (bytes, filename_hint) = if path == Path::new("-") {
673        let mut buf = Vec::new();
674        std::io::Read::read_to_end(&mut std::io::stdin(), &mut buf)
675            .context("Reading document from standard input")?;
676        (buf, None)
677    } else {
678        let data = std::fs::read(path).with_context(|| {
679            format!("Failed to read document file: {}", path.display())
680        })?;
681        let name = path.file_name().map(|n| n.to_string_lossy().into_owned());
682        (data, name)
683    };
684
685    convert_bytes_to_dcmstring(&bytes, filename_hint.as_deref(), options)
686}
687
688/// Exports a `DcMstring` to a file on disk (or '-' for stdout).
689pub fn convert_dcmstring_to_file(
690    doc: &DcMstring,
691    path: &Path,
692    format: SupportedDcOutputFormat,
693    options: &DcExportOptions,
694) -> Result<DcExportResult> {
695    let res = convert_dcmstring_to_bytes(doc, format, options)?;
696    if path == Path::new("-") {
697        std::io::Write::write_all(&mut std::io::stdout(), &res.bytes)
698            .context("Writing document to standard output")?;
699    } else {
700        std::fs::write(path, &res.bytes).with_context(|| {
701            format!("Failed to write document file: {}", path.display())
702        })?;
703    }
704    Ok(res)
705}
706
707#[cfg(test)]
708#[allow(
709    clippy::panic,
710    clippy::expect_used,
711    clippy::unwrap_used,
712    clippy::unwrap_in_result,
713    clippy::panic_in_result_fn,
714    clippy::indexing_slicing,
715    clippy::arithmetic_side_effects,
716    reason = "Standard repository test boilerplate"
717)]
718mod tests {
719    use super::*;
720
721    #[crate::ctb_test]
722    fn test_convert_legacy_dcs_without_upgrade() -> Result<()> {
723        let input = b"313 275 275 65 312 66 314 265 999";
724        let imported = convert_bytes_to_dcmstring(
725            input,
726            Some("legacy.dcil"),
727            &DcConversionOptions {
728                format: FormatSpec::Format(
729                    SupportedDcInputFormat::DcIntegerList,
730                ),
731                allow_binary_encapsulation: false,
732                ..Default::default()
733            },
734        )?;
735        let exported = convert_dcmstring_to_bytes(
736            &imported.document,
737            SupportedDcOutputFormat::DcUtf,
738            &DcExportOptions::default(),
739        )?;
740        let restored = convert_bytes_to_dcmstring(
741            &exported.bytes,
742            Some("legacy.dcutf"),
743            &DcConversionOptions {
744                format: FormatSpec::Format(SupportedDcInputFormat::DcUtf),
745                allow_binary_encapsulation: false,
746                ..Default::default()
747            },
748        )?;
749        let output = convert_dcmstring_to_bytes(
750            &restored.document,
751            SupportedDcOutputFormat::DcIntegerList,
752            &DcExportOptions::default(),
753        )?;
754        assert_eq!(
755            std::str::from_utf8(&output.bytes)?.trim(),
756            std::str::from_utf8(input)?
757        );
758        let mut checksummed = DcMstring::new();
759        checksummed
760            .push_binary_with_sha256(b"preserve metadata")
761            .unwrap();
762        let exported = convert_dcmstring_to_bytes(
763            &checksummed,
764            SupportedDcOutputFormat::DcUtf,
765            &DcExportOptions::default(),
766        )?;
767        let (restored, _) =
768            ctb_formats_dcstring::converters::utf8::dcutf_to_dcmstring(
769                &exported.bytes,
770            )?;
771        assert_eq!(restored.as_bytes(), checksummed.as_bytes());
772        let unchanged = convert_dcmstring_to_bytes(
773            &checksummed,
774            SupportedDcOutputFormat::DcMixed,
775            &DcExportOptions::default(),
776        )?;
777        assert_eq!(unchanged.bytes, checksummed.as_bytes());
778        Ok(())
779    }
780
781    #[crate::ctb_test]
782    fn test_convert_utf8_roundtrip() {
783        let input = b"Hello, world!";
784        let res = convert_bytes_to_dcmstring(
785            input,
786            Some("test.txt"),
787            &DcConversionOptions::default(),
788        )
789        .expect("convert utf8");
790        assert_eq!(res.detected_format, FormatId::Utf8);
791        assert_eq!(res.document, "Hello, world!");
792
793        let export = convert_dcmstring_to_bytes(
794            &res.document,
795            SupportedDcOutputFormat::Utf8,
796            &DcExportOptions::default(),
797        )
798        .expect("export utf8");
799        assert_eq!(export.bytes, input);
800    }
801
802    #[crate::ctb_test]
803    fn test_convert_single_byte_ascii_autodetect() {
804        let input = b"A";
805        let res = convert_bytes_to_dcmstring(
806            input,
807            None,
808            &DcConversionOptions::default(),
809        )
810        .expect("autodetect single byte ascii");
811        assert_eq!(res.detected_format, FormatId::Ascii);
812        assert_eq!(res.document, "A");
813    }
814
815    #[crate::ctb_test]
816    fn test_convert_dcal_roundtrip() {
817        let input = b"65 66 67 ";
818        let res = convert_bytes_to_dcmstring(
819            input,
820            Some("test.dcal"),
821            &DcConversionOptions::default(),
822        )
823        .expect("convert dcal");
824        assert_eq!(res.detected_format, FormatId::Dcal);
825        assert_eq!(res.document, "ABC");
826
827        let export = convert_dcmstring_to_bytes(
828            &res.document,
829            SupportedDcOutputFormat::Dcal,
830            &DcExportOptions::default(),
831        )
832        .expect("export dcal");
833        assert_eq!(export.bytes, input);
834    }
835
836    #[crate::ctb_test]
837    fn test_convert_dctext_roundtrip() {
838        let input = b"Hello @65@!";
839        let res = convert_bytes_to_dcmstring(
840            input,
841            Some("test.dctext"),
842            &DcConversionOptions::default(),
843        )
844        .expect("convert dctext");
845        assert_eq!(res.detected_format, FormatId::DcText);
846        assert_eq!(res.document, "Hello A!");
847
848        let export = convert_dcmstring_to_bytes(
849            &res.document,
850            SupportedDcOutputFormat::DcText,
851            &DcExportOptions::default(),
852        )
853        .expect("export dctext");
854        assert_eq!(std::str::from_utf8(&export.bytes).unwrap(), "Hello A!");
855
856        // Also test autodetection with NO filename hint
857        let res_no_hint = convert_bytes_to_dcmstring(
858            input,
859            None,
860            &DcConversionOptions::default(),
861        )
862        .expect("autodetect dctext without filename");
863        assert_eq!(res_no_hint.detected_format, FormatId::DcText);
864        assert_eq!(res_no_hint.document, "Hello A!");
865    }
866
867    #[crate::ctb_test]
868    fn test_convert_dcmm_roundtrip() {
869        let mut dcmm = DcMstring::new();
870        dcmm.push_str("Mixed document: ");
871        dcmm.push_binary(b"raw-bytes");
872        let bytes = dcmm.as_bytes();
873
874        let res = convert_bytes_to_dcmstring(
875            bytes,
876            Some("test.dcmm"),
877            &DcConversionOptions::default(),
878        )
879        .expect("convert dcmm");
880        assert_eq!(res.detected_format, FormatId::DcMixed2);
881        assert_eq!(res.document.as_bytes(), bytes);
882
883        let export = convert_dcmstring_to_bytes(
884            &res.document,
885            SupportedDcOutputFormat::DcMixed,
886            &DcExportOptions::default(),
887        )
888        .expect("export dcmm");
889        assert_eq!(export.bytes, bytes);
890    }
891
892    #[crate::ctb_test]
893    fn test_convert_ascii_roundtrip() {
894        let input = b"Hello, ASCII world!\n";
895        let res = convert_bytes_to_dcmstring(
896            input,
897            Some("test.txt"),
898            &DcConversionOptions {
899                format: FormatSpec::Format(SupportedDcInputFormat::Ascii),
900                allow_binary_encapsulation: false,
901                ..Default::default()
902            },
903        )
904        .expect("convert ascii");
905        assert_eq!(res.detected_format, FormatId::Ascii);
906        assert_eq!(res.document, "Hello, ASCII world!\n");
907
908        let export = convert_dcmstring_to_bytes(
909            &res.document,
910            SupportedDcOutputFormat::Ascii,
911            &DcExportOptions::default(),
912        )
913        .expect("export ascii");
914        assert_eq!(export.bytes, input);
915    }
916
917    #[crate::ctb_test]
918    fn test_convert_ascii_safe_subset_roundtrip() {
919        let input = b"Safe Line 1\r\nSafe Line 2\r\n";
920        let res = convert_bytes_to_dcmstring(
921            input,
922            Some("test.txt"),
923            &DcConversionOptions {
924                format: FormatSpec::Format(
925                    SupportedDcInputFormat::AsciiSafeSubset,
926                ),
927                allow_binary_encapsulation: false,
928                ..Default::default()
929            },
930        )
931        .expect("convert ascii safe subset");
932        assert_eq!(res.detected_format, FormatId::AsciiSafeSubset);
933        assert_eq!(res.document, "Safe Line 1\nSafe Line 2\n");
934
935        let export = convert_dcmstring_to_bytes(
936            &res.document,
937            SupportedDcOutputFormat::AsciiSafeSubset,
938            &DcExportOptions::default(),
939        )
940        .expect("export ascii safe subset");
941        assert_eq!(export.bytes, input);
942    }
943
944    #[crate::ctb_test]
945    fn test_convert_cscjournal_fixtures_to_dcmstring() {
946        let manifest_dir = env!("CARGO_MANIFEST_DIR");
947        let fixtures_dir = std::path::Path::new(manifest_dir)
948            .join("../../io/csc/fixtures/journals");
949
950        // Verify list_supported_input_formats includes CscJournal
951        let supported = crate::convert_api::list_supported_input_formats();
952        assert!(
953            supported.contains(&FormatId::CscJournal),
954            "Supported input formats must include CscJournal"
955        );
956
957        for (filename, is_legacy) in [
958            ("v1_ctbmeta1-20261011.cscjournal", true),
959            ("v2_ctbmeta2-20261011.cscjournal", true),
960            ("v3_ctbmeta3-20261011.cscjournal", true),
961            ("v4_dcmixed-20261011.cscjournal", false),
962        ] {
963            let path = fixtures_dir.join(filename);
964            let bytes = std::fs::read(&path).expect("read journal fixture");
965
966            // 1. Explicit format specification
967            let res_explicit = convert_bytes_to_dcmstring(
968                &bytes,
969                Some(filename),
970                &DcConversionOptions {
971                    format: FormatSpec::Format(
972                        SupportedDcInputFormat::CscJournal,
973                    ),
974                    allow_binary_encapsulation: false,
975                    ..Default::default()
976                },
977            )
978            .expect("convert cscjournal explicit");
979            assert_eq!(res_explicit.detected_format, FormatId::CscJournal);
980            assert!(
981                res_explicit.document.len()
982                    > ctb_formats_dcstring::DCMM_HEADER_LEN,
983                "{filename}: DcMstring must contain payload beyond 21-byte header"
984            );
985
986            // 2. FormatId specification
987            let res_fid = convert_bytes_to_dcmstring(
988                &bytes,
989                None,
990                &DcConversionOptions {
991                    format: FormatSpec::FormatId(if is_legacy {
992                        FormatId::CscJournal1Meta1
993                    } else {
994                        FormatId::CscJournal4
995                    }),
996                    allow_binary_encapsulation: false,
997                    ..Default::default()
998                },
999            )
1000            .expect("convert cscjournal by FormatId");
1001            assert_eq!(res_fid.detected_format, FormatId::CscJournal);
1002            assert!(
1003                res_fid.document.len() > ctb_formats_dcstring::DCMM_HEADER_LEN
1004            );
1005
1006            // 3. Autodetection with filename hint
1007            let res_auto_hint = convert_bytes_to_dcmstring(
1008                &bytes,
1009                Some(filename),
1010                &DcConversionOptions::default(),
1011            )
1012            .expect("autodetect cscjournal with filename");
1013            assert_eq!(res_auto_hint.detected_format, FormatId::CscJournal);
1014            assert!(
1015                res_auto_hint.document.len()
1016                    > ctb_formats_dcstring::DCMM_HEADER_LEN
1017            );
1018
1019            // 4. Autodetection from magic bytes alone (no filename hint)
1020            let res_auto_magic = convert_bytes_to_dcmstring(
1021                &bytes,
1022                None,
1023                &DcConversionOptions::default(),
1024            )
1025            .expect("autodetect cscjournal from magic alone");
1026            assert_eq!(res_auto_magic.detected_format, FormatId::CscJournal);
1027            assert!(
1028                res_auto_magic.document.len()
1029                    > ctb_formats_dcstring::DCMM_HEADER_LEN
1030            );
1031
1032            // 5. File conversion API (convert_file_to_dcmstring)
1033            let res_file = convert_file_to_dcmstring(
1034                &path,
1035                &DcConversionOptions::default(),
1036            )
1037            .expect("convert file cscjournal");
1038            assert_eq!(res_file.detected_format, FormatId::CscJournal);
1039            assert_eq!(
1040                res_file.document.as_bytes(),
1041                res_explicit.document.as_bytes()
1042            );
1043        }
1044    }
1045
1046    #[crate::ctb_test]
1047    fn test_convert_ctbnodes_and_ctbnbdl_parity() {
1048        let ctbnodes_input = b"# Sample nodes\nl8589934592: 586 615 581 # Is an instance of\nl8589934593: u4c u61 u74 u69 u6e # Latin\n";
1049        let nodes_res = convert_bytes_to_dcmstring(
1050            ctbnodes_input,
1051            Some("test.ctbnodes"),
1052            &DcConversionOptions::default(),
1053        )
1054        .expect("convert .ctbnodes");
1055        assert_eq!(nodes_res.detected_format, FormatId::CtbNodes);
1056
1057        let bdl_export = convert_dcmstring_to_bytes(
1058            &nodes_res.document,
1059            SupportedDcOutputFormat::CtbNodeBundle,
1060            &DcExportOptions::default(),
1061        )
1062        .expect("export .ctbnbdl");
1063        assert!(bdl_export.bytes.starts_with(b"CTBNBDL\x02"));
1064
1065        let bdl_res = convert_bytes_to_dcmstring(
1066            &bdl_export.bytes,
1067            Some("test.ctbnbdl"),
1068            &DcConversionOptions::default(),
1069        )
1070        .expect("convert .ctbnbdl");
1071        assert_eq!(bdl_res.document.as_bytes(), nodes_res.document.as_bytes());
1072
1073        let nodes_export = convert_dcmstring_to_bytes(
1074            &bdl_res.document,
1075            SupportedDcOutputFormat::CtbNodes,
1076            &DcExportOptions::default(),
1077        )
1078        .expect("export .ctbnodes");
1079        let reimported = convert_bytes_to_dcmstring(
1080            &nodes_export.bytes,
1081            Some("roundtrip.ctbnodes"),
1082            &DcConversionOptions::default(),
1083        )
1084        .expect("reimport .ctbnodes");
1085        assert_eq!(
1086            reimported.document.as_bytes(),
1087            nodes_res.document.as_bytes()
1088        );
1089    }
1090
1091    #[crate::ctb_test]
1092    fn test_permissive_dcmm_with_leading_asset_bundle_junk() {
1093        // Construct a synthetic asset bundle wrapper (CTBRSRC\0...) followed by CTBNBDL\x02 and a valid DcMixed2 document.
1094        let mut inner_doc = DcMstring::new();
1095        inner_doc.push_char(ctb_formats_dcstring::DcChar(1_114_729)); // Dc 617
1096        inner_doc.push_str("test node payload");
1097        inner_doc.push_char(ctb_formats_dcstring::DcChar(1_114_730)); // Dc 618
1098
1099        let mut wrapped = b"CTBRSRC\x00\x04\x00\x00\x00data/graph/system/85899_34942.ctbnbdlCTBNBDL\x02".to_vec();
1100        wrapped.extend_from_slice(inner_doc.as_bytes());
1101
1102        // Strict mode must reject the invalid DcMixed magic header
1103        let strict_err = convert_bytes_to_dcmstring(
1104            &wrapped,
1105            Some("system_graph_history.rsrc"),
1106            &DcConversionOptions {
1107                format: FormatSpec::Format(SupportedDcInputFormat::DcMixed),
1108                allow_binary_encapsulation: false,
1109                permissive: false,
1110            },
1111        )
1112        .unwrap_err();
1113        assert!(
1114            format!("{strict_err:#}").contains("Invalid DcMixed magic header")
1115        );
1116
1117        // Permissive mode must recover the embedded DcMixed2 document with warnings
1118        let permissive_res = convert_bytes_to_dcmstring(
1119            &wrapped,
1120            Some("system_graph_history.rsrc"),
1121            &DcConversionOptions {
1122                format: FormatSpec::Format(SupportedDcInputFormat::DcMixed),
1123                allow_binary_encapsulation: false,
1124                permissive: true,
1125            },
1126        )
1127        .expect("permissive dcmm decode");
1128        assert!(permissive_res.log.has_warnings());
1129        let dclist =
1130            permissive_res.document.to_dc_string().unwrap().to_dclist();
1131        assert!(
1132            dclist.contains(&1_114_729) && dclist.contains(&1_114_730),
1133            "Decoded dclist must contain the embedded Dc 617 .. Dc 618 statements"
1134        );
1135    }
1136
1137    #[crate::ctb_test]
1138    fn test_convert_csdl_dcsh_cscarchive_and_encodings() {
1139        // 1. Csdl roundtrip
1140        let csdl_in = b"65, 1114408, 2228304";
1141        let csdl_res = convert_bytes_to_dcmstring(
1142            csdl_in,
1143            Some("test.csdl"),
1144            &DcConversionOptions {
1145                format: FormatSpec::Format(SupportedDcInputFormat::Csdl),
1146                ..Default::default()
1147            },
1148        )
1149        .expect("csdl import");
1150        let csdl_out = convert_dcmstring_to_bytes(
1151            &csdl_res.document,
1152            SupportedDcOutputFormat::Csdl,
1153            &DcExportOptions::default(),
1154        )
1155        .expect("csdl export");
1156        assert_eq!(csdl_out.bytes, b"65,1114408,2228304");
1157
1158        // 2. Dcsh roundtrip
1159        let dcsh_in = b"u41 296 f80";
1160        let dcsh_res = convert_bytes_to_dcmstring(
1161            dcsh_in,
1162            Some("test.dcsh"),
1163            &DcConversionOptions {
1164                format: FormatSpec::Format(SupportedDcInputFormat::Dcsh),
1165                ..Default::default()
1166            },
1167        )
1168        .expect("dcsh import");
1169        assert_eq!(dcsh_res.document.as_bytes(), csdl_res.document.as_bytes());
1170        let dcsh_out = convert_dcmstring_to_bytes(
1171            &dcsh_res.document,
1172            SupportedDcOutputFormat::Dcsh,
1173            &DcExportOptions::default(),
1174        )
1175        .expect("dcsh export");
1176        assert_eq!(dcsh_out.bytes, dcsh_in);
1177
1178        // 2b. CtbNodeIncoming autodetection and import (strict and permissive)
1179        let incoming_in = b"# @provenance: manual\n# @rationale: Manual incoming node fixture\n# @comment: Sample node\nu41 296 f80 # inline comment\n";
1180        let incoming_res = convert_bytes_to_dcmstring(
1181            incoming_in,
1182            Some("001_sample.ctbnode-incoming"),
1183            &DcConversionOptions::default(),
1184        )
1185        .expect("ctbnode-incoming autodetect import");
1186        assert_eq!(incoming_res.detected_format, FormatId::CtbNodeIncoming);
1187        assert_eq!(
1188            incoming_res.document.as_bytes(),
1189            dcsh_res.document.as_bytes()
1190        );
1191
1192        // Strict CtbNodeIncoming rejects missing # @provenance header, while permissive mode recovers tokens
1193        let missing_prov = b"# @comment: Missing provenance\nu41 296 f80\n";
1194        convert_bytes_to_dcmstring(
1195            missing_prov,
1196            Some("bad.ctbnode-incoming"),
1197            &DcConversionOptions {
1198                format: FormatSpec::Format(
1199                    SupportedDcInputFormat::CtbNodeIncoming,
1200                ),
1201                permissive: false,
1202                ..Default::default()
1203            },
1204        )
1205        .unwrap_err();
1206        let perm_incoming = convert_bytes_to_dcmstring(
1207            missing_prov,
1208            Some("bad.ctbnode-incoming"),
1209            &DcConversionOptions {
1210                format: FormatSpec::Format(
1211                    SupportedDcInputFormat::CtbNodeIncoming,
1212                ),
1213                permissive: true,
1214                ..Default::default()
1215            },
1216        )
1217        .expect("permissive ctbnode-incoming import");
1218        assert!(perm_incoming.log.has_warnings());
1219        assert_eq!(
1220            perm_incoming.document.as_bytes(),
1221            dcsh_res.document.as_bytes()
1222        );
1223
1224        // 3. CscArchive roundtrip
1225        let arch_out = convert_dcmstring_to_bytes(
1226            &dcsh_res.document,
1227            SupportedDcOutputFormat::CscArchive,
1228            &DcExportOptions::default(),
1229        )
1230        .expect("cscarchive export");
1231        assert!(arch_out.bytes.starts_with(b"CTBCSCA\x02"));
1232        let arch_in = convert_bytes_to_dcmstring(
1233            &arch_out.bytes,
1234            Some("test.cscarchive"),
1235            &DcConversionOptions::default(),
1236        )
1237        .expect("cscarchive autodetect import");
1238        assert_eq!(arch_in.document.as_bytes(), dcsh_res.document.as_bytes());
1239
1240        // 4. MacRoman single-byte encoding roundtrip
1241        let mut text_doc = DcMstring::new();
1242        text_doc.push_str("caf\u{e9}");
1243        let mac_out = convert_dcmstring_to_bytes(
1244            &text_doc,
1245            SupportedDcOutputFormat::MacRoman,
1246            &DcExportOptions::default(),
1247        )
1248        .expect("macroman export");
1249        assert_eq!(mac_out.bytes, vec![99, 97, 102, 142]);
1250        let mac_in = convert_bytes_to_dcmstring(
1251            &mac_out.bytes,
1252            None,
1253            &DcConversionOptions {
1254                format: FormatSpec::Format(SupportedDcInputFormat::MacRoman),
1255                ..Default::default()
1256            },
1257        )
1258        .expect("macroman import");
1259        assert_eq!(mac_in.document, "caf\u{e9}");
1260    }
1261
1262    #[crate::ctb_test]
1263    fn test_convert_dceutils_legacy_cdce_and_control_preservation() {
1264        let mut text_doc = DcMstring::new();
1265        for short_id in [57, 86, 93, 93, 96, 119] {
1266            text_doc
1267                .push_char(ctb_formats_dcstring::DcChar::from_short(short_id));
1268        }
1269        let text_strict = convert_dcmstring_to_bytes(
1270            &text_doc,
1271            SupportedDcOutputFormat::Utf8,
1272            &DcExportOptions::default(),
1273        )
1274        .unwrap();
1275        assert_eq!(
1276            text_strict.bytes,
1277            "\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}".as_bytes()
1278        );
1279        assert!(text_strict.log.has_errors());
1280        assert!(!text_strict.log.has_warnings());
1281
1282        let text_no_norm = convert_dcmstring_to_bytes(
1283            &text_doc,
1284            SupportedDcOutputFormat::Utf8,
1285            &DcExportOptions {
1286                format: SupportedDcOutputFormat::Utf8,
1287                permissive: true,
1288                normalization: Some(DcNormalizationMode::None),
1289                ..Default::default()
1290            },
1291        )
1292        .unwrap();
1293        assert_eq!(
1294            text_no_norm.bytes,
1295            "\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}".as_bytes()
1296        );
1297        assert!(text_no_norm.log.has_warnings());
1298        assert!(!text_no_norm.log.has_errors());
1299
1300        let text = convert_dcmstring_to_bytes(
1301            &text_doc,
1302            SupportedDcOutputFormat::Utf8,
1303            &DcExportOptions {
1304                format: SupportedDcOutputFormat::Utf8,
1305                permissive: true,
1306                ..Default::default()
1307            },
1308        )
1309        .unwrap();
1310        assert_eq!(text.bytes, "Hello\u{85}".as_bytes());
1311        assert!(text.log.has_warnings());
1312        let wire = convert_dcmstring_to_bytes(
1313            &text_doc,
1314            SupportedDcOutputFormat::Dce_3_01a,
1315            &DcExportOptions::default(),
1316        )
1317        .unwrap();
1318        let imported = convert_bytes_to_dcmstring(
1319            &wire.bytes,
1320            None,
1321            &DcConversionOptions::default(),
1322        )
1323        .unwrap();
1324        let text = convert_dcmstring_to_bytes(
1325            &imported.document,
1326            SupportedDcOutputFormat::Utf8,
1327            &DcExportOptions {
1328                format: SupportedDcOutputFormat::Utf8,
1329                permissive: true,
1330                ..Default::default()
1331            },
1332        )
1333        .unwrap();
1334        assert_eq!(text.bytes, "Hello\u{85}".as_bytes());
1335        assert!(text.log.has_warnings());
1336        let markup = DcMstring::from("<b>literal</b>&amp;\u{e9}");
1337        for output in [
1338            SupportedDcOutputFormat::Html,
1339            SupportedDcOutputFormat::HtmlFragment,
1340        ] {
1341            let html = convert_dcmstring_to_bytes(
1342                &markup,
1343                output,
1344                &DcExportOptions::default(),
1345            )
1346            .unwrap();
1347            assert!(!html.log.has_warnings());
1348            let html = String::from_utf8(html.bytes).unwrap();
1349            assert!(html.contains("&lt;b&gt;literal&lt;/b&gt;&amp;amp;\u{e9}"));
1350            assert!(
1351                !html.starts_with("<!DOCTYPE")
1352                    || html.contains("charset=\"utf-8\"")
1353            );
1354        }
1355        // 1. Autodetect and roundtrip all valid Weave .legacy_cdce fixtures
1356        let fixtures: &[(&str, &[u8])] = &[
1357            (
1358                "datetime_string.legacy_cdce",
1359                include_bytes!("../weave/fixtures/datetime_string.legacy_cdce"),
1360            ),
1361            (
1362                "dce_number_format.legacy_cdce",
1363                include_bytes!(
1364                    "../weave/fixtures/dce_number_format.legacy_cdce"
1365                ),
1366            ),
1367            (
1368                "dce_separator_level_1.legacy_cdce",
1369                include_bytes!(
1370                    "../weave/fixtures/dce_separator_level_1.legacy_cdce"
1371                ),
1372            ),
1373            (
1374                "dce_separator_level_2.legacy_cdce",
1375                include_bytes!(
1376                    "../weave/fixtures/dce_separator_level_2.legacy_cdce"
1377                ),
1378            ),
1379        ];
1380
1381        for &(filename, raw_bytes) in fixtures {
1382            let imported = convert_bytes_to_dcmstring(
1383                raw_bytes,
1384                Some(filename),
1385                &DcConversionOptions::default(),
1386            )
1387            .expect("autodetect and import .legacy_cdce fixture");
1388            assert_eq!(imported.detected_format, FormatId::CdceLegacy);
1389            assert!(!imported.log.has_errors());
1390            assert!(!imported.log.has_warnings());
1391
1392            let exported = convert_dcmstring_to_bytes(
1393                &imported.document,
1394                SupportedDcOutputFormat::CdceLegacy,
1395                &DcExportOptions::default(),
1396            )
1397            .expect("export back to .legacy_cdce");
1398            assert!(!exported.log.has_errors());
1399            assert!(!exported.log.has_warnings());
1400            assert_eq!(
1401                exported.bytes, raw_bytes,
1402                "roundtrip mismatch for {filename}"
1403            );
1404        }
1405
1406        // 2. Convert datetime_string.legacy_cdce -> DCE 3.01a -> DcMstring -> legacy_cdce
1407        // Verify body encoding controls are preserved in DcMstring, ignored when exporting to legacy_cdce,
1408        // and roundtrip back to DCE 3.01a.
1409        let dt_bytes =
1410            include_bytes!("../weave/fixtures/datetime_string.legacy_cdce");
1411        let dt_doc = convert_bytes_to_dcmstring(
1412            dt_bytes,
1413            Some("datetime_string.legacy_cdce"),
1414            &DcConversionOptions::default(),
1415        )
1416        .expect("import datetime_string.legacy_cdce");
1417
1418        let dce_301a = convert_dcmstring_to_bytes(
1419            &dt_doc.document,
1420            SupportedDcOutputFormat::Dce_3_01a,
1421            &DcExportOptions::default(),
1422        )
1423        .expect("export to DCE 3.01a");
1424        assert!(dce_301a.bytes.starts_with(b"DCEe\x02\x01\x02\xfd"));
1425        assert!(!dce_301a.log.has_warnings());
1426
1427        // Autodetect DCE 3.01a from magic bytes and import into DcMstring preserving control Dcs
1428        let from_301a = convert_bytes_to_dcmstring(
1429            &dce_301a.bytes,
1430            None,
1431            &DcConversionOptions::default(),
1432        )
1433        .expect("autodetect and import DCE 3.01a");
1434        assert_eq!(from_301a.detected_format, FormatId::Dce_3_01a);
1435
1436        let dclist = from_301a.document.to_dc_string().unwrap().to_dclist();
1437        let short_start = ctb_formats_dcdata::dc::SHORT_DC_REGION_START;
1438        // Must preserve body framing and sheet switches, excluding the file envelope.
1439        for ctrl_short in [13_u128, 114, 197, 115] {
1440            assert!(
1441                dclist.contains(&short_start.saturating_add(ctrl_short)),
1442                "DcMstring imported from DCE 3.01a must preserve control Dc {ctrl_short}"
1443            );
1444        }
1445
1446        // Exporting DcMstring (with preserved DCE control Dcs) to legacy_cdce ignores control Dcs
1447        let cdce_from_301a = convert_dcmstring_to_bytes(
1448            &from_301a.document,
1449            SupportedDcOutputFormat::CdceLegacy,
1450            &DcExportOptions::default(),
1451        )
1452        .expect("export DCE 3.01a DcMstring to legacy_cdce");
1453        assert_eq!(cdce_from_301a.bytes, dt_bytes);
1454
1455        // Exporting DcMstring (with preserved DCE control Dcs) back to DCE 3.01a roundtrips identically
1456        let reencoded_301a = convert_dcmstring_to_bytes(
1457            &from_301a.document,
1458            SupportedDcOutputFormat::Dce_3_01a,
1459            &DcExportOptions::default(),
1460        )
1461        .expect("re-export DCE 3.01a DcMstring to DCE 3.01a");
1462        assert_eq!(reencoded_301a.bytes, dce_301a.bytes);
1463
1464        // 3. Verify unrepresentable Dcs (such as long Dcs and short Dcs > 12 in CdceLegacy)
1465        // emit errors in strict mode and warnings in permissive mode because dceutils formats do not support Dc 308.
1466        let mut unmappable_doc = DcMstring::new();
1467        unmappable_doc.push_str("A");
1468        unmappable_doc.push_char(ctb_formats_dcstring::DcChar(1_114_420)); // short Dc 308 -> U+FFFD
1469        unmappable_doc.push_char(ctb_formats_dcstring::DcChar(3_000_000)); // long Dc -> U+FFFD
1470        let strict_export = convert_dcmstring_to_bytes(
1471            &unmappable_doc,
1472            SupportedDcOutputFormat::CdceLegacy,
1473            &DcExportOptions::default(),
1474        )
1475        .expect("export in strict mode");
1476        assert_eq!(strict_export.bytes, b"A\xef\xbf\xbd\xef\xbf\xbd");
1477        assert!(strict_export.log.has_errors());
1478        assert!(
1479            strict_export.log.get_errors().len() >= 2,
1480            "Expected errors for unmappable short Dc 308 and long Dc 3000000 in strict mode"
1481        );
1482
1483        let warn_export = convert_dcmstring_to_bytes(
1484            &unmappable_doc,
1485            SupportedDcOutputFormat::CdceLegacy,
1486            &DcExportOptions {
1487                format: SupportedDcOutputFormat::CdceLegacy,
1488                permissive: true,
1489                ..Default::default()
1490            },
1491        )
1492        .expect("export with warnings in permissive mode");
1493        assert_eq!(warn_export.bytes, b"A\xef\xbf\xbd\xef\xbf\xbd");
1494        assert!(warn_export.log.has_warnings());
1495        assert!(
1496            warn_export.log.get_warnings().len() >= 2,
1497            "Expected warnings for unmappable short Dc 308 and long Dc 3000000"
1498        );
1499
1500        // 4. Verify all mapped short Dcs in DCE 3.0a (0, 1, 13..=115; 2..=12 logged as unmappable),
1501        // 0..=199 in DCE 3.01a, and 0..=202 in DCE 3.02a roundtrip losslessly via DcMstring.
1502        for short_id in 0..=115_u32 {
1503            let mut doc = DcMstring::new();
1504            doc.push_char(ctb_formats_dcstring::DcChar::from_short(short_id));
1505            let exported = convert_dcmstring_to_bytes(
1506                &doc,
1507                SupportedDcOutputFormat::Dce_3_0a,
1508                &DcExportOptions::default(),
1509            );
1510            if short_id == 113 {
1511                assert!(exported.is_err());
1512                continue;
1513            }
1514            let exported = exported.expect("export 0..=115 to Dce_3_0a");
1515            if (2..=12).contains(&short_id) {
1516                assert!(
1517                    !exported.log.has_errors() && exported.log.has_warnings(),
1518                    "Dce_3_0a export of unmapped short Dc {short_id} should emit a warning: {:?}",
1519                    exported.log
1520                );
1521                continue;
1522            }
1523            assert!(
1524                !exported.log.has_errors() && !exported.log.has_warnings(),
1525                "Dce_3_0a export of short Dc {short_id} emitted warnings/errors: {:?}",
1526                exported.log
1527            );
1528            let reimported = convert_bytes_to_dcmstring(
1529                &exported.bytes,
1530                None,
1531                &DcConversionOptions::default(),
1532            )
1533            .expect("reimport Dce_3_0a");
1534            let dcs = reimported.document.to_dc_string().unwrap().to_dclist();
1535            assert!(
1536                dcs.contains(&short_start.saturating_add(u128::from(short_id))),
1537                "Dce_3_0a reimported DcMstring missing short Dc {short_id}"
1538            );
1539        }
1540
1541        for short_id in 0..=199_u32 {
1542            let mut doc = DcMstring::new();
1543            doc.push_char(ctb_formats_dcstring::DcChar::from_short(short_id));
1544            let exported = convert_dcmstring_to_bytes(
1545                &doc,
1546                SupportedDcOutputFormat::Dce_3_01a,
1547                &DcExportOptions::default(),
1548            );
1549            if short_id == 113 {
1550                assert!(exported.is_err());
1551                continue;
1552            }
1553            let exported = exported.expect("export 0..=199 to Dce_3_01a");
1554            assert!(
1555                !exported.log.has_errors() && !exported.log.has_warnings(),
1556                "Dce_3_01a export of short Dc {short_id} emitted warnings/errors: {:?}",
1557                exported.log
1558            );
1559            let reimported = convert_bytes_to_dcmstring(
1560                &exported.bytes,
1561                None,
1562                &DcConversionOptions::default(),
1563            );
1564            let resolver =
1565                ctb_formats_dcdata::syntax::default_syntax_resolver();
1566            if ctb_formats_dcdata::syntax::SyntaxRuleResolver::token_fills_role(
1567                resolver.as_ref(),
1568                ctb_formats_dcstring::DcChar::from_short(short_id).to_u128(),
1569                ctb_formats_dcdata::syntax::DcRole::StartEncapsulationUtf8,
1570            ) {
1571                assert!(reimported.is_err());
1572                let repaired = convert_bytes_to_dcmstring(
1573                    &exported.bytes,
1574                    None,
1575                    &DcConversionOptions {
1576                        permissive: true,
1577                        ..DcConversionOptions::default()
1578                    },
1579                )
1580                .expect("repair unterminated UTF-8 encapsulation");
1581                assert!(repaired.log.has_warnings());
1582                assert!(
1583                    repaired
1584                        .document
1585                        .to_dc_string()
1586                        .unwrap()
1587                        .to_dclist()
1588                        .contains(&u128::from('\u{FFFD}'),)
1589                );
1590                continue;
1591            }
1592            let reimported = reimported.expect("reimport Dce_3_01a");
1593            let dcs = reimported.document.to_dc_string().unwrap().to_dclist();
1594            assert!(
1595                dcs.contains(&short_start.saturating_add(u128::from(short_id))),
1596                "Dce_3_01a reimported DcMstring missing short Dc {short_id}"
1597            );
1598        }
1599    }
1600
1601    #[crate::ctb_test]
1602    fn test_normalization_modes_across_formats() {
1603        // Document containing:
1604        // - decomposed Unicode "cafe\u{0301}"
1605        // - deprecated short Dc 57 ('H', <equiv>u48)
1606        // - deprecated short Dc 265 (<prefer>307)
1607        let mut doc = DcMstring::from("cafe\u{0301}");
1608        doc.push_char(ctb_formats_dcstring::DcChar::from_short(57));
1609        doc.push_char(ctb_formats_dcstring::DcChar::from_short(265));
1610
1611        // 1. Export to Dcal (which can represent all Dcs and Unicode codepoints as-is):
1612        // - RequiredByTarget (default in permissive mode): preserves decomposed Unicode and deprecated Dcs as-is
1613        let dcal_req = convert_dcmstring_to_bytes(
1614            &doc,
1615            SupportedDcOutputFormat::Dcal,
1616            &DcExportOptions {
1617                format: SupportedDcOutputFormat::Dcal,
1618                permissive: true,
1619                normalization: Some(DcNormalizationMode::RequiredByTarget),
1620                ..Default::default()
1621            },
1622        )
1623        .unwrap();
1624        assert_eq!(
1625            String::from_utf8(dcal_req.bytes).unwrap(),
1626            "99 97 102 101 769 1114169 1114377 "
1627        );
1628        assert!(!dcal_req.log.has_warnings() && !dcal_req.log.has_errors());
1629
1630        // - All: normalizes "cafe\u{0301}" -> "caf\u{00E9}" (233), short Dc 57 -> 'H' (72), and short Dc 265 -> short Dc 307 (1114419)
1631        let dcal_all = convert_dcmstring_to_bytes(
1632            &doc,
1633            SupportedDcOutputFormat::Dcal,
1634            &DcExportOptions {
1635                format: SupportedDcOutputFormat::Dcal,
1636                permissive: true,
1637                normalization: Some(DcNormalizationMode::All),
1638                ..Default::default()
1639            },
1640        )
1641        .unwrap();
1642        assert_eq!(
1643            String::from_utf8(dcal_all.bytes).unwrap(),
1644            "99 97 102 233 72 1114419 "
1645        );
1646        assert!(dcal_all.log.has_warnings() && !dcal_all.log.has_errors());
1647
1648        // 2. Export decomposed Unicode "cafe\u{0301}" to MacRoman:
1649        let decomp_doc = DcMstring::from("cafe\u{0301}");
1650        // - None: does not normalize, fails because U+0301 is not representable in MacRoman
1651        assert!(
1652            convert_dcmstring_to_bytes(
1653                &decomp_doc,
1654                SupportedDcOutputFormat::MacRoman,
1655                &DcExportOptions {
1656                    format: SupportedDcOutputFormat::MacRoman,
1657                    permissive: true,
1658                    normalization: Some(DcNormalizationMode::None),
1659                    ..Default::default()
1660                },
1661            )
1662            .is_err()
1663        );
1664        // - RequiredByTarget (default in permissive mode): normalizes to NFC on demand so MacRoman can represent 'é'
1665        let mac_req = convert_dcmstring_to_bytes(
1666            &decomp_doc,
1667            SupportedDcOutputFormat::MacRoman,
1668            &DcExportOptions {
1669                format: SupportedDcOutputFormat::MacRoman,
1670                permissive: true,
1671                ..Default::default()
1672            },
1673        )
1674        .unwrap();
1675        assert_eq!(mac_req.bytes, vec![99, 97, 102, 142]);
1676        assert!(mac_req.log.has_warnings() && !mac_req.log.has_errors());
1677    }
1678
1679    #[crate::ctb_test]
1680    fn test_unicode_to_short_dc_transformation_in_sems() {
1681        let imported = convert_bytes_to_dcmstring(
1682            b"AB",
1683            None,
1684            &DcConversionOptions {
1685                format: FormatSpec::Format(SupportedDcInputFormat::Ascii),
1686                ..Default::default()
1687            },
1688        )
1689        .unwrap();
1690
1691        // Without transformation: 'A' (65) and 'B' (66) are exported to SEMS via Dc 308
1692        let sems_default = convert_dcmstring_to_bytes(
1693            &imported.document,
1694            SupportedDcOutputFormat::Sems,
1695            &DcExportOptions::default(),
1696        )
1697        .unwrap();
1698        assert_eq!(
1699            String::from_utf8(sems_default.bytes.clone())
1700                .unwrap()
1701                .trim(),
1702            "308 6 199 128 128 7 308 6 199 128 129 7"
1703        );
1704        assert!(!sems_default.log.has_warnings());
1705
1706        // With UnicodeToShortDc transformation: 'A' -> Dc 50, 'B' -> Dc 51 with warnings
1707        let sems_transformed = convert_dcmstring_to_bytes(
1708            &imported.document,
1709            SupportedDcOutputFormat::Sems,
1710            &DcExportOptions {
1711                format: SupportedDcOutputFormat::Sems,
1712                transformations: vec![
1713                    SupportedDcTransformation::UnicodeToShortDc,
1714                ],
1715                ..Default::default()
1716            },
1717        )
1718        .unwrap();
1719        assert_eq!(
1720            String::from_utf8(sems_transformed.bytes.clone())
1721                .unwrap()
1722                .trim(),
1723            "50 51"
1724        );
1725        assert_eq!(sems_transformed.log.get_warnings().len(), 2);
1726        assert!(sems_transformed.log.get_warnings()[0].contains("short Dc 50"));
1727        assert!(sems_transformed.log.get_warnings()[1].contains("short Dc 51"));
1728
1729        // Re-importing the default SEMS and exporting to ASCII without normalization roundtrips losslessly
1730        let reimported_default = convert_bytes_to_dcmstring(
1731            &sems_default.bytes,
1732            None,
1733            &DcConversionOptions {
1734                format: FormatSpec::Format(SupportedDcInputFormat::Sems),
1735                ..Default::default()
1736            },
1737        )
1738        .unwrap();
1739        let ascii_default_out = convert_dcmstring_to_bytes(
1740            &reimported_default.document,
1741            SupportedDcOutputFormat::Ascii,
1742            &DcExportOptions::default(),
1743        )
1744        .unwrap();
1745        assert_eq!(ascii_default_out.bytes, b"AB");
1746
1747        // Re-importing the transformed SEMS yields short Dcs 50 and 51 (1114162, 1114163)
1748        let reimported_sems = convert_bytes_to_dcmstring(
1749            &sems_transformed.bytes,
1750            None,
1751            &DcConversionOptions {
1752                format: FormatSpec::Format(SupportedDcInputFormat::Sems),
1753                ..Default::default()
1754            },
1755        )
1756        .unwrap();
1757        assert_eq!(
1758            reimported_sems
1759                .document
1760                .to_dc_string()
1761                .unwrap()
1762                .to_dclist(),
1763            vec![1_114_162, 1_114_163]
1764        );
1765    }
1766}