ctb_formats_dceutils/
converter.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//! Specification-oriented DCE 3.0a / 3.01a / 3.02a and CDCE converters.
21//!
22//! Unlike the legacy modules (`cdce`, `dce3_0a`, `dce3_01a`, `unicode`), which are
23//! preserved to match `old/libdce-2.51/` as closely as possible for comparison,
24//! this module implements DCE wire codecs from `docs/` and delegates document
25//! conversion to shared APIs, with the limits documented below:
26//!
27//! - **DCE 3.0a (`3_0a`, `3_0a_raw`, `hex_3_0a`, `hex_3_0a_raw`)**:
28//!   Raw transport encodes and decodes all mapped short Dcs in `0..=115`
29//!   ([`MAX_DCE_3_0A_SHORT_DC`], i.e. `0`, `1`, and `13..=115`; short Dcs `2..=12`
30//!   had no byte mappings in 3.0a and are logged as unmappable in `FormatLog` and omitted).
31//! - **DCE 3.01a (`3_01a`, `3_01a_raw`, `hex_3_01a`, `hex_3_01a_raw`)**:
32//!   Raw transport encodes and decodes all allocated short Dcs in `0..=199`
33//!   ([`MAX_DCE_3_01A_SHORT_DC`]), unlocking Base64 encapsulation
34//!   (`Dc 191` .. `Dc 127..=190` / `Dc 195` .. `Dc 192`) for arbitrary UTF-8 and data.
35//! - **DCE 3.02a (`3_02a`, `3_02a_raw`, `hex_3_02a`, `hex_3_02a_raw`)**:
36//!   Stubbed (returns an error when invoked). Allocates short Dcs `0..=202`
37//!   ([`MAX_DCE_3_02A_SHORT_DC`]), adding keyed embed framing (`Dc 200..=202`) on
38//!   `Core:C9..=CB`, but the 18 October 2013 specification left its version selector
39//!   in `DCE_Version_Selectors` and corresponding short Dc unassigned (marked as TBD;
40//!   `Dc 205` is `DCE Version Selector 3.03a`, so position `0x03` is not used here to
41//!   avoid colliding with 3.03a).
42//! - **Corrected Base64 digit 34 (`Dc 161`, `'i'`) vs digit 8 (`Dc 135`, `'I'`)**:
43//!   The upstream `.ods` spreadsheet auto-capitalized lowercase `'i'` to `'I'`,
44//!   corrupting `Base64_to_Dc` and `Dc_to_Base64`.
45//! - **Corrected `Dc 113` (`End DCE content`) mapping (`Core:03`)**:
46//!   The upstream `DCE Character List by ID` sheet had a typo `Core:01` instead of `Core:03`.
47//! - **Unicode conversion** uses the shared modern equivalence and approximation
48//!   resolver, including NEXT LINE for the historical newline character.
49//!   Unmapped Unicode is preserved using UTF-8 encapsulation on capable targets.
50//!
51//! The 3.02a version selector is left marked as TBD because its spreadsheet leaves
52//! the selector unassigned and `Dc 205` is allocated to DCE 3.03a. Explicit legacy
53//! one-step and legacy HTML translators retain PHP-compatible behavior. Normal
54//! HTML escapes shared Unicode text. See `porting-notes.md` for audit limits.
55
56#[allow(
57    unused_imports,
58    clippy::wildcard_imports,
59    reason = "Standard workspace module prelude"
60)]
61use crate::utilities::*;
62
63use anyhow::{Context, Result, anyhow, bail};
64use ctb_formats_hexdump::hex2bin;
65use ctb_formats_utilities::FormatLog;
66
67use crate::legacy;
68use crate::tools::explode_escaped;
69
70/// Maximum short Dc allocated in DCE 3.0a (`0..=115`).
71pub const MAX_DCE_3_0A_SHORT_DC: u32 = 115;
72
73/// Maximum short Dc allocated in DCE 3.01a (`0..=199`).
74pub const MAX_DCE_3_01A_SHORT_DC: u32 = 199;
75
76/// Maximum short Dc allocated in DCE 3.02a (`0..=202`).
77pub const MAX_DCE_3_02A_SHORT_DC: u32 = 202;
78
79/// DCE specification version.
80#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
81pub enum DceVersion {
82    /// DCE 3.0a (version byte `0x01`, short Dcs `0..=115`).
83    V3_0a,
84    /// DCE 3.01a (version byte `0x02`, short Dcs `0..=199`, Base64 encapsulation).
85    V3_01a,
86    /// DCE 3.02a (stubbed; version byte TBD, short Dcs `0..=202`, keyed embeds + Base64 encapsulation).
87    V3_02a,
88}
89
90impl DceVersion {
91    /// Returns the DCE header version selector byte (`Some(0x01)` for 3.0a, `Some(0x02)` for 3.01a,
92    /// or `None` for 3.02a whose version selector byte in `DCE_Version_Selectors` is TBD).
93    #[must_use]
94    pub const fn version_byte(self) -> Option<u8> {
95        match self {
96            Self::V3_0a => Some(0x01),
97            Self::V3_01a => Some(0x02),
98            // TBD: the 18 October 2013 DCE 3.02a specification left its version selector
99            // position in DCE_Version_Selectors unassigned (position 0x03 may belong to 3.03a).
100            Self::V3_02a => None,
101        }
102    }
103
104    /// Returns the `dceutils` format code for this version (`"3_0a"`, `"3_01a"`, `"3_02a"`).
105    #[must_use]
106    pub const fn as_format_str(self) -> &'static str {
107        match self {
108            Self::V3_0a => "3_0a",
109            Self::V3_01a => "3_01a",
110            Self::V3_02a => "3_02a",
111        }
112    }
113
114    /// Returns the maximum contiguous short Dc ID allocated in this version of DCE.
115    #[must_use]
116    pub const fn max_short_dc(self) -> u32 {
117        match self {
118            Self::V3_0a => MAX_DCE_3_0A_SHORT_DC,
119            Self::V3_01a => MAX_DCE_3_01A_SHORT_DC,
120            Self::V3_02a => MAX_DCE_3_02A_SHORT_DC,
121        }
122    }
123
124    /// Returns `true` if `short_dc` can be represented in this version of DCE.
125    #[must_use]
126    pub const fn supports_short_dc(self, short_dc: u32) -> bool {
127        match self {
128            Self::V3_0a => {
129                short_dc <= MAX_DCE_3_0A_SHORT_DC && !matches!(short_dc, 2..=12)
130            }
131            Self::V3_01a => short_dc <= MAX_DCE_3_01A_SHORT_DC,
132            Self::V3_02a => {
133                // TBD: version selector short Dc for 3.02a was left unassigned in the spec
134                // (Dc 205 is DCE Version Selector 3.03a).
135                short_dc <= MAX_DCE_3_02A_SHORT_DC
136            }
137        }
138    }
139
140    /// Returns `true` if this DCE version supports Base64 encapsulation (`Dc 127..=192`, `Dc 195`).
141    #[must_use]
142    pub const fn supports_base64_encapsulation(self) -> bool {
143        matches!(self, Self::V3_01a | Self::V3_02a)
144    }
145}
146
147/// Active DCE code sheet state.
148#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149enum DceSheet {
150    Core,
151    DceVersionSelectors,
152    VariantSelectors,
153    SemanticRecords,
154    Mathematics,
155    PunctuationAndWhitespace,
156}
157
158impl DceSheet {
159    const fn name(self) -> &'static str {
160        match self {
161            Self::Core => "Core",
162            Self::DceVersionSelectors => "DCE_Version_Selectors",
163            Self::VariantSelectors => "Variant_Selectors",
164            Self::SemanticRecords => "Semantic_Records",
165            Self::Mathematics => "Mathematics",
166            Self::PunctuationAndWhitespace => "Punctuation_and_Whitespace",
167        }
168    }
169
170    const fn switch_byte_from_core(self) -> Option<u8> {
171        match self {
172            Self::Core => None,
173            Self::DceVersionSelectors => Some(0x01),
174            Self::VariantSelectors => Some(0xC5),
175            Self::SemanticRecords => Some(0xC6),
176            Self::Mathematics => Some(0xC7),
177            Self::PunctuationAndWhitespace => Some(0xC8),
178        }
179    }
180}
181
182/// Returns `true` if `short_dc` is a DCE stateful-encoding control character or
183/// unbounded-content framing marker that has no glyph representation in text/CDCE.
184#[must_use]
185pub fn is_dce_encoding_control_dc(short_dc: u32) -> bool {
186    use ctb_formats_dcstring::syntax::SyntaxRuleResolver;
187    ctb_formats_dcstring::syntax::default_syntax_resolver()
188        .matches_named_type_starter(
189            "text_encoding_control",
190            ctb_formats_dcstring::DcChar::from_short(short_dc).to_u128(),
191        )
192}
193
194/// Maps a standard Base64 ASCII byte (`A-Z`, `a-z`, `0-9`, `+`, `/`, `=`) to its
195/// DCE 3.01a+ short Dc (`127..=190`, `195`).
196///
197/// Correctly maps `'I'` (`0x49`) to `135` and `'i'` (`0x69`) to `161`.
198#[must_use]
199pub const fn base64_char_to_short_dc(ch: u8) -> Option<u32> {
200    match ch {
201        b'A'..=b'Z' => {
202            let offset = ch.saturating_sub(b'A');
203            Some(127_u32.saturating_add(u32::from_le_bytes([offset, 0, 0, 0])))
204        }
205        b'a'..=b'z' => {
206            let offset = ch.saturating_sub(b'a');
207            Some(153_u32.saturating_add(u32::from_le_bytes([offset, 0, 0, 0])))
208        }
209        b'0'..=b'9' => {
210            let offset = ch.saturating_sub(b'0');
211            Some(179_u32.saturating_add(u32::from_le_bytes([offset, 0, 0, 0])))
212        }
213        b'+' => Some(189),
214        b'/' => Some(190),
215        b'=' => Some(195),
216        _ => None,
217    }
218}
219
220/// Maps a DCE 3.01a+ Base64 short Dc (`127..=190`, `195`) to its standard Base64 character.
221///
222/// Correctly maps `135` to `'I'` and `161` to `'i'`.
223#[must_use]
224pub const fn short_dc_to_base64_char(short_dc: u32) -> Option<char> {
225    match short_dc {
226        127..=152 => {
227            let cp = short_dc.saturating_sub(127).saturating_add(0x41);
228            char::from_u32(cp)
229        }
230        153..=178 => {
231            let cp = short_dc.saturating_sub(153).saturating_add(0x61);
232            char::from_u32(cp)
233        }
234        179..=188 => {
235            let cp = short_dc.saturating_sub(179).saturating_add(0x30);
236            char::from_u32(cp)
237        }
238        189 => Some('+'),
239        190 => Some('/'),
240        195 => Some('='),
241        _ => None,
242    }
243}
244
245/// Returns `true` if `short_dc` is a Base64 digit (`127..=190`) or padding (`195`).
246#[must_use]
247pub const fn is_base64_payload_short_dc(short_dc: u32) -> bool {
248    matches!(short_dc, 127..=190 | 195)
249}
250
251/// Encodes arbitrary bytes into DCE 3.01a+ Base64 short Dcs (`127..=190`, `195`).
252#[must_use]
253pub fn encode_bytes_to_dc64(bytes: &[u8]) -> Vec<u32> {
254    if bytes.is_empty() {
255        return Vec::new();
256    }
257    let b64 = ctb_formats_base64::base64_encode(bytes);
258    let mut out = Vec::with_capacity(b64.len());
259    for &b in b64.as_bytes() {
260        if let Some(dc) = base64_char_to_short_dc(b) {
261            out.push(dc);
262        }
263    }
264    out
265}
266
267/// Encodes UTF-8 bytes into a DCE 3.01a+ Base64-encapsulated short Dc sequence
268/// (`Dc 191`, Base64 Dcs `127..=190` / `195`, `Dc 192`).
269#[must_use]
270pub fn encode_utf8_to_dc64_encapsulated(bytes: &[u8]) -> Vec<u32> {
271    let payload = encode_bytes_to_dc64(bytes);
272    let mut out = Vec::with_capacity(payload.len().saturating_add(2));
273    out.push(191);
274    out.extend(payload);
275    out.push(192);
276    out
277}
278
279/// Decodes a slice of DCE 3.01a+ Base64 short Dcs (`127..=190`, `195`) into raw bytes.
280///
281/// # Errors
282/// Returns an error if `dcs` contains non-Base64 short Dcs or invalid Base64 data.
283pub fn decode_dc64_to_bytes(
284    dcs: &[u32],
285    log: &mut FormatLog,
286) -> Result<Vec<u8>> {
287    let mut b64_str = String::with_capacity(dcs.len());
288    for &dc in dcs {
289        if let Some(ch) = short_dc_to_base64_char(dc) {
290            b64_str.push(ch);
291        } else {
292            log.error(
293                "This document is not stored using the specified format.",
294            );
295            bail!("This document is not stored using the specified format.");
296        }
297    }
298    ctb_formats_base64::base64_decode(&b64_str).map_err(|_| {
299        log.error("This document is not stored using the specified format.");
300        anyhow!("This document is not stored using the specified format.")
301    })
302}
303
304/// Selects a DCE short character with an exact shared Unicode equivalence.
305#[must_use]
306pub fn unicode_codepoint_to_short_dc(cp: u32) -> Option<u32> {
307    use ctb_formats_dcstring::syntax::SyntaxRuleResolver;
308    let resolver = ctb_formats_dcstring::syntax::default_syntax_resolver();
309    (0..=MAX_DCE_3_01A_SHORT_DC).find(|&short| {
310        resolver.canonical_token(
311            ctb_formats_dcstring::DcChar::from_short(short).to_u128(),
312        ) == u128::from(cp)
313    })
314}
315
316/// Maps a short Dc ID to its target `(DceSheet, byte)` for the given `DceVersion`.
317const fn encode_short_dc_in_version(
318    short_dc: u32,
319    ver: DceVersion,
320) -> Option<(DceSheet, u8)> {
321    if !ver.supports_short_dc(short_dc) {
322        return None;
323    }
324    match short_dc {
325        0 => Some((DceSheet::Core, 0x00)),
326        1 => Some((DceSheet::Core, 0x40)),
327        2..=11 => {
328            let [low, _, _, _] = short_dc.saturating_sub(1).to_le_bytes();
329            Some((DceSheet::SemanticRecords, low))
330        }
331        12 => Some((DceSheet::Mathematics, 0x01)),
332        13 => Some((DceSheet::Core, 0xFD)),
333        14 => Some((DceSheet::Core, 0xFE)),
334        15 => Some((DceSheet::Core, 0x02)),
335        16 => Some((DceSheet::Core, 0x01)),
336        17 => Some((DceSheet::Core, 0xFF)),
337        18..=49 => {
338            let [low, _, _, _] = short_dc
339                .saturating_sub(18)
340                .saturating_add(0x20)
341                .to_le_bytes();
342            Some((DceSheet::Core, low))
343        }
344        50..=111 => {
345            let [low, _, _, _] = short_dc
346                .saturating_sub(50)
347                .saturating_add(0x41)
348                .to_le_bytes();
349            Some((DceSheet::Core, low))
350        }
351        112 => Some((DceSheet::DceVersionSelectors, 0x01)),
352        113 => Some((DceSheet::Core, 0x03)),
353        114 => Some((DceSheet::Core, 0x80)),
354        115 => Some((DceSheet::Core, 0x81)),
355        116 => Some((DceSheet::Core, 0x08)),
356        117 => Some((DceSheet::Core, 0x09)),
357        118 => Some((DceSheet::Core, 0x0B)),
358        119 => Some((DceSheet::PunctuationAndWhitespace, 0x01)),
359        120 => Some((DceSheet::Core, 0x0A)),
360        121 => Some((DceSheet::Core, 0x0D)),
361        122..=126 => {
362            let [low, _, _, _] = short_dc.saturating_sub(121).to_le_bytes();
363            Some((DceSheet::VariantSelectors, low))
364        }
365        127..=190 => {
366            let [low, _, _, _] = short_dc
367                .saturating_sub(127)
368                .saturating_add(0x82)
369                .to_le_bytes();
370            Some((DceSheet::Core, low))
371        }
372        191 => Some((DceSheet::Core, 0xC3)),
373        192 => Some((DceSheet::Core, 0xC4)),
374        193 => Some((DceSheet::Core, 0x0C)),
375        194 => Some((DceSheet::DceVersionSelectors, 0x02)),
376        195 => Some((DceSheet::Core, 0xC2)),
377        196 => Some((DceSheet::Core, 0xC5)),
378        197 => Some((DceSheet::Core, 0xC6)),
379        198 => Some((DceSheet::Core, 0xC7)),
380        199 => Some((DceSheet::Core, 0xC8)),
381        200 => Some((DceSheet::Core, 0xC9)),
382        201 => Some((DceSheet::Core, 0xCB)),
383        202 => Some((DceSheet::Core, 0xCA)),
384        // TBD: DCE 3.02a version selector short Dc and DCE_Version_Selectors byte
385        // (Dc 205 is DCE Version Selector 3.03a).
386        _ => None,
387    }
388}
389
390/// Detects the DCE format version (`"3_0a"` or `"3_01a"`) of `data`.
391#[must_use]
392pub fn get_dce_version(data: &[u8]) -> String {
393    let mut log = FormatLog::default();
394    let res = get_dce_version_with_log(data, &mut log);
395    log.auto_log();
396    res
397}
398
399/// Detects the DCE format version (`"3_0a"` or `"3_01a"`) of `data`,
400/// recording any errors in `log`.
401pub fn get_dce_version_with_log(data: &[u8], log: &mut FormatLog) -> String {
402    if data.len() < 7 || data.get(0..6) != Some(b"DCEe\x02\x01".as_slice()) {
403        log.error("This document does not appear to be stored using DCE.");
404        return "This document does not appear to be stored using DCE."
405            .to_string();
406    }
407    match data.get(6) {
408        Some(&1) => "3_0a".to_string(),
409        Some(&2) => "3_01a".to_string(),
410        // TBD: DCE 3.02a version selector byte is unassigned (position 0x03 may belong to 3.03a).
411        _ => {
412            log.error(
413                "This document is not stored using a supported version of DCE.",
414            );
415            "This document is not stored using a supported version of DCE."
416                .to_string()
417        }
418    }
419}
420
421/// Selects the minimum implemented [`DceVersion`] (`V3_0a` or `V3_01a`) required to represent `dcs`.
422///
423/// Note: [`DceVersion::V3_02a`] (`Dc 200..=202`) is stubbed until its version selector
424/// in `DCE_Version_Selectors` is determined (TBD).
425#[must_use]
426pub fn select_dce_version_for_short_dcs(dcs: &[u32]) -> DceVersion {
427    let mut ver = DceVersion::V3_0a;
428    for &dc in dcs {
429        if matches!(dc, 2..=12 | 116..=202) {
430            ver = DceVersion::V3_01a;
431        }
432    }
433    ver
434}
435
436/// Decodes a DCE binary or hex-encoded stream (`dce`, `3_0a`, `3_0a_raw`,
437/// `3_01a`, `3_01a_raw`, `3_02a`, `3_02a_raw`, and their `hex_*` variants)
438/// into a sequence of short Dc IDs while preserving all stateful DCE control
439/// characters (`13..=16`, `112..=115`, `194`, `196..=199`, `205`) as-is.
440///
441/// # Errors
442/// Returns an error if the input format is unknown or the header does not match
443/// the specified DCE version.
444pub fn decode_dce_preserving_controls(
445    data: &[u8],
446    input_format: &str,
447    log: &mut FormatLog,
448) -> Result<Vec<u32>> {
449    decode_dce_preserving_controls_with_options(data, input_format, false, log)
450}
451
452/// Decodes DCE while retaining encoding controls and diagnosing recovery.
453///
454/// # Errors
455/// Returns an error for invalid framing or unassigned bytes in strict mode.
456pub fn decode_dce_preserving_controls_with_options(
457    data: &[u8],
458    input_format: &str,
459    permissive: bool,
460    log: &mut FormatLog,
461) -> Result<Vec<u32>> {
462    let (raw_bytes, base_fmt) = match input_format {
463        "hex_dce" | "dce_hex" => (decode_hex_payload(data, log)?, "dce"),
464        "hex_3_0a" | "3_0a_hex" | "dce_3_0a_hex" => {
465            (decode_hex_payload(data, log)?, "3_0a")
466        }
467        "hex_3_0a_raw" | "3_0a_raw_hex" | "dce_3_0a_raw_hex" => {
468            (decode_hex_payload(data, log)?, "3_0a_raw")
469        }
470        "hex_3_01a" | "3_01a_hex" | "dce_3_01a_hex" => {
471            (decode_hex_payload(data, log)?, "3_01a")
472        }
473        "hex_3_01a_raw" | "3_01a_raw_hex" | "dce_3_01a_raw_hex" => {
474            (decode_hex_payload(data, log)?, "3_01a_raw")
475        }
476        "hex_3_02a" | "3_02a_hex" | "dce_3_02a_hex" => {
477            (decode_hex_payload(data, log)?, "3_02a")
478        }
479        "hex_3_02a_raw" | "3_02a_raw_hex" | "dce_3_02a_raw_hex" => {
480            (decode_hex_payload(data, log)?, "3_02a_raw")
481        }
482        "3_0a" | "dce_3_0a" => (data.to_vec(), "3_0a"),
483        "3_0a_raw" | "dce_3_0a_raw" => (data.to_vec(), "3_0a_raw"),
484        "3_01a" | "dce_3_01a" => (data.to_vec(), "3_01a"),
485        "3_01a_raw" | "dce_3_01a_raw" => (data.to_vec(), "3_01a_raw"),
486        "3_02a" | "dce_3_02a" => (data.to_vec(), "3_02a"),
487        "3_02a_raw" | "dce_3_02a_raw" => (data.to_vec(), "3_02a_raw"),
488        "dce" => (data.to_vec(), "dce"),
489        _ => {
490            log.error("Unknown DCE input format.");
491            bail!("Unknown DCE input format: {input_format}");
492        }
493    };
494
495    let (ver, start_offset) = match base_fmt {
496        "3_0a_raw" => {
497            if raw_bytes.first() != Some(&0x80) {
498                log.error(
499                    "This document is not stored using the specified format.",
500                );
501                bail!(
502                    "This document is not stored using the specified format."
503                );
504            }
505            (DceVersion::V3_0a, 0_usize)
506        }
507        "3_01a_raw" => {
508            if raw_bytes.first() != Some(&0x80) {
509                log.error(
510                    "This document is not stored using the specified format.",
511                );
512                bail!(
513                    "This document is not stored using the specified format."
514                );
515            }
516            (DceVersion::V3_01a, 0_usize)
517        }
518        "3_02a" | "3_02a_raw" => {
519            // Stubbed for later: the 18 October 2013 DCE 3.02a specification left its
520            // version selector in DCE_Version_Selectors unassigned (TBD; position 0x03
521            // may belong to DCE 3.03a / Dc 205).
522            let msg = "DCE 3.02a is not yet implemented (version selector in DCE_Version_Selectors is TBD).";
523            log.error(msg);
524            bail!("{msg}");
525        }
526        "3_0a" | "3_01a" | "dce" => {
527            if raw_bytes.len() < 7
528                || raw_bytes.get(0..6) != Some(b"DCEe\x02\x01".as_slice())
529            {
530                log.error(
531                    "This document is not stored using the specified format.",
532                );
533                bail!(
534                    "This document is not stored using the specified format."
535                );
536            }
537            let ver_byte = *raw_bytes.get(6).context("missing version byte")?;
538            match (base_fmt, ver_byte) {
539                ("3_0a" | "dce", 1) => (DceVersion::V3_0a, 4_usize),
540                ("3_01a" | "dce", 2) => (DceVersion::V3_01a, 4_usize),
541                // TBD: DCE 3.02a version selector byte in DCE_Version_Selectors is unassigned.
542                ("3_0a", _) => {
543                    log.error(
544                        "This document is not stored using the specified format.",
545                    );
546                    bail!(
547                        "This document is not stored using the specified format."
548                    );
549                }
550                ("3_01a", _) => {
551                    log.error(
552                        "This document is not stored using the specified version of DCE.",
553                    );
554                    bail!(
555                        "This document is not stored using the specified version of DCE."
556                    );
557                }
558                _ => {
559                    log.error(
560                        "This document is not stored using a supported version of DCE.",
561                    );
562                    bail!(
563                        "This document is not stored using a supported version of DCE."
564                    );
565                }
566            }
567        }
568        _ => unreachable!("base_fmt is constrained above"),
569    };
570
571    let mut out = Vec::new();
572    let mut state = DceSheet::Core;
573    let valid_envelope = if start_offset == 0 {
574        raw_bytes.last() == Some(&0x81)
575    } else {
576        raw_bytes
577            .get(7..raw_bytes.len().saturating_sub(2))
578            .is_some_and(|selector_region| selector_region.contains(&0xFD))
579            && raw_bytes.ends_with(&[0xFD, 0x03])
580    };
581    if !valid_envelope {
582        log.error("This document is not stored using the specified format.");
583        bail!("This document is not stored using the specified format.");
584    }
585    let slice = raw_bytes
586        .get(start_offset..)
587        .context("raw_bytes shorter than start offset")?;
588
589    for (idx, &byte) in slice.iter().enumerate() {
590        let idx_u64 = u64::try_from(idx.saturating_add(start_offset))?;
591        let decoded_length = out.len();
592        match state {
593            DceSheet::Core => match byte {
594                0x00 => out.push(0),
595                0x01 => {
596                    out.push(16);
597                    state = DceSheet::DceVersionSelectors;
598                }
599                0x02 => out.push(15),
600                0x03 => {
601                    ensure!(
602                        start_offset == 0
603                            || idx
604                                .saturating_add(start_offset)
605                                .saturating_add(1)
606                                == raw_bytes.len(),
607                        "Content follows the DCE end marker at offset {idx_u64}",
608                    );
609                    out.push(113);
610                }
611                0x08 if ver >= DceVersion::V3_01a => out.push(116),
612                0x09 if ver >= DceVersion::V3_01a => out.push(117),
613                0x0A if ver >= DceVersion::V3_01a => out.push(120),
614                0x0B if ver >= DceVersion::V3_01a => out.push(118),
615                0x0C if ver >= DceVersion::V3_01a => out.push(193),
616                0x0D if ver >= DceVersion::V3_01a => out.push(121),
617                0x20..=0x3F => {
618                    out.push(
619                        u32::from(byte).saturating_sub(0x20).saturating_add(18),
620                    );
621                }
622                0x40 => out.push(1),
623                0x41..=0x7E => {
624                    out.push(
625                        u32::from(byte).saturating_sub(0x41).saturating_add(50),
626                    );
627                }
628                0x80 => out.push(114),
629                0x81 => out.push(115),
630                0x82..=0xC1 if ver >= DceVersion::V3_01a => {
631                    out.push(
632                        u32::from(byte)
633                            .saturating_sub(0x82)
634                            .saturating_add(127),
635                    );
636                }
637                0xC2 if ver >= DceVersion::V3_01a => out.push(195),
638                0xC3 if ver >= DceVersion::V3_01a => out.push(191),
639                0xC4 if ver >= DceVersion::V3_01a => out.push(192),
640                0xC5 if ver >= DceVersion::V3_01a => {
641                    out.push(196);
642                    state = DceSheet::VariantSelectors;
643                }
644                0xC6 if ver >= DceVersion::V3_01a => {
645                    out.push(197);
646                    state = DceSheet::SemanticRecords;
647                }
648                0xC7 if ver >= DceVersion::V3_01a => {
649                    out.push(198);
650                    state = DceSheet::Mathematics;
651                }
652                0xC8 if ver >= DceVersion::V3_01a => {
653                    out.push(199);
654                    state = DceSheet::PunctuationAndWhitespace;
655                }
656                0xC9 if ver >= DceVersion::V3_02a => out.push(200),
657                0xCA if ver >= DceVersion::V3_02a => out.push(202),
658                0xCB if ver >= DceVersion::V3_02a => out.push(201),
659                0xFD => {
660                    out.push(13);
661                    state = DceSheet::Core;
662                }
663                0xFE => {
664                    out.push(14);
665                    state = DceSheet::Core;
666                }
667                0xFF => out.push(17),
668                _ => {
669                    log.import_warning(
670                        idx_u64,
671                        &format!(
672                            "Unmapped DCE Core byte 0x{byte:02X} dropped during import"
673                        ),
674                    );
675                }
676            },
677            DceSheet::DceVersionSelectors => match byte {
678                0x00 => out.push(0),
679                0x01 => out.push(112),
680                0x02 if ver >= DceVersion::V3_01a => out.push(194),
681                // TBD: DCE 3.02a version selector byte and short Dc (position 0x03 is unassigned
682                // in the 3.02a specification and may belong to DCE 3.03a / Dc 205).
683                0xFD => {
684                    out.push(13);
685                    state = DceSheet::Core;
686                }
687                0xFE => {
688                    out.push(14);
689                    state = DceSheet::Core;
690                }
691                0xFF => out.push(17),
692                _ => {
693                    log.import_warning(
694                        idx_u64,
695                        &format!(
696                            "Unmapped DCE_Version_Selectors byte 0x{byte:02X} dropped during import"
697                        ),
698                    );
699                }
700            },
701            DceSheet::VariantSelectors => match byte {
702                0x00 => out.push(0),
703                0x01..=0x05 => {
704                    out.push(u32::from(byte).saturating_add(121));
705                }
706                0xFD => {
707                    out.push(13);
708                    state = DceSheet::Core;
709                }
710                0xFE => {
711                    out.push(14);
712                    state = DceSheet::Core;
713                }
714                0xFF => out.push(17),
715                _ => {
716                    log.import_warning(
717                        idx_u64,
718                        &format!(
719                            "Unmapped DCE Variant_Selectors byte 0x{byte:02X} dropped during import"
720                        ),
721                    );
722                }
723            },
724            DceSheet::SemanticRecords => match byte {
725                0x00 => out.push(0),
726                0x01..=0x0A => {
727                    out.push(u32::from(byte).saturating_add(1));
728                }
729                0xFD => {
730                    out.push(13);
731                    state = DceSheet::Core;
732                }
733                0xFE => {
734                    out.push(14);
735                    state = DceSheet::Core;
736                }
737                0xFF => out.push(17),
738                _ => {
739                    log.import_warning(
740                        idx_u64,
741                        &format!(
742                            "Unmapped DCE Semantic_Records byte 0x{byte:02X} dropped during import"
743                        ),
744                    );
745                }
746            },
747            DceSheet::Mathematics => match byte {
748                0x00 => out.push(0),
749                0x01 => out.push(12),
750                0xFD => {
751                    out.push(13);
752                    state = DceSheet::Core;
753                }
754                0xFE => {
755                    out.push(14);
756                    state = DceSheet::Core;
757                }
758                0xFF => out.push(17),
759                _ => {
760                    log.import_warning(
761                        idx_u64,
762                        &format!(
763                            "Unmapped DCE Mathematics byte 0x{byte:02X} dropped during import"
764                        ),
765                    );
766                }
767            },
768            DceSheet::PunctuationAndWhitespace => match byte {
769                0x00 => out.push(0),
770                0x01 => out.push(119),
771                0xFD => {
772                    out.push(13);
773                    state = DceSheet::Core;
774                }
775                0xFE => {
776                    out.push(14);
777                    state = DceSheet::Core;
778                }
779                0xFF => out.push(17),
780                _ => {
781                    log.import_warning(
782                        idx_u64,
783                        &format!(
784                            "Unmapped DCE {} byte 0x{byte:02X} dropped during import",
785                            state.name()
786                        ),
787                    );
788                }
789            },
790        }
791        ensure!(
792            permissive || out.len() > decoded_length,
793            "Unassigned DCE {} byte 0x{byte:02X} at offset {idx_u64}",
794            state.name(),
795        );
796    }
797
798    Ok(out)
799}
800
801/// Encodes a sequence of short Dc IDs into a DCE binary or hex-encoded format
802/// (`dce`, `3_0a`, `3_0a_raw`, `3_01a`, `3_01a_raw`, `3_02a`, `3_02a_raw`, and
803/// their `hex_*` variants), respecting any explicit DCE sheet/control Dcs
804/// already present in `dcs` and automatically inserting sheet transitions or
805/// framing when absent.
806///
807/// # Errors
808/// Returns an error if `output_format` is not a recognized DCE format.
809pub fn encode_dce_preserving_controls(
810    dcs: &[u32],
811    output_format: &str,
812    log: &mut FormatLog,
813) -> Result<Vec<u8>> {
814    let (base_fmt, is_hex) = match output_format {
815        "hex_dce" | "dce_hex" => ("dce", true),
816        "hex_3_0a" | "3_0a_hex" | "dce_3_0a_hex" => ("3_0a", true),
817        "hex_3_0a_raw" | "3_0a_raw_hex" | "dce_3_0a_raw_hex" => {
818            ("3_0a_raw", true)
819        }
820        "hex_3_01a" | "3_01a_hex" | "dce_3_01a_hex" => ("3_01a", true),
821        "hex_3_01a_raw" | "3_01a_raw_hex" | "dce_3_01a_raw_hex" => {
822            ("3_01a_raw", true)
823        }
824        "hex_3_02a" | "3_02a_hex" | "dce_3_02a_hex" => ("3_02a", true),
825        "hex_3_02a_raw" | "3_02a_raw_hex" | "dce_3_02a_raw_hex" => {
826            ("3_02a_raw", true)
827        }
828        "dce" | "3_0a" | "3_0a_raw" | "3_01a" | "3_01a_raw" | "3_02a"
829        | "3_02a_raw" => (output_format, false),
830        "dce_3_0a" => ("3_0a", false),
831        "dce_3_0a_raw" => ("3_0a_raw", false),
832        "dce_3_01a" => ("3_01a", false),
833        "dce_3_01a_raw" => ("3_01a_raw", false),
834        "dce_3_02a" => ("3_02a", false),
835        "dce_3_02a_raw" => ("3_02a_raw", false),
836        _ => {
837            log.error("Unknown DCE output format.");
838            bail!("Unknown DCE output format: {output_format}");
839        }
840    };
841
842    let is_raw = matches!(base_fmt, "3_0a_raw" | "3_01a_raw" | "3_02a_raw");
843
844    // Strip outer DCE file envelope (`[15, 16, 112|194, 13|14, ..., 13|14, 113]`;
845    // 3.02a version selector Dc is TBD) only when both header and trailer are present.
846    let (inner, inner_offset) = if let Some(start) = dce_content_start(dcs) {
847        (
848            dcs.get(start..dcs.len().saturating_sub(2))
849                .context("dcs envelope slice out of bounds")?,
850            start,
851        )
852    } else {
853        (dcs, 0_usize)
854    };
855
856    // Strip outer unbounded-content markers (`[114, ..., 115]`) only when both are present.
857    let (body, body_offset) = if inner.len() >= 2
858        && inner.first() == Some(&114)
859        && inner.last() == Some(&115)
860    {
861        (
862            inner
863                .get(1..inner.len().saturating_sub(1))
864                .context("inner unbounded slice out of bounds")?,
865            inner_offset.saturating_add(1),
866        )
867    } else {
868        (inner, inner_offset)
869    };
870
871    ensure!(
872        is_raw || !body.contains(&113),
873        "DCE content contains an interior file end marker"
874    );
875    let ver = match base_fmt {
876        "3_0a" | "3_0a_raw" => DceVersion::V3_0a,
877        "3_01a" | "3_01a_raw" => DceVersion::V3_01a,
878        "3_02a" | "3_02a_raw" => {
879            // Stubbed for later: the 18 October 2013 DCE 3.02a specification left its
880            // version selector in DCE_Version_Selectors unassigned (TBD; position 0x03
881            // may belong to DCE 3.03a / Dc 205).
882            let msg = "DCE 3.02a is not yet implemented (version selector in DCE_Version_Selectors is TBD).";
883            log.error(msg);
884            bail!("{msg}");
885        }
886        "dce" => select_dce_version_for_short_dcs(body),
887        _ => unreachable!("base_fmt is constrained above"),
888    };
889
890    let mut raw_out = Vec::with_capacity(body.len().saturating_add(16));
891    if !is_raw {
892        let Some(ver_byte) = ver.version_byte() else {
893            let msg = "DCE 3.02a is not yet implemented (version selector in DCE_Version_Selectors is TBD).";
894            log.error(msg);
895            bail!("{msg}");
896        };
897        raw_out.extend_from_slice(b"DCEe\x02\x01");
898        raw_out.push(ver_byte);
899        raw_out.push(0xFD);
900    }
901
902    // Begin unbounded content (Dc 114 = 0x80)
903    raw_out.push(0x80);
904
905    let mut state = DceSheet::Core;
906    encode_short_dcs_into_stream(
907        body,
908        body_offset,
909        ver,
910        output_format,
911        &mut state,
912        &mut raw_out,
913        log,
914    )?;
915
916    if state != DceSheet::Core {
917        raw_out.push(0xFD);
918    }
919
920    // End unbounded content (Dc 115 = 0x81)
921    raw_out.push(0x81);
922
923    if !is_raw {
924        raw_out.extend_from_slice(&[0xFD, 0x03]);
925    }
926
927    if is_hex {
928        Ok(bin2hex(raw_out).to_uppercase().into_bytes())
929    } else {
930        Ok(raw_out)
931    }
932}
933
934fn encode_short_dcs_into_stream(
935    body: &[u32],
936    body_offset: usize,
937    ver: DceVersion,
938    output_format: &str,
939    state: &mut DceSheet,
940    raw_out: &mut Vec<u8>,
941    log: &mut FormatLog,
942) -> Result<()> {
943    for (idx, &dc) in body.iter().enumerate() {
944        let idx_u64 = u64::try_from(idx.saturating_add(body_offset))?;
945        match dc {
946            13 => {
947                raw_out.push(0xFD);
948                *state = DceSheet::Core;
949                continue;
950            }
951            14 => {
952                raw_out.push(0xFE);
953                *state = DceSheet::Core;
954                continue;
955            }
956            16 => {
957                if *state != DceSheet::Core {
958                    raw_out.push(0xFD);
959                }
960                raw_out.push(0x01);
961                *state = DceSheet::DceVersionSelectors;
962                continue;
963            }
964            196 if ver >= DceVersion::V3_01a => {
965                if *state != DceSheet::Core {
966                    raw_out.push(0xFD);
967                }
968                raw_out.push(0xC5);
969                *state = DceSheet::VariantSelectors;
970                continue;
971            }
972            197 if ver >= DceVersion::V3_01a => {
973                if *state != DceSheet::Core {
974                    raw_out.push(0xFD);
975                }
976                raw_out.push(0xC6);
977                *state = DceSheet::SemanticRecords;
978                continue;
979            }
980            198 if ver >= DceVersion::V3_01a => {
981                if *state != DceSheet::Core {
982                    raw_out.push(0xFD);
983                }
984                raw_out.push(0xC7);
985                *state = DceSheet::Mathematics;
986                continue;
987            }
988            199 if ver >= DceVersion::V3_01a => {
989                if *state != DceSheet::Core {
990                    raw_out.push(0xFD);
991                }
992                raw_out.push(0xC8);
993                *state = DceSheet::PunctuationAndWhitespace;
994                continue;
995            }
996            _ => {}
997        }
998
999        if let Some((sheet_needed, byte)) = encode_short_dc_in_version(dc, ver)
1000        {
1001            if sheet_needed != *state {
1002                if *state != DceSheet::Core {
1003                    raw_out.push(0xFD);
1004                    *state = DceSheet::Core;
1005                }
1006                if let Some(sw_byte) = sheet_needed.switch_byte_from_core() {
1007                    raw_out.push(sw_byte);
1008                    *state = sheet_needed;
1009                }
1010            }
1011            raw_out.push(byte);
1012        } else {
1013            log.export_warning_unmappable(idx_u64, dc, output_format);
1014        }
1015    }
1016    Ok(())
1017}
1018
1019/// Converts between any `dceutils` / DCE / CDCE formats using the spec-compliant
1020/// implementations (supporting DCE 3.0a `0..=115`, DCE 3.01a `0..=199` with Base64
1021/// encapsulation, DCE 3.02a `0..=202`, and general/legacy CDCE).
1022///
1023/// # Errors
1024/// Returns an error if the input/output format is unknown or input validation fails.
1025pub fn dce_convert(
1026    data: &[u8],
1027    input_format: &str,
1028    output_format: &str,
1029) -> Result<Vec<u8>> {
1030    let (res, log) = dce_convert_with_log(data, input_format, output_format)?;
1031    log.auto_log();
1032    Ok(res)
1033}
1034
1035/// Converts between any `dceutils` / DCE / CDCE formats using the spec-compliant
1036/// implementations, returning the converted bytes and [`FormatLog`].
1037///
1038/// # Errors
1039/// Returns an error if the input/output format is unknown or input validation fails.
1040pub fn dce_convert_with_log(
1041    data: &[u8],
1042    input_format: &str,
1043    output_format: &str,
1044) -> Result<(Vec<u8>, FormatLog)> {
1045    dce_convert_with_options(data, input_format, output_format, false)
1046}
1047
1048/// Converts formats with optional replacement-character recovery for damaged
1049/// text, returning converted bytes and diagnostics.
1050///
1051/// # Errors
1052/// Returns an error for unsupported formats or unrecoverable input. In strict
1053/// mode, malformed encapsulated text also returns an error.
1054pub fn dce_convert_with_options(
1055    data: &[u8],
1056    input_format: &str,
1057    output_format: &str,
1058    permissive: bool,
1059) -> Result<(Vec<u8>, FormatLog)> {
1060    let mut log = FormatLog::default();
1061    let res = dce_convert_internal(
1062        data,
1063        input_format,
1064        output_format,
1065        permissive,
1066        &mut log,
1067    )?;
1068    Ok((res, log))
1069}
1070
1071pub(crate) fn dce_convert_internal(
1072    data: &[u8],
1073    input_format: &str,
1074    output_format: &str,
1075    permissive: bool,
1076    log: &mut FormatLog,
1077) -> Result<Vec<u8>> {
1078    // One-step legacy translators
1079    match (input_format, output_format) {
1080        ("3_0a_old" | "dce_3_0a_old", "none") => {
1081            return legacy::onestep_3_0a_old_to_none(data);
1082        }
1083        ("dce2txt", "none") => return legacy::onestep_dce2txt_to_none(data),
1084        ("dce2hex", "none") => return legacy::onestep_dce2hex_to_none(data),
1085        ("hex2dce", "none") => return legacy::onestep_hex2dce_to_none(data),
1086        (
1087            "legacy_cdce" | "cdce_legacy",
1088            "html_snippet_l" | "html_s_legacy" | "html_legacy_cdce_snippet",
1089        ) => return legacy::onestep_legacy_cdce_to_html_snippet_l(data),
1090        (
1091            "legacy_cdce" | "cdce_legacy",
1092            "html_l" | "html_legacy" | "html_legacy_cdce",
1093        ) => return legacy::onestep_legacy_cdce_to_html_l(data),
1094        _ => {}
1095    }
1096
1097    let (doc, input_log) = crate::document::dceutils_to_dcmstring_with_options(
1098        data,
1099        input_format,
1100        permissive,
1101    )?;
1102    log.merge(&input_log);
1103    let (bytes, output_log) = crate::document::dcmstr_to_dceutils_with_options(
1104        &doc,
1105        output_format,
1106        permissive,
1107    )?;
1108    log.merge(&output_log);
1109    Ok(bytes)
1110}
1111
1112/// Extracts content short Dc IDs (bounded by `114` and `115`,
1113/// without the outer `[15, 16, ver, 13]` / `[13, 113]` file envelope or automatic sheet switches
1114/// unless those control Dcs were the sole content).
1115pub(crate) fn content_short_dcs(all: &[u32]) -> Result<Vec<u32>> {
1116    let inner = if let Some(start) = dce_content_start(all) {
1117        all.get(start..all.len().saturating_sub(2))
1118            .context("DCE envelope slice")?
1119    } else {
1120        all
1121    };
1122
1123    // Strip sheet-switch control Dcs (`16`, `196..=199`, and `13`/`14` that follow a sheet switch)
1124    // when they were used to introduce a non-Core character, while preserving standalone control Dcs.
1125    let mut out = Vec::with_capacity(inner.len());
1126    let mut in_non_core_sheet = false;
1127    for (idx, &dc) in inner.iter().enumerate() {
1128        let next_dc = inner.get(idx.saturating_add(1)).copied();
1129        if matches!(dc, 16 | 196..=199) {
1130            let next_is_sheet_char = match (dc, next_dc) {
1131                // TBD: 3.02a version selector Dc in DCE_Version_Selectors is unassigned.
1132                (16, Some(112 | 194))
1133                | (196, Some(122..=126))
1134                | (197, Some(2..=11))
1135                | (198, Some(12))
1136                | (199, Some(119)) => true,
1137                _ => false,
1138            };
1139            if next_is_sheet_char {
1140                in_non_core_sheet = true;
1141                continue;
1142            }
1143            // Standalone sheet-switch Dc (followed immediately by 13/14/115)
1144            out.push(dc);
1145            in_non_core_sheet = true;
1146            continue;
1147        }
1148        if matches!(dc, 13 | 14) && in_non_core_sheet {
1149            in_non_core_sheet = false;
1150            continue;
1151        }
1152        out.push(dc);
1153    }
1154
1155    Ok(out)
1156}
1157
1158pub(crate) fn dce_content_start(dcs: &[u32]) -> Option<usize> {
1159    if dcs.starts_with(&[15, 16]) && dcs.ends_with(&[13, 113]) {
1160        dcs.get(2..dcs.len().checked_sub(2)?)?
1161            .iter()
1162            .position(|&token| token == 13)
1163            .map(|offset| offset.saturating_add(3))
1164    } else {
1165        None
1166    }
1167}
1168
1169pub(crate) fn decode_cdce(
1170    data: &[u8],
1171    legacy_only: bool,
1172    strict: bool,
1173    permissive: bool,
1174    log: &mut FormatLog,
1175) -> Result<ctb_formats_dcstring::DcMstring> {
1176    let (doc, text_log) =
1177        ctb_formats_dcstring::converters::utf8::utf8_to_dcmstring_with_options(
1178            data, permissive,
1179        )?;
1180    log.merge(&text_log);
1181    let codepoints: Vec<u32> = doc
1182        .to_dc_string()?
1183        .chars()
1184        .map(|ch| {
1185            u32::try_from(ch.to_long()).context("UTF-8 codepoint fits u32")
1186        })
1187        .collect::<Result<_>>()?;
1188
1189    let mut output = ctb_formats_dcstring::DcMstring::new();
1190    let mut i = 0_usize;
1191
1192    while i < codepoints.len() {
1193        let cp = *codepoints
1194            .get(i)
1195            .context("codepoints index out of bounds")?;
1196        if cp == 0x40 {
1197            if let Some((dc_val, consumed)) =
1198                parse_at_escape(&codepoints, i, legacy_only)
1199            {
1200                output.push_char(ctb_formats_dcstring::DcChar::from_short(
1201                    dc_val,
1202                ));
1203                i = i.saturating_add(consumed);
1204                continue;
1205            }
1206            if strict && !permissive {
1207                let message = format!(
1208                    "CDCE decoding error: invalid escape sequence at codepoint index {i}"
1209                );
1210                log.error(&message);
1211                bail!("{message}");
1212            }
1213            log.warn(&format!(
1214                "Warning: Unicode recovery attempted for corrupted CDCE sequence at codepoint index {i}"
1215            ));
1216            output.push_char(ctb_formats_dcstring::DcChar::from('@'));
1217            i = i.saturating_add(1);
1218        } else {
1219            output.push_char(ctb_formats_dcstring::DcChar::from_u128(
1220                u128::from(cp),
1221            ));
1222            i = i.saturating_add(1);
1223        }
1224    }
1225    Ok(output)
1226}
1227
1228fn parse_at_escape(
1229    codepoints: &[u32],
1230    start: usize,
1231    legacy_only: bool,
1232) -> Option<(u32, usize)> {
1233    let mut j = start.saturating_add(1);
1234    let mut val = 0_u32;
1235    let mut digits = 0_usize;
1236    while j < codepoints.len() {
1237        let cp = *codepoints.get(j)?;
1238        if cp == 0x40 {
1239            if digits == 0 {
1240                return None;
1241            }
1242            if legacy_only && !(1..=12).contains(&val) {
1243                return None;
1244            }
1245            return Some((val, digits.saturating_add(2)));
1246        }
1247        if (0x30..=0x39).contains(&cp) {
1248            let d = cp.saturating_sub(0x30);
1249            if digits == 0 && d == 0 && legacy_only {
1250                return None;
1251            }
1252            val = val.checked_mul(10)?.checked_add(d)?;
1253            digits = digits.saturating_add(1);
1254            if legacy_only && digits > 2 {
1255                return None;
1256            }
1257            j = j.saturating_add(1);
1258        } else {
1259            return None;
1260        }
1261    }
1262    None
1263}
1264
1265pub(crate) fn encode_cdce(
1266    doc: &ctb_formats_dcstring::DcMstr,
1267    legacy_only: bool,
1268    permissive: bool,
1269    log: &mut FormatLog,
1270) -> Result<Vec<u8>> {
1271    use ctb_formats_dcstring::DcMstring;
1272    use ctb_formats_dcstring::syntax::{DcRole, SyntaxRuleResolver};
1273    let resolver = ctb_formats_dcstring::syntax::default_syntax_resolver();
1274    let mut output = Vec::new();
1275    let mut run = DcMstring::new();
1276    let mut encapsulated = false;
1277    let flush = |run: &mut DcMstring,
1278                 output: &mut Vec<u8>,
1279                 log: &mut FormatLog|
1280     -> Result<()> {
1281        let (bytes, text_log) = ctb_formats_dcstring::converters::utf8::dcmstr_to_utf8_with_options(
1282            run,
1283            &ctb_formats_dcstring::converters::utf8::DcListUtf8Settings {
1284                canonicalize_equivalent_dcs: true,
1285                permissive,
1286                ..Default::default()
1287            },
1288        )?;
1289        log.merge(&text_log);
1290        for byte in bytes {
1291            if byte == b'@' {
1292                output.extend_from_slice(b"@1@");
1293            } else {
1294                output.push(byte);
1295            }
1296        }
1297        *run = DcMstring::new();
1298        Ok(())
1299    };
1300    for ch in doc.to_dc_string()?.chars() {
1301        let token = ch.to_u128();
1302        if resolver.token_fills_role(token, DcRole::StartEncapsulationUtf8) {
1303            encapsulated = true;
1304        }
1305        if !encapsulated && let Ok(short) = ch.to_short() {
1306            let mapped = u32::try_from(resolver.canonical_token(token))
1307                .ok()
1308                .and_then(char::from_u32)
1309                .is_some()
1310                || resolver.unicode_text_mapping(token, true).is_some();
1311            if (1..=12).contains(&short)
1312                || (!legacy_only
1313                    && !mapped
1314                    && !is_dce_encoding_control_dc(short))
1315            {
1316                flush(&mut run, &mut output, log)?;
1317                output.extend_from_slice(format!("@{short}@").as_bytes());
1318                continue;
1319            }
1320            if is_dce_encoding_control_dc(short) {
1321                continue;
1322            }
1323        }
1324        run.push_char(ch);
1325        if resolver.token_fills_role(token, DcRole::EndEncapsulationUtf8) {
1326            encapsulated = false;
1327        }
1328    }
1329    flush(&mut run, &mut output, log)?;
1330    Ok(output)
1331}
1332
1333pub(crate) fn decode_utf8_dc64_csv_to_bytes(
1334    data: &[u8],
1335    encapsulated: bool,
1336    log: &mut FormatLog,
1337) -> Result<Vec<u8>> {
1338    let data_str = std::str::from_utf8(data).map_err(|_| {
1339        log.error("This document is not stored using the specified format.");
1340        anyhow!("This document is not stored using the specified format.")
1341    })?;
1342    let trimmed = data_str.trim().trim_end_matches(',');
1343    let inner = if encapsulated && trimmed == "191,192" {
1344        ""
1345    } else if encapsulated {
1346        if let Some(rest) = trimmed.strip_prefix("191,")
1347            && let Some(core) = rest.strip_suffix(",192")
1348        {
1349            core
1350        } else {
1351            log.error(
1352                "This document is not stored using the specified format.",
1353            );
1354            bail!("This document is not stored using the specified format.");
1355        }
1356    } else {
1357        if trimmed.starts_with("191,") && trimmed.ends_with(",192") {
1358            log.error(
1359                "This document is not stored using the specified format.",
1360            );
1361            bail!("This document is not stored using the specified format.");
1362        }
1363        trimmed
1364    };
1365
1366    let mut dcs = Vec::new();
1367    for piece in explode_escaped(',', inner) {
1368        let token = piece.trim();
1369        if token.is_empty() {
1370            continue;
1371        }
1372        let Ok(val) = token.parse::<u32>() else {
1373            log.error(
1374                "This document is not stored using the specified format.",
1375            );
1376            bail!("This document is not stored using the specified format.");
1377        };
1378        if !is_base64_payload_short_dc(val) {
1379            log.error(
1380                "This document is not stored using the specified format.",
1381            );
1382            bail!("This document is not stored using the specified format.");
1383        }
1384        dcs.push(val);
1385    }
1386    decode_dc64_to_bytes(&dcs, log)
1387}
1388
1389pub(crate) fn decode_utf8_dc64_bin_to_bytes(
1390    data: &[u8],
1391    encapsulated: bool,
1392    is_hex: bool,
1393    log: &mut FormatLog,
1394) -> Result<Vec<u8>> {
1395    let raw_bytes = if is_hex {
1396        decode_hex_payload(data, log)?
1397    } else {
1398        data.to_vec()
1399    };
1400
1401    let payload = if encapsulated {
1402        if raw_bytes.len() < 2
1403            || raw_bytes.first() != Some(&0xC3)
1404            || raw_bytes.last() != Some(&0xC4)
1405        {
1406            log.error(
1407                "This document is not stored using the specified format.",
1408            );
1409            bail!("This document is not stored using the specified format.");
1410        }
1411        raw_bytes
1412            .get(1..raw_bytes.len().saturating_sub(1))
1413            .context("encapsulated slice")?
1414    } else {
1415        raw_bytes.as_slice()
1416    };
1417
1418    let mut dcs = Vec::with_capacity(payload.len());
1419    for &byte in payload {
1420        match byte {
1421            0x82..=0xC1 => {
1422                dcs.push(
1423                    u32::from(byte).saturating_sub(0x82).saturating_add(127),
1424                );
1425            }
1426            0xC2 => dcs.push(195),
1427            _ => {
1428                log.error(
1429                    "This document is not stored using the specified format.",
1430                );
1431                bail!(
1432                    "This document is not stored using the specified format."
1433                );
1434            }
1435        }
1436    }
1437    decode_dc64_to_bytes(&dcs, log)
1438}
1439
1440pub(crate) fn encode_dc64_to_core_bytes(
1441    dcs: &[u32],
1442    encapsulated: bool,
1443    is_hex: bool,
1444) -> Result<Vec<u8>> {
1445    let mut out = Vec::with_capacity(dcs.len().saturating_add(2));
1446    if encapsulated {
1447        out.push(0xC3);
1448    }
1449    for &dc in dcs {
1450        let Some((DceSheet::Core, byte)) =
1451            encode_short_dc_in_version(dc, DceVersion::V3_01a)
1452        else {
1453            bail!("Invalid Base64 short Dc {dc}");
1454        };
1455        out.push(byte);
1456    }
1457    if encapsulated {
1458        out.push(0xC4);
1459    }
1460    if is_hex {
1461        Ok(bin2hex(out).to_uppercase().into_bytes())
1462    } else {
1463        Ok(out)
1464    }
1465}
1466
1467fn decode_hex_payload(data: &[u8], log: &mut FormatLog) -> Result<Vec<u8>> {
1468    let hex_str = std::str::from_utf8(data).map_err(|_| {
1469        log.error("This document is not stored using the specified format.");
1470        anyhow!("This document is not stored using the specified format.")
1471    })?;
1472    hex2bin(hex_str).map_err(|_| {
1473        log.error("This document is not stored using the specified format.");
1474        anyhow!("This document is not stored using the specified format.")
1475    })
1476}
1477
1478#[cfg(test)]
1479#[allow(
1480    clippy::panic,
1481    clippy::expect_used,
1482    clippy::unwrap_used,
1483    clippy::unwrap_in_result,
1484    clippy::panic_in_result_fn,
1485    clippy::indexing_slicing,
1486    clippy::arithmetic_side_effects,
1487    reason = "Standard repository test boilerplate"
1488)]
1489mod tests {
1490    use super::*;
1491
1492    #[crate::ctb_test]
1493    fn test_new_converter_3_0a_all_short_dcs_0_to_115() {
1494        for dc in 0..=crate::MAX_DCE_3_0A_SHORT_DC {
1495            if (2..=12).contains(&dc) {
1496                // Short Dcs 2..=12 had no byte mappings in DCE 3.0a (added in 3.01a);
1497                // exporting to 3.0a must log an export warning in FormatLog and omit them.
1498                let mut enc_log = crate::FormatLog::default();
1499                let encoded = crate::converter::encode_dce_preserving_controls(
1500                    &[18, dc, 19],
1501                    "3_0a",
1502                    &mut enc_log,
1503                )
1504                .unwrap();
1505                assert!(
1506                    !enc_log.has_errors() && enc_log.has_warnings(),
1507                    "3_0a encoding of unmapped short Dc {dc} should log a warning: {enc_log:?}"
1508                );
1509                let mut dec_log = crate::FormatLog::default();
1510                let decoded = crate::converter::decode_dce_preserving_controls(
1511                    &encoded,
1512                    "3_0a",
1513                    &mut dec_log,
1514                )
1515                .unwrap();
1516                assert!(!decoded.contains(&dc));
1517                assert!(decoded.contains(&18) && decoded.contains(&19));
1518                continue;
1519            }
1520
1521            for fmt in ["3_0a", "3_0a_raw", "hex_3_0a", "hex_3_0a_raw"] {
1522                let mut enc_log = crate::FormatLog::default();
1523                let encoded = crate::converter::encode_dce_preserving_controls(
1524                    &[dc],
1525                    fmt,
1526                    &mut enc_log,
1527                );
1528                if dc == 113 && !fmt.ends_with("_raw") {
1529                    assert!(encoded.is_err());
1530                    continue;
1531                }
1532                let encoded = encoded.unwrap();
1533                assert!(
1534                    !enc_log.has_errors() && !enc_log.has_warnings(),
1535                    "3_0a ({fmt}) encoding of short Dc {dc} had warnings/errors: {enc_log:?}"
1536                );
1537
1538                let mut dec_log = crate::FormatLog::default();
1539                let decoded = crate::converter::decode_dce_preserving_controls(
1540                    &encoded,
1541                    fmt,
1542                    &mut dec_log,
1543                )
1544                .unwrap();
1545                assert!(
1546                    !dec_log.has_errors() && !dec_log.has_warnings(),
1547                    "3_0a ({fmt}) decoding of short Dc {dc} had warnings/errors: {dec_log:?}"
1548                );
1549                assert!(
1550                    decoded.contains(&dc),
1551                    "3_0a ({fmt}) decoded sequence {decoded:?} did not contain short Dc {dc}"
1552                );
1553
1554                // Re-encoding the decoded sequence must be byte-for-byte idempotent
1555                let mut reenc_log = crate::FormatLog::default();
1556                let reencoded =
1557                    crate::converter::encode_dce_preserving_controls(
1558                        &decoded,
1559                        fmt,
1560                        &mut reenc_log,
1561                    )
1562                    .unwrap();
1563                assert_eq!(
1564                    reencoded, encoded,
1565                    "3_0a ({fmt}) re-encode mismatch for short Dc {dc}"
1566                );
1567            }
1568
1569            // Also verify dc -> 3_0a -> dc roundtrip via converter::dce_convert_with_log
1570            let dc_input = format!("114,{dc},115");
1571            if dc == 113 {
1572                assert!(
1573                    crate::converter::dce_convert_with_log(
1574                        dc_input.as_bytes(),
1575                        "dc",
1576                        "3_0a"
1577                    )
1578                    .is_err()
1579                );
1580                continue;
1581            }
1582            let (dce_bytes, log_out) = crate::converter::dce_convert_with_log(
1583                dc_input.as_bytes(),
1584                "dc",
1585                "3_0a",
1586            )
1587            .unwrap();
1588            assert!(
1589                !log_out.has_errors() && !log_out.has_warnings(),
1590                "dce_convert dc -> 3_0a failed for Dc {dc}: {log_out:?}"
1591            );
1592            let (dc_back, log_in) = crate::converter::dce_convert_with_log(
1593                &dce_bytes, "3_0a", "dc",
1594            )
1595            .unwrap();
1596            assert!(
1597                !log_in.has_errors() && !log_in.has_warnings(),
1598                "dce_convert 3_0a -> dc failed for Dc {dc}: {log_in:?}"
1599            );
1600            assert_eq!(
1601                String::from_utf8(dc_back).unwrap(),
1602                dc_input,
1603                "dc -> 3_0a -> dc mismatch for short Dc {dc}"
1604            );
1605        }
1606    }
1607
1608    #[crate::ctb_test]
1609    fn test_new_converter_3_01a_all_short_dcs_0_to_199_and_base64() {
1610        for dc in 0..=crate::MAX_DCE_3_01A_SHORT_DC {
1611            for fmt in ["3_01a", "3_01a_raw", "hex_3_01a", "hex_3_01a_raw"] {
1612                let mut enc_log = crate::FormatLog::default();
1613                let encoded = crate::converter::encode_dce_preserving_controls(
1614                    &[dc],
1615                    fmt,
1616                    &mut enc_log,
1617                );
1618                if dc == 113 && !fmt.ends_with("_raw") {
1619                    assert!(encoded.is_err());
1620                    continue;
1621                }
1622                let encoded = encoded.unwrap();
1623                assert!(
1624                    !enc_log.has_errors() && !enc_log.has_warnings(),
1625                    "3_01a ({fmt}) encoding of short Dc {dc} had warnings/errors: {enc_log:?}"
1626                );
1627
1628                let mut dec_log = crate::FormatLog::default();
1629                let decoded = crate::converter::decode_dce_preserving_controls(
1630                    &encoded,
1631                    fmt,
1632                    &mut dec_log,
1633                )
1634                .unwrap();
1635                assert!(
1636                    !dec_log.has_errors() && !dec_log.has_warnings(),
1637                    "3_01a ({fmt}) decoding of short Dc {dc} had warnings/errors: {dec_log:?}"
1638                );
1639                assert!(
1640                    decoded.contains(&dc),
1641                    "3_01a ({fmt}) decoded sequence {decoded:?} did not contain short Dc {dc}"
1642                );
1643
1644                let mut reenc_log = crate::FormatLog::default();
1645                let reencoded =
1646                    crate::converter::encode_dce_preserving_controls(
1647                        &decoded,
1648                        fmt,
1649                        &mut reenc_log,
1650                    )
1651                    .unwrap();
1652                assert_eq!(
1653                    reencoded, encoded,
1654                    "3_01a ({fmt}) re-encode mismatch for short Dc {dc}"
1655                );
1656            }
1657
1658            let dc_input = format!("114,{dc},115");
1659            if dc == 113 {
1660                assert!(
1661                    crate::converter::dce_convert_with_log(
1662                        dc_input.as_bytes(),
1663                        "dc",
1664                        "3_01a"
1665                    )
1666                    .is_err()
1667                );
1668                continue;
1669            }
1670            if dc == 191 {
1671                assert!(
1672                    crate::converter::dce_convert_with_log(
1673                        dc_input.as_bytes(),
1674                        "dc",
1675                        "3_01a",
1676                    )
1677                    .is_err()
1678                );
1679                let (repaired, repair_log) =
1680                    crate::converter::dce_convert_with_options(
1681                        dc_input.as_bytes(),
1682                        "dc",
1683                        "utf8",
1684                        true,
1685                    )
1686                    .unwrap();
1687                assert_eq!(repaired, "\u{FFFD}".as_bytes());
1688                assert!(repair_log.has_warnings());
1689                continue;
1690            }
1691            let (dce_bytes, log_out) = crate::converter::dce_convert_with_log(
1692                dc_input.as_bytes(),
1693                "dc",
1694                "3_01a",
1695            )
1696            .unwrap();
1697            assert!(
1698                !log_out.has_errors() && !log_out.has_warnings(),
1699                "dce_convert dc -> 3_01a failed for Dc {dc}: {log_out:?}"
1700            );
1701            let (dc_back, log_in) = crate::converter::dce_convert_with_log(
1702                &dce_bytes, "3_01a", "dc",
1703            )
1704            .unwrap();
1705            assert!(
1706                !log_in.has_errors() && !log_in.has_warnings(),
1707                "dce_convert 3_01a -> dc failed for Dc {dc}: {log_in:?}"
1708            );
1709            assert_eq!(
1710                String::from_utf8(dc_back).unwrap(),
1711                dc_input,
1712                "dc -> 3_01a -> dc mismatch for short Dc {dc}"
1713            );
1714        }
1715
1716        // Verify Base64 'I' (Dc 135) and 'i' (Dc 161) are distinct and roundtrip properly
1717        assert_eq!(crate::converter::base64_char_to_short_dc(b'I'), Some(135));
1718        assert_eq!(crate::converter::base64_char_to_short_dc(b'i'), Some(161));
1719        assert_eq!(crate::converter::short_dc_to_base64_char(135), Some('I'));
1720        assert_eq!(crate::converter::short_dc_to_base64_char(161), Some('i'));
1721
1722        // Payload whose Base64 encoding ("SGkh") contains 'i' (Dc 161) and ("I1 test") -> "STEgdGVzdA==" contains 'I'
1723        let utf8_with_b64_i_and_cap_i =
1724            "Hi! — 🌄 Testing Base64 'i' and 'I' encapsulation";
1725        for b64_fmt in [
1726            "utf8_dc64",
1727            "utf8_dc64_enc",
1728            "utf8_dc64_bin",
1729            "utf8_dc64_bin_hex",
1730            "utf8_dc64_bin_enc",
1731            "utf8_dc64_bin_enc_hex",
1732            "3_01a",
1733            "dce",
1734        ] {
1735            let (encoded, enc_log) = crate::converter::dce_convert_with_log(
1736                utf8_with_b64_i_and_cap_i.as_bytes(),
1737                "utf8",
1738                b64_fmt,
1739            )
1740            .unwrap();
1741            assert!(!enc_log.has_errors() && !enc_log.has_warnings());
1742            let (decoded, dec_log) = crate::converter::dce_convert_with_log(
1743                &encoded, b64_fmt, "utf8",
1744            )
1745            .unwrap();
1746            assert!(!dec_log.has_errors() && !dec_log.has_warnings());
1747            assert_eq!(
1748                String::from_utf8(decoded).unwrap(),
1749                utf8_with_b64_i_and_cap_i,
1750                "UTF-8 roundtrip through {b64_fmt} failed"
1751            );
1752        }
1753    }
1754
1755    #[crate::ctb_test]
1756    fn test_new_converter_3_02a_stubbed_returns_error() {
1757        assert_eq!(crate::DceVersion::V3_02a.version_byte(), None);
1758        assert!(crate::DceVersion::V3_02a.supports_short_dc(202));
1759        assert!(!crate::DceVersion::V3_02a.supports_short_dc(205));
1760
1761        for fmt in [
1762            "3_02a",
1763            "dce_3_02a",
1764            "3_02a_raw",
1765            "dce_3_02a_raw",
1766            "hex_3_02a",
1767            "3_02a_hex",
1768            "dce_3_02a_hex",
1769            "hex_3_02a_raw",
1770            "3_02a_raw_hex",
1771            "dce_3_02a_raw_hex",
1772        ] {
1773            let mut enc_log = crate::FormatLog::default();
1774            assert!(
1775                crate::converter::encode_dce_preserving_controls(
1776                    &[50],
1777                    fmt,
1778                    &mut enc_log,
1779                )
1780                .is_err(),
1781                "{fmt} encode should return an error while 3.02a is stubbed"
1782            );
1783            assert!(enc_log.has_errors());
1784
1785            let mut dec_log = crate::FormatLog::default();
1786            let sample_input = if fmt.contains("hex") {
1787                &b"804181"[..]
1788            } else {
1789                &b"\x80A\x81"[..]
1790            };
1791            assert!(
1792                crate::converter::decode_dce_preserving_controls(
1793                    sample_input,
1794                    fmt,
1795                    &mut dec_log,
1796                )
1797                .is_err(),
1798                "{fmt} decode should return an error while 3.02a is stubbed"
1799            );
1800            assert!(dec_log.has_errors());
1801
1802            assert!(
1803                crate::converter::dce_convert_with_log(
1804                    b"114,50,115",
1805                    "dc",
1806                    fmt,
1807                )
1808                .is_err(),
1809                "dce_convert dc -> {fmt} should return an error while 3.02a is stubbed"
1810            );
1811            assert!(
1812                crate::converter::dce_convert_with_log(
1813                    sample_input,
1814                    fmt,
1815                    "dc",
1816                )
1817                .is_err(),
1818                "dce_convert {fmt} -> dc should return an error while 3.02a is stubbed"
1819            );
1820        }
1821    }
1822}