ctb_formats_dcstring/
dc_mixed.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//! Mixed-mode Document Character String (`DcMstring`, `DcMstr`) for the `DcMixed`
21//! format (`.dcmm`).
22//!
23//! Provides borrowed and owned types for DcTF mixed-mode data containing
24//! embedded binary payloads with direct (non-base64) storage and
25//! optional SHA-256 integrity verification.
26
27#[allow(
28    unused_imports,
29    clippy::wildcard_imports,
30    reason = "Standard workspace module prelude"
31)]
32use crate::utilities::*;
33
34use std::borrow::Borrow;
35use std::fmt;
36use std::ops::{Deref, DerefMut, Index, RangeFull};
37
38use ctb_formats_dctf::{
39    decode_dctf_buf, decode_utf_8e_128_buf, determine_dctf_error_len,
40    determine_utf_8e_128_error_len, encode_dctf_buf, encode_utf_8e_128_buf,
41};
42use sha2::{Digest, Sha256};
43
44use crate::{DcChar, DcStr, DcString, DcUtfError};
45use ctb_formats_dcdata::dc_char::DcCharExt;
46use ctb_formats_dcdata::syntax::DcRole;
47pub use ctb_formats_utilities::FormatLog;
48use ctb_utilities::format_support::SupportedHashFormat;
49
50/// Magic header bytes for the `DcMixed` format (`DcMM\0`).
51pub const DCMM_MAGIC: [u8; 5] = [b'D', b'c', b'M', b'M', 0];
52
53/// Binary equivalent of `DcMixed2` format UUID `b0327a84-b745-492c-b39d-77c2827e3a6f`.
54pub const DCMM_UUID: [u8; 16] = [
55    0xb0, 0x32, 0x7a, 0x84, 0xb7, 0x45, 0x49, 0x2c, 0xb3, 0x9d, 0x77, 0xc2,
56    0x82, 0x7e, 0x3a, 0x6f,
57];
58
59/// Binary equivalent of legacy `DcMixed1` format UUID `d5ab819e-9b8e-4d61-adbc-933e8851e79a`.
60pub const DCMM_UUID_V1: [u8; 16] = [
61    0xd5, 0xab, 0x81, 0x9e, 0x9b, 0x8e, 0x4d, 0x61, 0xad, 0xbc, 0x93, 0x3e,
62    0x88, 0x51, 0xe7, 0x9a,
63];
64
65/// Total length of the `DcMixed` document header (21 bytes).
66pub const DCMM_HEADER_LEN: usize = 21;
67
68/// Type byte indicating direct binary encapsulation (unchecksummed).
69pub const TYPE_BINARY: u8 = 0;
70
71/// Direct binary payload with a length-delimited DcTF metadata block.
72pub const TYPE_BINARY_METADATA: u8 = 2;
73
74/// Type byte indicating direct binary encapsulation with a 32-byte SHA-256
75/// checksum.
76pub const TYPE_BINARY_SHA256: u8 = 3;
77
78pub use ctb_formats_dcdata::dc::{
79    DC_END_ENCAPSULATION_BINARY, DC_START_ENCAPSULATION_BINARY,
80};
81
82/// Pre-computed DcTF byte sequence for `Dc 203` (`SHORT_DC_REGION_START + 203`).
83pub const DC_203_BYTES: [u8; 4] = [0xF4, 0x90, 0x83, 0x8B];
84
85/// Pre-computed legacy UTF-8e-128 (`DcUtf`) byte sequence for `Dc 203` (`SHORT_DC_REGION_START + 203`).
86pub const DC_203_BYTES_V1: [u8; 6] = [0xFF, 0x84, 0x84, 0x90, 0x83, 0x8B];
87
88const ENCAP_TYPE_IDX: usize = DC_203_BYTES.len();
89const ENCAP_SIZE_START: usize = ENCAP_TYPE_IDX + 1;
90const ENCAP_SIZE_END: usize = ENCAP_SIZE_START + 16;
91const ENCAP_META_LEN_END: usize = ENCAP_SIZE_END + 16;
92const ENCAP_SHA256_END: usize = ENCAP_SIZE_END + 32;
93
94/// Errors encountered while parsing or validating `DcMixed` / `DcMstring` data.
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub enum DcMixedError {
97    /// Invalid typed encapsulation metadata, length, or checksum.
98    InvalidMetadata {
99        /// Byte offset of the metadata block.
100        offset: usize,
101        /// Explanation of the failure.
102        message: String,
103    },
104    /// Document is shorter than the 21-byte header.
105    TooShort {
106        /// Actual length of the slice in bytes.
107        len: usize,
108    },
109    /// Magic header does not match `DcMM\0`.
110    InvalidMagic {
111        /// Found magic bytes.
112        found: [u8; 5],
113    },
114    /// UUID does not match `d5ab819e-9b8e-4d61-adbc-933e8851e79a`.
115    InvalidUuid {
116        /// Found UUID bytes.
117        found: [u8; 16],
118    },
119    /// Encapsulation header or payload is truncated before expected length.
120    TruncatedEncapsulation {
121        /// Byte offset in stream where encapsulation starts.
122        offset: usize,
123        /// Expected minimum byte count from offset.
124        expected: usize,
125        /// Available byte count from offset.
126        available: usize,
127    },
128    /// Encapsulation type byte is invalid or reserved.
129    InvalidEncapsulationType {
130        /// Byte offset of the type byte in stream.
131        offset: usize,
132        /// The invalid type byte found.
133        type_byte: u8,
134    },
135    /// Retired type 1 or 4 has ambiguous legacy DcUtf semantics. I think they were meant to indicate that the stored data is to be *interpreted* as DcUtf, not that it was *stored* as DcUtf, but the implementation used them to store data as DcUtf (invalid Dc 203 syntax). Since indicating the type of stored data is now possible using the new type byte 2, the original use case of these is satisfied. As they were never used, they are reported as an error if encountered.
136    UnsupportedLegacyType {
137        /// Byte offset of the type byte.
138        offset: usize,
139        /// Retired type byte.
140        type_byte: u8,
141    },
142    /// Encapsulated payload size exceeds addressable memory size (`usize`).
143    SizeOverflow {
144        /// Byte offset where encapsulation starts.
145        offset: usize,
146        /// Size specified in header.
147        size: u128,
148    },
149    /// SHA-256 checksum verification failed for an encapsulated payload.
150    ChecksumMismatch {
151        /// Byte offset where encapsulation starts.
152        offset: usize,
153        /// Expected SHA-256 digest from header.
154        expected: [u8; 32],
155        /// Actual computed SHA-256 digest.
156        actual: [u8; 32],
157    },
158    /// Malformed or non-canonical UTF-8e-128 sequence encountered.
159    InvalidUtf8e128 {
160        /// Byte offset where invalid sequence begins.
161        offset: usize,
162        /// Underlying UTF-8e-128 error.
163        source: DcUtfError,
164    },
165}
166
167impl fmt::Display for DcMixedError {
168    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169        match self {
170            Self::InvalidMetadata { offset, message } => {
171                write!(
172                    f,
173                    "Invalid encapsulation metadata at offset {offset}: {message}"
174                )
175            }
176            Self::TooShort { len } => {
177                write!(
178                    f,
179                    "DcMixed document too short ({len} bytes, minimum 21 bytes)"
180                )
181            }
182            Self::InvalidMagic { found } => {
183                write!(f, "Invalid DcMixed magic header: {found:?}")
184            }
185            Self::InvalidUuid { found } => {
186                write!(f, "Invalid DcMixed UUID header: {found:?}")
187            }
188            Self::TruncatedEncapsulation {
189                offset,
190                expected,
191                available,
192            } => {
193                write!(
194                    f,
195                    "Truncated encapsulation at offset {offset}: expected {expected} bytes, available {available}"
196                )
197            }
198            Self::InvalidEncapsulationType { offset, type_byte } => {
199                write!(
200                    f,
201                    "Invalid encapsulation type {type_byte} at offset {offset}"
202                )
203            }
204            Self::UnsupportedLegacyType { offset, type_byte } => {
205                write!(
206                    f,
207                    "Unsupported legacy DcMixed type {type_byte} at offset {offset}: ambiguous DcUtf semantics; use type 2 with declared type metadata"
208                )
209            }
210            Self::SizeOverflow { offset, size } => {
211                write!(
212                    f,
213                    "Encapsulation size {size} exceeds addressable memory at offset {offset}"
214                )
215            }
216            Self::ChecksumMismatch {
217                offset,
218                expected,
219                actual,
220            } => {
221                write!(
222                    f,
223                    "SHA-256 checksum mismatch at offset {offset}: expected {expected:?}, actual {actual:?}"
224                )
225            }
226            Self::InvalidUtf8e128 { offset, source } => {
227                write!(
228                    f,
229                    "Invalid UTF-8e-128 sequence at offset {offset}: {source}"
230                )
231            }
232        }
233    }
234}
235
236impl std::error::Error for DcMixedError {}
237
238/// A segment of data in a `DcMixed` document.
239#[derive(Clone, PartialEq, Eq, Debug)]
240pub enum DcMixed<'a> {
241    /// Normal Document Character / Unicode text.
242    Text(&'a DcStr),
243    /// Direct binary encapsulated data with optional SHA-256 digest.
244    Binary {
245        /// Raw binary slice.
246        data: &'a [u8],
247        /// Optional 32-byte SHA-256 digest.
248        sha256: Option<[u8; 32]>,
249    },
250    /// Direct binary payload with optional type and checksum encoded as DcUtf.
251    BinaryWithMetadata {
252        /// Raw binary slice.
253        data: &'a [u8],
254        /// DcUtf metadata containing `[type]? [checksum]?`.
255        metadata: &'a DcStr,
256    },
257}
258
259impl<'a> DcMixed<'a> {
260    /// Creates a borrowed `DcMixed::Text` segment.
261    #[must_use]
262    pub const fn text(s: &'a DcStr) -> Self {
263        Self::Text(s)
264    }
265
266    /// Creates an unchecksummed binary segment (`TYPE_BINARY`).
267    #[must_use]
268    pub const fn binary(data: &'a [u8]) -> Self {
269        Self::Binary { data, sha256: None }
270    }
271
272    /// Creates a SHA-256 checksummed binary segment (`TYPE_BINARY_SHA256`).
273    #[must_use]
274    pub const fn binary_sha256(data: &'a [u8], sha256: [u8; 32]) -> Self {
275        Self::Binary {
276            data,
277            sha256: Some(sha256),
278        }
279    }
280
281    /// Returns the text slice if this segment is `Text`.
282    #[must_use]
283    pub fn as_text(&self) -> Option<&'a DcStr> {
284        match self {
285            Self::Text(s) => Some(*s),
286            _ => None,
287        }
288    }
289
290    /// Returns the binary slice if this segment is `Binary`.
291    #[must_use]
292    pub fn as_binary(&self) -> Option<&'a [u8]> {
293        match self {
294            Self::Binary { data, .. }
295            | Self::BinaryWithMetadata { data, .. } => Some(*data),
296            _ => None,
297        }
298    }
299
300    /// Returns the legacy fixed-header SHA-256 checksum, if present.
301    ///
302    /// Type-2 checksums are retained in the segment's DcUtf metadata instead.
303    #[must_use]
304    pub const fn sha256(&self) -> Option<[u8; 32]> {
305        match self {
306            Self::Text(_) | Self::BinaryWithMetadata { .. } => None,
307            Self::Binary { sha256, .. } => *sha256,
308        }
309    }
310
311    /// Verifies the SHA-256 checksum against payload data.
312    ///
313    /// Returns `true` if checksum matches, or `true` if no checksum is attached.
314    #[must_use]
315    pub fn verify_checksum(&self) -> bool {
316        match self {
317            Self::Text(_) => true,
318            Self::BinaryWithMetadata { data, metadata } => {
319                crate::encapsulation::validate_metadata(metadata, data).is_ok()
320            }
321            Self::Binary { data, sha256 } => {
322                if let Some(expected) = sha256 {
323                    let actual = Sha256::digest(data);
324                    actual.as_slice() == expected.as_slice()
325                } else {
326                    true
327                }
328            }
329        }
330    }
331}
332
333/// Type alias for `DcMixed`.
334pub type DcMixedChunk<'a> = DcMixed<'a>;
335
336/// An owned segment of data in a `DcMixed` document.
337#[derive(Clone, PartialEq, Eq, Debug)]
338pub enum DcMixedOwned {
339    /// Normal Document Character / Unicode text.
340    Text(DcString),
341    /// Direct binary encapsulated data with optional SHA-256 digest.
342    Binary {
343        /// Raw binary data.
344        data: Vec<u8>,
345        /// Optional 32-byte SHA-256 digest.
346        sha256: Option<[u8; 32]>,
347    },
348    /// Direct binary payload with optional type and checksum encoded as DcUtf.
349    BinaryWithMetadata {
350        /// Raw binary bytes.
351        data: Vec<u8>,
352        /// DcUtf metadata containing `[type]? [checksum]?`.
353        metadata: DcString,
354    },
355}
356
357/// A borrowed slice representing valid `DcMixed` format data (`.dcmm`).  Analogous to `DcStr` and Rust's `str`.
358#[repr(transparent)]
359#[derive(Eq, PartialEq, Ord, PartialOrd, Hash)]
360pub struct DcMstr {
361    pub(crate) inner: [u8],
362}
363
364impl DcMstr {
365    /// Validates the provided byte slice as valid `DcMixed` and wraps it as a `&DcMstr`.
366    ///
367    /// # Errors
368    /// Returns `DcMixedError` if the byte slice does not conform to the `DcMixed` specification.
369    pub fn from_bytes(bytes: &[u8]) -> Result<&Self, DcMixedError> {
370        Self::from_bytes_with_policy(
371            bytes,
372            &crate::DcProjectionPolicy::strict(),
373        )
374    }
375
376    pub(crate) fn from_bytes_with_policy<'a>(
377        bytes: &'a [u8],
378        policy: &crate::DcProjectionPolicy,
379    ) -> Result<&'a Self, DcMixedError> {
380        validate_dcmst_with_policy(bytes, policy)?;
381        #[expect(
382            unsafe_code,
383            reason = "DcMstr is #[repr(transparent)] around [u8] and bytes have been fully validated"
384        )]
385        // Safety: bytes have been validated as conforming to DcMixed format.
386        Ok(unsafe { Self::from_bytes_unchecked(bytes) })
387    }
388
389    /// Creates a `&DcMstr` from a byte slice without validation.
390    ///
391    /// # Safety
392    /// The caller must ensure that `bytes` contains valid `DcMixed` data.
393    #[must_use]
394    #[expect(
395        unsafe_code,
396        reason = "DcMstr is #[repr(transparent)] around [u8], so &[u8] and &DcMstr have identical layout"
397    )]
398    pub const unsafe fn from_bytes_unchecked(bytes: &[u8]) -> &Self {
399        // Safety: Caller guarantees valid DcMixed data and DcMstr is #[repr(transparent)] around [u8].
400        unsafe { std::mem::transmute::<&[u8], &Self>(bytes) }
401    }
402
403    /// Validates the mutable byte slice as valid `DcMixed` and wraps it as a `&mut DcMstr`.
404    ///
405    /// # Errors
406    /// Returns `DcMixedError` if the slice does not conform to `DcMixed`.
407    pub fn from_bytes_mut(bytes: &mut [u8]) -> Result<&mut Self, DcMixedError> {
408        validate_dcmst(bytes)?;
409        #[expect(
410            unsafe_code,
411            reason = "DcMstr is #[repr(transparent)] around [u8] and bytes have been fully validated"
412        )]
413        // Safety: bytes have been validated as conforming to DcMixed format.
414        Ok(unsafe { Self::from_bytes_unchecked_mut(bytes) })
415    }
416
417    /// Creates a `&mut DcMstr` without validation.
418    ///
419    /// # Safety
420    /// The caller must ensure `bytes` contains valid `DcMixed` data.
421    #[expect(
422        unsafe_code,
423        clippy::transmute_ptr_to_ptr,
424        reason = "DcMstr is #[repr(transparent)] around [u8], so &mut [u8] and &mut DcMstr have identical layout; pointer casts require as which is denied by clippy"
425    )]
426    pub unsafe fn from_bytes_unchecked_mut(bytes: &mut [u8]) -> &mut Self {
427        // Safety: Caller guarantees valid DcMixed data and DcMstr is #[repr(transparent)] around [u8].
428        unsafe { std::mem::transmute::<&mut [u8], &mut Self>(bytes) }
429    }
430
431    /// Returns the underlying byte slice (including the 21-byte header).
432    #[must_use]
433    pub const fn as_bytes(&self) -> &[u8] {
434        &self.inner
435    }
436
437    /// Returns the total byte length of the slice (including the 21-byte header).
438    #[must_use]
439    pub const fn len(&self) -> usize {
440        self.inner.len()
441    }
442
443    /// Returns `true` if the document has no payload data (only contains the 21-byte header).
444    #[must_use]
445    pub const fn is_empty(&self) -> bool {
446        self.inner.len() <= DCMM_HEADER_LEN
447    }
448
449    /// Returns the 21-byte document header (`DcMM\0` + UUID).
450    #[must_use]
451    pub fn header(&self) -> &[u8] {
452        #[expect(
453            clippy::expect_used,
454            reason = "A valid DcMstr is guaranteed to be at least DCMM_HEADER_LEN (21 bytes)"
455        )]
456        self.inner
457            .get(..DCMM_HEADER_LEN)
458            .expect("DcMstr is guaranteed >= 21 bytes")
459    }
460
461    /// Returns the slice of payload bytes occurring after the 21-byte header.
462    #[must_use]
463    pub fn payload_bytes(&self) -> &[u8] {
464        #[expect(
465            clippy::expect_used,
466            reason = "A valid DcMstr is guaranteed to be at least DCMM_HEADER_LEN (21 bytes)"
467        )]
468        self.inner
469            .get(DCMM_HEADER_LEN..)
470            .expect("DcMstr is guaranteed >= 21 bytes")
471    }
472
473    /// Returns the length in bytes of the payload after the 21-byte header.
474    #[must_use]
475    pub fn payload_len(&self) -> usize {
476        self.inner.len().saturating_sub(DCMM_HEADER_LEN)
477    }
478
479    /// Returns an iterator yielding `DcMixed` chunks (text segments and encapsulated payloads).
480    #[must_use]
481    pub fn chunks(&self) -> DcMixedChunks<'_> {
482        DcMixedChunks {
483            slice: self.payload_bytes(),
484        }
485    }
486
487    /// Converts this `DcMstr` into a standard `DcString` (DcUtf) representation.
488    ///
489    /// Binary payloads are converted into base64 characters between Dc 203 and
490    /// Dc 204, with byte length and any declared type or checksum.
491    ///
492    /// # Errors
493    /// Returns error if base64 encoding fails.
494    pub fn to_dc_string(&self) -> Result<DcString> {
495        self.to_dc_string_with_policy(&crate::DcProjectionPolicy::strict())
496    }
497
498    /// Converts this `DcMstr` into a standard `DcString` (DcUtf) representation
499    /// using the provided [`crate::DcProjectionPolicy`].
500    pub fn to_dc_string_with_policy(
501        &self,
502        policy: &crate::DcProjectionPolicy,
503    ) -> Result<DcString> {
504        self.to_dc_string_with_policy_and_resolver(
505            policy,
506            ctb_formats_dcdata::syntax::default_syntax_resolver().as_ref(),
507        )
508    }
509
510    /// Converts this `DcMstr` into a standard `DcString` (DcUtf) representation
511    /// using the provided [`crate::DcProjectionPolicy`] and [`crate::SyntaxRuleResolver`].
512    pub fn to_dc_string_with_policy_and_resolver(
513        &self,
514        policy: &crate::DcProjectionPolicy,
515        resolver: &dyn crate::SyntaxRuleResolver,
516    ) -> Result<DcString> {
517        let mut out = DcString::new();
518        for chunk in self.chunks() {
519            match chunk {
520                DcMixed::Text(text) => {
521                    out.push_dc_str(text);
522                }
523                DcMixed::Binary { data, sha256 } => {
524                    let metadata = if let Some(digest) = sha256 {
525                        crate::encapsulation::checksum_text(
526                            ctb_utilities::format_id::DC_SHA256,
527                            &digest,
528                        )?
529                    } else {
530                        DcString::new()
531                    };
532                    crate::encapsulation::write_text_with_policy_and_resolver(
533                        &mut out, data, &metadata, policy, resolver,
534                    )?;
535                }
536                DcMixed::BinaryWithMetadata { data, metadata } => {
537                    crate::encapsulation::write_text_with_policy_and_resolver(
538                        &mut out, data, metadata, policy, resolver,
539                    )?;
540                }
541            }
542        }
543        Ok(out)
544    }
545
546    /// Converts this `DcMstr` into a token stream of native `u128` character
547    /// identifiers suitable for syntax parsing and validation.
548    ///
549    /// # Errors
550    /// Returns an error if any character or payload cannot be converted.
551    pub fn to_dc_tokens(&self) -> Result<Vec<u128>> {
552        let dc_str = self.to_dc_string()?;
553        Ok(dc_str.chars().map(ctb_utilities::DcChar::to_u128).collect())
554    }
555}
556
557impl PartialEq<str> for DcMstr {
558    #[inline]
559    fn eq(&self, other: &str) -> bool {
560        self == DcMstring::from(other).as_mstr()
561    }
562}
563
564impl PartialEq<&str> for DcMstr {
565    #[inline]
566    fn eq(&self, other: &&str) -> bool {
567        self == DcMstring::from(*other).as_mstr()
568    }
569}
570
571impl PartialEq<DcStr> for DcMstr {
572    #[inline]
573    fn eq(&self, other: &DcStr) -> bool {
574        DcMstring::from_dc_str(other).is_ok_and(|mst| self == mst.as_mstr())
575    }
576}
577
578impl AsRef<[u8]> for DcMstr {
579    #[inline]
580    fn as_ref(&self) -> &[u8] {
581        &self.inner
582    }
583}
584
585impl AsRef<DcMstr> for DcMstr {
586    #[inline]
587    fn as_ref(&self) -> &Self {
588        self
589    }
590}
591
592impl ToOwned for DcMstr {
593    type Owned = DcMstring;
594
595    fn to_owned(&self) -> Self::Owned {
596        DcMstring {
597            inner: self.inner.to_vec(),
598        }
599    }
600}
601
602impl Index<RangeFull> for DcMstr {
603    type Output = Self;
604
605    #[inline]
606    fn index(&self, _: RangeFull) -> &Self::Output {
607        self
608    }
609}
610
611impl fmt::Display for DcMstr {
612    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
613        for chunk in self.chunks() {
614            match chunk {
615                DcMixed::Text(t) => write!(f, "{t}")?,
616                DcMixed::Binary { data, sha256 } => {
617                    if sha256.is_some() {
618                        write!(
619                            f,
620                            "[Binary blob: {} bytes, SHA-256 verified]",
621                            data.len()
622                        )?;
623                    } else {
624                        write!(f, "[Binary blob: {} bytes]", data.len())?;
625                    }
626                }
627                DcMixed::BinaryWithMetadata { data, .. } => {
628                    write!(f, "[Typed binary blob: {} bytes]", data.len())?;
629                }
630            }
631        }
632        Ok(())
633    }
634}
635
636impl fmt::Debug for DcMstr {
637    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
638        write!(f, "DcMstr(\"{self}\")")
639    }
640}
641
642/// An owned, growable buffer containing valid `DcMixed` (Dc mixed mode) format data (`.dcmm`). Analogous to `DcString` and Rust's `String`.
643#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
644pub struct DcMstring {
645    pub(crate) inner: Vec<u8>,
646}
647
648impl Default for DcMstring {
649    fn default() -> Self {
650        Self::new()
651    }
652}
653
654impl DcMstring {
655    /// Appends through the same encoder used for direct streaming output.
656    pub fn writer(&mut self) -> crate::DcWriter<'_> {
657        crate::DcWriter::new(&mut self.inner)
658    }
659
660    /// Creates a new, empty `DcMstring` initialized with the standard 21-byte header.
661    #[must_use]
662    pub fn new() -> Self {
663        let mut inner = Vec::with_capacity(DCMM_HEADER_LEN);
664        inner.extend_from_slice(&DCMM_MAGIC);
665        inner.extend_from_slice(&DCMM_UUID);
666        Self { inner }
667    }
668
669    /// Creates an empty `DcMstring` with pre-allocated capacity in bytes.
670    #[must_use]
671    pub fn with_capacity(capacity: usize) -> Self {
672        let cap = capacity.max(DCMM_HEADER_LEN);
673        let mut inner = Vec::with_capacity(cap);
674        inner.extend_from_slice(&DCMM_MAGIC);
675        inner.extend_from_slice(&DCMM_UUID);
676        Self { inner }
677    }
678
679    /// Validates an owned `Vec<u8>` as `DcMixed` and wraps it in `DcMstring`.
680    ///
681    /// # Errors
682    /// Returns `DcMixedError` if the bytes do not conform to the `DcMixed` specification.
683    pub fn from_bytes(bytes: Vec<u8>) -> Result<Self, DcMixedError> {
684        validate_dcmst(&bytes)?;
685        Ok(Self { inner: bytes })
686    }
687
688    /// Validates an owned `Vec<u8>` as `DcMixed` using `policy` and wraps it in `DcMstring`.
689    ///
690    /// # Errors
691    /// Returns `DcMixedError` if the bytes do not conform to the `DcMixed` specification.
692    pub fn from_bytes_with_policy(
693        bytes: Vec<u8>,
694        policy: &crate::DcProjectionPolicy,
695    ) -> Result<Self, DcMixedError> {
696        let _ = DcMstr::from_bytes_with_policy(&bytes, policy)?;
697        Ok(Self { inner: bytes })
698    }
699
700    /// Validates a borrowed `&[u8]` as `DcMixed` and creates an owned `DcMstring`.
701    ///
702    /// # Errors
703    /// Returns `DcMixedError` if the slice does not conform to the `DcMixed` specification.
704    pub fn from_slice(bytes: &[u8]) -> Result<Self, DcMixedError> {
705        validate_dcmst(bytes)?;
706        Ok(Self {
707            inner: bytes.to_vec(),
708        })
709    }
710
711    /// Validates a borrowed `&[u8]` as `DcMixed` using `policy` and creates an owned `DcMstring`.
712    ///
713    /// # Errors
714    /// Returns `DcMixedError` if the slice does not conform to the `DcMixed` specification.
715    pub fn from_slice_with_policy(
716        bytes: &[u8],
717        policy: &crate::DcProjectionPolicy,
718    ) -> Result<Self, DcMixedError> {
719        let _ = DcMstr::from_bytes_with_policy(bytes, policy)?;
720        Ok(Self {
721            inner: bytes.to_vec(),
722        })
723    }
724
725    /// Wraps a `Vec<u8>` as `DcMstring` without validation.
726    ///
727    /// # Safety
728    /// Caller must ensure `bytes` contains valid `DcMixed` format data.
729    #[must_use]
730    #[expect(
731        unsafe_code,
732        reason = "Caller guarantees bytes are valid DcMixed format"
733    )]
734    pub const unsafe fn from_bytes_unchecked(bytes: Vec<u8>) -> Self {
735        Self { inner: bytes }
736    }
737
738    /// Converts a standard `DcStr` (DcUtf) into a `DcMstring` document.
739    ///
740    /// Dc 203 regions contain an optional type, decoded byte length, checksum,
741    /// and base64 payload. They are stored as direct type-2 binary runs.
742    ///
743    /// # Errors
744    /// Returns an error for malformed encapsulations or invalid lengths and
745    /// checksums. Base64 spelling and framing may be normalized.
746    pub fn from_dc_str(s: &DcStr) -> Result<Self> {
747        Self::from_dc_str_with_policy(s, &crate::DcProjectionPolicy::strict())
748    }
749
750    /// Converts a standard `DcStr` (DcUtf) into a `DcMstring` document using
751    /// the provided [`crate::DcProjectionPolicy`].
752    pub fn from_dc_str_with_policy(
753        s: &DcStr,
754        policy: &crate::DcProjectionPolicy,
755    ) -> Result<Self> {
756        Self::from_dc_str_with_policy_and_resolver(
757            s,
758            policy,
759            ctb_formats_dcdata::syntax::default_syntax_resolver().as_ref(),
760        )
761    }
762
763    /// Converts a standard `DcStr` (DcUtf) into a `DcMstring` document using
764    /// the provided [`crate::DcProjectionPolicy`] and [`crate::SyntaxRuleResolver`].
765    pub fn from_dc_str_with_policy_and_resolver(
766        s: &DcStr,
767        policy: &crate::DcProjectionPolicy,
768        resolver: &dyn crate::SyntaxRuleResolver,
769    ) -> Result<Self> {
770        let mut mst = Self::new();
771        let mut offset = 0usize;
772        let mut escaped = false;
773        while offset < s.len() {
774            let remaining = s
775                .get(offset..)
776                .context("Invalid DcUtf conversion boundary")?;
777            let (val, char_len) = match decode_dctf_buf(remaining.as_ref()) {
778                Some(res) => res,
779                None => anyhow::bail!("Missing Dc character"),
780            };
781            let ch = DcChar(val);
782            if escaped {
783                escaped = false;
784                mst.push_char(ch);
785                offset = offset.saturating_add(char_len);
786                continue;
787            }
788            if ch.fills_role_with(DcRole::Escape, resolver) {
789                escaped = true;
790                mst.push_char(ch);
791                offset = offset.saturating_add(char_len);
792                continue;
793            }
794            if ch.fills_role_with(DcRole::StartEncapsulationBinary, resolver) {
795                let is_textual_encap = remaining
796                    .as_bytes()
797                    .get(char_len..)
798                    .and_then(decode_dctf_buf)
799                    .is_some_and(|(next_val, _)| {
800                        is_textual_encapsulation_follower(
801                            DcChar(next_val),
802                            resolver,
803                        )
804                    });
805                if is_textual_encap {
806                    let (metadata, data, consumed) =
807                        crate::encapsulation::parse_text_with_policy_and_resolver(
808                            remaining, policy, resolver,
809                        )?;
810                    mst.push_binary_with_metadata_policy_and_resolver(
811                        &data, &metadata, policy, resolver,
812                    )?;
813                    offset = offset.saturating_add(consumed);
814                } else {
815                    mst.push_char(ch);
816                    offset = offset.saturating_add(char_len);
817                }
818            } else {
819                mst.push_char(ch);
820                offset = offset.saturating_add(char_len);
821            }
822        }
823        Ok(mst)
824    }
825
826    /// Converts a standard `DcString` (DcUtf) into a `DcMstring` document.
827    pub fn from_dc_string(s: &DcString) -> Result<Self> {
828        Self::from_dc_str(s)
829    }
830
831    /// Converts a standard `DcString` (DcUtf) into a `DcMstring` document using
832    /// the provided [`crate::DcProjectionPolicy`].
833    pub fn from_dc_string_with_policy(
834        s: &DcString,
835        policy: &crate::DcProjectionPolicy,
836    ) -> Result<Self> {
837        Self::from_dc_str_with_policy(s, policy)
838    }
839
840    /// Converts this `DcMstring` into a standard `DcString` (DcUtf) representation.
841    pub fn to_dc_string(&self) -> Result<DcString> {
842        DcMstr::to_dc_string(self)
843    }
844
845    /// Converts this `DcMstring` into a standard `DcString` (DcUtf) representation
846    /// using the provided [`crate::DcProjectionPolicy`].
847    pub fn to_dc_string_with_policy(
848        &self,
849        policy: &crate::DcProjectionPolicy,
850    ) -> Result<DcString> {
851        DcMstr::to_dc_string_with_policy(self, policy)
852    }
853
854    /// Borrows this `DcMstring` as a `&DcMstr` slice.
855    #[inline]
856    #[must_use]
857    pub fn as_mstr(&self) -> &DcMstr {
858        self
859    }
860
861    /// Consumes this `DcMstring` and returns the underlying byte vector.
862    #[must_use]
863    pub fn into_bytes(self) -> Vec<u8> {
864        self.inner
865    }
866
867    /// Appends a standard UTF-8 string slice as text.
868    pub fn push_str(&mut self, s: &str) {
869        self.inner.extend_from_slice(s.as_bytes());
870    }
871
872    /// Appends a `DcStr` slice as text.
873    pub fn push_dc_str(&mut self, s: &DcStr) {
874        self.inner.extend_from_slice(s.as_bytes());
875    }
876
877    /// Appends a single character (`DcChar` or `char`) as text.
878    pub fn push_char(&mut self, ch: impl Into<DcChar>) {
879        let dc = ch.into();
880        let mut buf = [0u8; 24];
881        let n = encode_dctf_buf(&mut buf, dc.0);
882        if let Some(slice) = buf.get(..n) {
883            self.inner.extend_from_slice(slice);
884        }
885    }
886
887    /// Appends a type-2 binary payload with an empty metadata block.
888    pub fn push_binary(&mut self, data: &[u8]) {
889        #[expect(
890            clippy::expect_used,
891            reason = "usize is at most 64 bits and always fits into u64 on supported architectures"
892        )]
893        let len_u64 = u64::try_from(data.len()).expect("usize fits into u64");
894        self.write_encapsulation_header(TYPE_BINARY_METADATA, len_u64, None);
895        self.inner.extend_from_slice(&0u128.to_be_bytes());
896        self.inner.extend_from_slice(data);
897    }
898
899    /// Appends binary data with `[type]? [checksum]?` DcUtf metadata.
900    ///
901    /// # Errors
902    /// Returns an error for invalid metadata or a mismatched checksum.
903    pub fn push_binary_with_metadata(
904        &mut self,
905        data: &[u8],
906        metadata: &DcStr,
907    ) -> Result<()> {
908        self.writer().push_binary_with_metadata(data, metadata)
909    }
910
911    /// Appends binary data with `[type]? [checksum]?` DcUtf metadata using the
912    /// provided [`crate::DcProjectionPolicy`].
913    pub fn push_binary_with_metadata_and_policy(
914        &mut self,
915        data: &[u8],
916        metadata: &DcStr,
917        policy: &crate::DcProjectionPolicy,
918    ) -> Result<()> {
919        self.writer()
920            .push_binary_with_metadata_and_policy(data, metadata, policy)
921    }
922
923    /// Appends binary data with `[type]? [checksum]?` DcUtf metadata using the
924    /// provided [`crate::DcProjectionPolicy`] and [`crate::SyntaxRuleResolver`].
925    pub fn push_binary_with_metadata_policy_and_resolver(
926        &mut self,
927        data: &[u8],
928        metadata: &DcStr,
929        policy: &crate::DcProjectionPolicy,
930        resolver: &dyn crate::SyntaxRuleResolver,
931    ) -> Result<()> {
932        self.writer().push_binary_with_metadata_policy_and_resolver(
933            data, metadata, policy, resolver,
934        )
935    }
936
937    /// Appends a type-2 binary payload with a DcUtf SHA-256 checksum.
938    ///
939    /// # Errors
940    /// Returns an error if checksum metadata cannot be encoded.
941    pub fn push_binary_with_sha256(&mut self, data: &[u8]) -> Result<()> {
942        self.writer().push_binary_with_sha256(data)
943    }
944
945    /// Appends a typed checksum payload enclosed between `Dc 203` and `Dc 204`.
946    ///
947    /// Formats the payload as `Dc 203` (`DC_START_ENCAPSULATION_BINARY`), followed by
948    /// a hash format and byte length, followed by base64 encapsulation digits
949    /// and Dc 204. Mixed mode stores the digest directly with its type.
950    ///
951    /// # Errors
952    /// Returns error if base64 encoding fails.
953    pub fn push_checksum(
954        &mut self,
955        format: impl Into<DcChar>,
956        digest: &[u8],
957    ) -> Result<()> {
958        self.writer().push_checksum(format, digest)
959    }
960
961    /// Appends `Dc 641 "Global graph system block most recent node ID at time of document creation"`
962    /// followed by the specified System-block node ID (`l<node_id>`).
963    pub fn push_system_graph_most_recent_with_id(&mut self, node_id: u128) {
964        self.push_char(
965            ctb_formats_dcdata::dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID,
966        );
967        self.push_char(DcChar::from_u128(node_id));
968    }
969
970    /// Appends `Dc 641 "Global graph system block most recent node ID at time of document creation"`
971    /// followed by the current highest allocated System-block node ID from the runtime seed graph.
972    ///
973    /// # Errors
974    /// Returns an error if the shared runtime seed graph fails to load.
975    pub fn push_system_graph_most_recent(&mut self) -> Result<u128> {
976        let node_id = ctb_formats_dcdata::seed_graph::current_system_block_most_recent_node_id()?;
977        self.push_system_graph_most_recent_with_id(node_id);
978        Ok(node_id)
979    }
980
981    /// Appends a binary payload read directly from a stream (`std::io::Read`).
982    pub fn push_binary_from_reader<R: std::io::Read + ?Sized>(
983        &mut self,
984        reader: &mut R,
985        size: u64,
986        sha256: Option<[u8; 32]>,
987    ) -> Result<()> {
988        let size_usize = usize::try_from(size).context(
989            "Payload size exceeds addressable memory size for in-memory buffer; use write_binary_encapsulation instead",
990        )?;
991        let start = self.inner.len();
992        self.inner.reserve(size_usize);
993        let result = Self::write_binary_encapsulation(
994            &mut self.inner,
995            reader,
996            size,
997            sha256,
998        );
999        if result.is_err() {
1000            self.inner.truncate(start);
1001        }
1002        result
1003    }
1004
1005    /// Writes binary encapsulation directly to a `std::io::Write` stream from a `std::io::Read`.
1006    pub fn write_binary_encapsulation<
1007        W: std::io::Write,
1008        R: std::io::Read + ?Sized,
1009    >(
1010        writer: &mut W,
1011        reader: &mut R,
1012        size: u64,
1013        sha256: Option<[u8; 32]>,
1014    ) -> Result<()> {
1015        let metadata = if let Some(digest) = sha256 {
1016            crate::encapsulation::checksum_text(
1017                ctb_utilities::format_id::DC_SHA256,
1018                &digest,
1019            )?
1020        } else {
1021            DcString::new()
1022        };
1023        writer.write_all(&DC_203_BYTES)?;
1024        writer.write_all(&[TYPE_BINARY_METADATA])?;
1025        let size_u128 = u128::from(size);
1026        writer.write_all(&size_u128.to_be_bytes())?;
1027        writer.write_all(&u128::try_from(metadata.len())?.to_be_bytes())?;
1028        writer.write_all(metadata.as_bytes())?;
1029        let mut buf = [0u8; 64 * 1024];
1030        let mut remaining = size;
1031        let mut hasher = Sha256::new();
1032        while remaining > 0 {
1033            let buf_cap =
1034                u64::try_from(buf.len()).context("65536 fits into u64")?;
1035            let to_read_u64 = remaining.min(buf_cap);
1036            let to_read = usize::try_from(to_read_u64)
1037                .context("at most 65536 bytes fits in usize")?;
1038            let Some(buf_slice) = buf.get_mut(..to_read) else {
1039                bail!("Buffer slice out of range");
1040            };
1041            let n = reader.read(buf_slice)?;
1042            if n == 0 {
1043                bail!(
1044                    "Unexpected EOF writing binary payload to stream: expected {remaining} more bytes"
1045                );
1046            }
1047            let Some(read_slice) = buf.get(..n) else {
1048                bail!("Read slice out of range");
1049            };
1050            if sha256.is_some() {
1051                hasher.update(read_slice);
1052            }
1053            writer.write_all(read_slice)?;
1054            let n_u64 = u64::try_from(n).context("n fits in u64")?;
1055            remaining = remaining.saturating_sub(n_u64);
1056        }
1057        if let Some(expected) = sha256 {
1058            ensure!(
1059                hasher.finalize().as_slice() == expected.as_slice(),
1060                "Streamed binary payload SHA-256 checksum mismatch"
1061            );
1062        }
1063        Ok(())
1064    }
1065
1066    /// Appends a `DcMixed` segment.
1067    ///
1068    /// # Errors
1069    /// Returns an error for invalid type-2 metadata or checksum.
1070    pub fn push_chunk(&mut self, chunk: &DcMixed<'_>) -> Result<()> {
1071        match chunk {
1072            DcMixed::Text(text) => self.push_dc_str(text),
1073            DcMixed::BinaryWithMetadata { data, metadata } => {
1074                self.push_binary_with_metadata(data, metadata)?;
1075            }
1076            DcMixed::Binary {
1077                data,
1078                sha256: Some(sha),
1079            } => {
1080                let len_u64 = u64::try_from(data.len())?;
1081                self.write_encapsulation_header(
1082                    TYPE_BINARY_SHA256,
1083                    len_u64,
1084                    Some(*sha),
1085                );
1086                self.inner.extend_from_slice(data);
1087            }
1088            DcMixed::Binary { data, sha256: None } => {
1089                self.push_binary(data);
1090            }
1091        }
1092        Ok(())
1093    }
1094
1095    /// Shortens the `DcMstring` to `new_len` bytes.
1096    ///
1097    /// Must not shorten past the 21-byte header.
1098    pub fn truncate(&mut self, new_len: usize) {
1099        let min_len = DCMM_HEADER_LEN;
1100        if new_len >= min_len && new_len <= self.inner.len() {
1101            self.inner.truncate(new_len);
1102        }
1103    }
1104
1105    /// Clears the body of the document, resetting to an empty document with the 21-byte header.
1106    pub fn clear(&mut self) {
1107        self.inner.truncate(DCMM_HEADER_LEN);
1108    }
1109
1110    /// Reserves capacity for at least `additional` more bytes.
1111    pub fn reserve(&mut self, additional: usize) {
1112        self.inner.reserve(additional);
1113    }
1114
1115    /// Returns the total number of bytes this buffer can hold without reallocating.
1116    #[must_use]
1117    pub fn capacity(&self) -> usize {
1118        self.inner.capacity()
1119    }
1120
1121    fn write_encapsulation_header(
1122        &mut self,
1123        type_byte: u8,
1124        size: u64,
1125        sha256: Option<[u8; 32]>,
1126    ) {
1127        self.inner.extend_from_slice(&DC_203_BYTES);
1128        self.inner.push(type_byte);
1129        let size_u128 = u128::from(size);
1130        self.inner.extend_from_slice(&size_u128.to_be_bytes());
1131        if let Some(hash) = sha256 {
1132            self.inner.extend_from_slice(&hash);
1133        }
1134    }
1135}
1136
1137impl Deref for DcMstring {
1138    type Target = DcMstr;
1139
1140    #[inline]
1141    fn deref(&self) -> &Self::Target {
1142        #[expect(
1143            unsafe_code,
1144            reason = "DcMstring inner bytes are guaranteed to be valid DcMixed format"
1145        )]
1146        // Safety: DcMstring inner bytes are valid DcMixed data.
1147        unsafe {
1148            DcMstr::from_bytes_unchecked(&self.inner)
1149        }
1150    }
1151}
1152
1153impl DerefMut for DcMstring {
1154    #[inline]
1155    fn deref_mut(&mut self) -> &mut Self::Target {
1156        #[expect(
1157            unsafe_code,
1158            reason = "DcMstring inner bytes are guaranteed to be valid DcMixed format"
1159        )]
1160        // Safety: DcMstring inner bytes are valid DcMixed data.
1161        unsafe {
1162            DcMstr::from_bytes_unchecked_mut(&mut self.inner)
1163        }
1164    }
1165}
1166
1167impl Borrow<DcMstr> for DcMstring {
1168    #[inline]
1169    fn borrow(&self) -> &DcMstr {
1170        self
1171    }
1172}
1173
1174impl AsRef<DcMstr> for DcMstring {
1175    #[inline]
1176    fn as_ref(&self) -> &DcMstr {
1177        self
1178    }
1179}
1180
1181impl AsRef<[u8]> for DcMstring {
1182    #[inline]
1183    fn as_ref(&self) -> &[u8] {
1184        &self.inner
1185    }
1186}
1187
1188impl From<&str> for DcMstring {
1189    #[inline]
1190    fn from(s: &str) -> Self {
1191        let mut mst =
1192            Self::with_capacity(DCMM_HEADER_LEN.saturating_add(s.len()));
1193        mst.push_str(s);
1194        mst
1195    }
1196}
1197
1198impl From<String> for DcMstring {
1199    #[inline]
1200    fn from(s: String) -> Self {
1201        Self::from(s.as_str())
1202    }
1203}
1204
1205impl From<&DcStr> for DcMstring {
1206    #[inline]
1207    fn from(s: &DcStr) -> Self {
1208        let mut mst =
1209            Self::with_capacity(DCMM_HEADER_LEN.saturating_add(s.len()));
1210        mst.push_dc_str(s);
1211        mst
1212    }
1213}
1214
1215impl From<DcString> for DcMstring {
1216    #[inline]
1217    fn from(s: DcString) -> Self {
1218        let dc_str: &DcStr = s.as_ref();
1219        Self::from(dc_str)
1220    }
1221}
1222
1223impl From<&DcMstr> for DcMstring {
1224    #[inline]
1225    fn from(s: &DcMstr) -> Self {
1226        s.to_owned()
1227    }
1228}
1229
1230impl From<&DcMstring> for DcMstring {
1231    #[inline]
1232    fn from(s: &DcMstring) -> Self {
1233        s.clone()
1234    }
1235}
1236
1237impl FromIterator<DcChar> for DcMstring {
1238    fn from_iter<I: IntoIterator<Item = DcChar>>(iter: I) -> Self {
1239        let mut mst = Self::new();
1240        for ch in iter {
1241            mst.push_char(ch);
1242        }
1243        mst
1244    }
1245}
1246
1247impl FromIterator<char> for DcMstring {
1248    fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> Self {
1249        let mut mst = Self::new();
1250        for ch in iter {
1251            mst.push_char(ch);
1252        }
1253        mst
1254    }
1255}
1256
1257impl Extend<DcChar> for DcMstring {
1258    fn extend<I: IntoIterator<Item = DcChar>>(&mut self, iter: I) {
1259        for ch in iter {
1260            self.push_char(ch);
1261        }
1262    }
1263}
1264
1265impl Extend<char> for DcMstring {
1266    fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1267        for ch in iter {
1268            self.push_char(ch);
1269        }
1270    }
1271}
1272
1273impl PartialEq<str> for DcMstring {
1274    #[inline]
1275    fn eq(&self, other: &str) -> bool {
1276        self.as_mstr() == other
1277    }
1278}
1279
1280impl PartialEq<&str> for DcMstring {
1281    #[inline]
1282    fn eq(&self, other: &&str) -> bool {
1283        self.as_mstr() == *other
1284    }
1285}
1286
1287impl PartialEq<String> for DcMstring {
1288    #[inline]
1289    fn eq(&self, other: &String) -> bool {
1290        self.as_mstr() == other.as_str()
1291    }
1292}
1293
1294impl PartialEq<DcStr> for DcMstring {
1295    #[inline]
1296    fn eq(&self, other: &DcStr) -> bool {
1297        self.as_mstr() == other
1298    }
1299}
1300
1301impl PartialEq<&DcStr> for DcMstring {
1302    #[inline]
1303    fn eq(&self, other: &&DcStr) -> bool {
1304        self.as_mstr() == *other
1305    }
1306}
1307
1308impl PartialEq<DcString> for DcMstring {
1309    #[inline]
1310    fn eq(&self, other: &DcString) -> bool {
1311        self.as_mstr() == &**other
1312    }
1313}
1314
1315impl PartialEq<DcMstr> for DcMstring {
1316    #[inline]
1317    fn eq(&self, other: &DcMstr) -> bool {
1318        self.as_bytes() == other.as_bytes()
1319    }
1320}
1321
1322impl PartialEq<&DcMstr> for DcMstring {
1323    #[inline]
1324    fn eq(&self, other: &&DcMstr) -> bool {
1325        self.as_bytes() == other.as_bytes()
1326    }
1327}
1328
1329impl fmt::Display for DcMstring {
1330    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1331        fmt::Display::fmt(&**self, f)
1332    }
1333}
1334
1335impl fmt::Debug for DcMstring {
1336    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1337        write!(f, "DcMstring(\"{self}\")")
1338    }
1339}
1340
1341/// Returns true if `ch` can immediately follow `Dc 203` (`StartEncapsulationBinary`)
1342/// in a textual base64 encapsulation (`203 [type]? (6..7)? [checksum]? 127..190* 195* 204`).
1343pub(crate) fn is_textual_encapsulation_follower(
1344    ch: DcChar,
1345    resolver: &dyn crate::SyntaxRuleResolver,
1346) -> bool {
1347    let val = ch.to_u128();
1348    ch.fills_role_with(DcRole::BeginTypeDef, resolver)
1349        || ch.fills_role_with(DcRole::TypeUnion, resolver)
1350        || ch.fills_role_with(DcRole::TypeIntersection, resolver)
1351        || ch.fills_role_with(DcRole::FormatParamApplication, resolver)
1352        || resolver.token_satisfies_type(val, "type", None)
1353        || ch.fills_role_with(DcRole::BeginNumber, resolver)
1354        || ch.fills_role_with(DcRole::StartEncapsulationBinary, resolver)
1355        || ch.fills_role_with(DcRole::Base64Digit, resolver)
1356        || ch.fills_role_with(DcRole::Base64Padding, resolver)
1357        || ch.fills_role_with(DcRole::EndEncapsulationBinary, resolver)
1358        || resolver.matches_named_type_starter("base64_transport_control", val)
1359}
1360
1361/// Returns true if `slice` starts with a raw `DcMixed2` binary encapsulation header
1362/// (`DC_203_BYTES` followed by a valid binary encapsulation type byte `0`, `2`, or `3`).
1363pub(crate) fn is_binary_encapsulation_at(slice: &[u8]) -> bool {
1364    slice.starts_with(&DC_203_BYTES)
1365        && matches!(
1366            slice.get(ENCAP_TYPE_IDX).copied(),
1367            Some(TYPE_BINARY | TYPE_BINARY_METADATA | TYPE_BINARY_SHA256)
1368        )
1369}
1370
1371/// Returns true if `slice` starts with `Dc 203` (`DC_203_BYTES` or `DC_203_BYTES_V1`)
1372/// acting as a standalone character token rather than a binary or textual encapsulation.
1373pub(crate) fn is_non_encapsulating_dc203_at(
1374    slice: &[u8],
1375    is_v1: bool,
1376    resolver: &dyn crate::SyntaxRuleResolver,
1377) -> bool {
1378    let dc203_bytes: &[u8] = if is_v1 {
1379        &DC_203_BYTES_V1
1380    } else {
1381        &DC_203_BYTES
1382    };
1383    let Some(after) = slice.strip_prefix(dc203_bytes) else {
1384        return false;
1385    };
1386    let Some(&first_byte) = after.first() else {
1387        return true;
1388    };
1389    if first_byte < 0xF4 {
1390        return false;
1391    }
1392    let decoded = if is_v1 {
1393        decode_utf_8e_128_buf(after)
1394    } else {
1395        decode_dctf_buf(after)
1396    };
1397    let Some((next_val, _)) = decoded else {
1398        return false;
1399    };
1400    !is_textual_encapsulation_follower(DcChar(next_val), resolver)
1401}
1402
1403/// An iterator yielding `DcMixed` chunks from payload bytes.
1404#[derive(Clone, Debug)]
1405pub struct DcMixedChunks<'a> {
1406    pub(crate) slice: &'a [u8],
1407}
1408
1409impl<'a> Iterator for DcMixedChunks<'a> {
1410    type Item = DcMixed<'a>;
1411
1412    fn next(&mut self) -> Option<Self::Item> {
1413        if self.slice.is_empty() {
1414            return None;
1415        }
1416
1417        // Check if current position starts with a raw Dc 203 binary encapsulation
1418        if is_binary_encapsulation_at(self.slice) {
1419            let type_byte = *self.slice.get(ENCAP_TYPE_IDX)?;
1420            let size_bytes =
1421                self.slice.get(ENCAP_SIZE_START..ENCAP_SIZE_END)?;
1422            let mut size_buf = [0u8; 16];
1423            size_buf.copy_from_slice(size_bytes);
1424            let size_usize =
1425                usize::try_from(u128::from_be_bytes(size_buf)).ok()?;
1426            let metadata = if type_byte == TYPE_BINARY_METADATA {
1427                Some(metadata_region(self.slice, ENCAP_SIZE_END).ok()?)
1428            } else {
1429                None
1430            };
1431
1432            let (payload_start, sha256) = match type_byte {
1433                TYPE_BINARY => (ENCAP_SIZE_END, None),
1434                TYPE_BINARY_METADATA => {
1435                    let (payload_start, _) = metadata?;
1436                    (payload_start, None)
1437                }
1438                TYPE_BINARY_SHA256 => {
1439                    let sha_slice =
1440                        self.slice.get(ENCAP_SIZE_END..ENCAP_SHA256_END)?;
1441                    let mut sha = [0u8; 32];
1442                    sha.copy_from_slice(sha_slice);
1443                    (ENCAP_SHA256_END, Some(sha))
1444                }
1445                _ => return None,
1446            };
1447
1448            let payload_end = payload_start.checked_add(size_usize)?;
1449            let payload = self.slice.get(payload_start..payload_end)?;
1450            self.slice = self.slice.get(payload_end..)?;
1451
1452            return match type_byte {
1453                TYPE_BINARY | TYPE_BINARY_SHA256 => Some(DcMixed::Binary {
1454                    data: payload,
1455                    sha256,
1456                }),
1457                TYPE_BINARY_METADATA => {
1458                    let (_, metadata) = metadata?;
1459                    Some(DcMixed::BinaryWithMetadata {
1460                        data: payload,
1461                        metadata,
1462                    })
1463                }
1464                _ => None,
1465            };
1466        }
1467
1468        // Scan ahead for the next binary encapsulation chunk or end of slice
1469        let mut end = 0usize;
1470        let mut escaped = false;
1471        while end < self.slice.len() {
1472            if let Some(sub) = self.slice.get(end..) {
1473                if !escaped && is_binary_encapsulation_at(sub) {
1474                    break;
1475                }
1476                if let Some((val, char_len)) = decode_dctf_buf(sub) {
1477                    escaped = !escaped && DcChar(val).fills_role(DcRole::Escape);
1478                    end = end.saturating_add(char_len);
1479                } else {
1480                    break;
1481                }
1482            } else {
1483                break;
1484            }
1485        }
1486
1487        if end == 0 {
1488            return None;
1489        }
1490
1491        let text_slice = self.slice.get(..end)?;
1492        self.slice = self.slice.get(end..)?;
1493        #[expect(
1494            unsafe_code,
1495            reason = "Text slice consists of validated DcTF character sequences"
1496        )]
1497        // Safety: text_slice was validated as valid DcTF.
1498        let dc_str = unsafe { DcStr::from_bytes_unchecked(text_slice) };
1499        Some(DcMixed::Text(dc_str))
1500    }
1501}
1502
1503impl std::iter::FusedIterator for DcMixedChunks<'_> {}
1504
1505fn validate_header(bytes: &[u8]) -> Result<(), DcMixedError> {
1506    if bytes.len() < DCMM_HEADER_LEN {
1507        return Err(DcMixedError::TooShort { len: bytes.len() });
1508    }
1509
1510    let Some(magic_slice) = bytes.get(..5) else {
1511        return Err(DcMixedError::TooShort { len: bytes.len() });
1512    };
1513    if magic_slice != DCMM_MAGIC {
1514        let mut found = [0u8; 5];
1515        found.copy_from_slice(magic_slice);
1516        return Err(DcMixedError::InvalidMagic { found });
1517    }
1518
1519    let Some(uuid_slice) = bytes.get(5..21) else {
1520        return Err(DcMixedError::TooShort { len: bytes.len() });
1521    };
1522    if uuid_slice != DCMM_UUID {
1523        let mut found = [0u8; 16];
1524        found.copy_from_slice(uuid_slice);
1525        return Err(DcMixedError::InvalidUuid { found });
1526    }
1527
1528    Ok(())
1529}
1530
1531fn validate_encapsulation_region(
1532    bytes: &[u8],
1533    enc_start: usize,
1534    policy: &crate::DcProjectionPolicy,
1535) -> Result<usize, DcMixedError> {
1536    let after_dc203 = enc_start.saturating_add(ENCAP_TYPE_IDX);
1537    let Some(&type_byte) = bytes.get(after_dc203) else {
1538        return Err(DcMixedError::TruncatedEncapsulation {
1539            offset: enc_start,
1540            expected: ENCAP_SIZE_START,
1541            available: bytes.len().saturating_sub(enc_start),
1542        });
1543    };
1544    if matches!(type_byte, 1 | 4) {
1545        return Err(DcMixedError::UnsupportedLegacyType {
1546            offset: after_dc203,
1547            type_byte,
1548        });
1549    }
1550    if !matches!(
1551        type_byte,
1552        TYPE_BINARY | TYPE_BINARY_METADATA | TYPE_BINARY_SHA256
1553    ) {
1554        return Err(DcMixedError::InvalidEncapsulationType {
1555            offset: after_dc203,
1556            type_byte,
1557        });
1558    }
1559
1560    let size_start = after_dc203.saturating_add(1);
1561    let size_end = size_start.saturating_add(16);
1562    let Some(size_bytes) = bytes.get(size_start..size_end) else {
1563        return Err(DcMixedError::TruncatedEncapsulation {
1564            offset: enc_start,
1565            expected: ENCAP_SIZE_END,
1566            available: bytes.len().saturating_sub(enc_start),
1567        });
1568    };
1569
1570    let mut size_buf = [0u8; 16];
1571    size_buf.copy_from_slice(size_bytes);
1572    let size_u128 = u128::from_be_bytes(size_buf);
1573    let Ok(size_usize) = usize::try_from(size_u128) else {
1574        return Err(DcMixedError::SizeOverflow {
1575            offset: enc_start,
1576            size: size_u128,
1577        });
1578    };
1579
1580    let (payload_start, expected_sha) =
1581        match type_byte {
1582            TYPE_BINARY => (size_end, None),
1583            TYPE_BINARY_METADATA => {
1584                let (payload_start, _) = metadata_region(bytes, size_end)
1585                    .map_err(|error| DcMixedError::InvalidMetadata {
1586                        offset: enc_start,
1587                        message: error.to_string(),
1588                    })?;
1589                (payload_start, None)
1590            }
1591            TYPE_BINARY_SHA256 => {
1592                let sha_end = size_end.saturating_add(32);
1593                let Some(sha_slice) = bytes.get(size_end..sha_end) else {
1594                    return Err(DcMixedError::TruncatedEncapsulation {
1595                        offset: enc_start,
1596                        expected: sha_end.saturating_sub(enc_start),
1597                        available: bytes.len().saturating_sub(enc_start),
1598                    });
1599                };
1600                let mut sha = [0u8; 32];
1601                sha.copy_from_slice(sha_slice);
1602                (sha_end, Some(sha))
1603            }
1604            _ => {
1605                return Err(DcMixedError::InvalidEncapsulationType {
1606                    offset: after_dc203,
1607                    type_byte,
1608                });
1609            }
1610        };
1611
1612    let payload_end = payload_start.checked_add(size_usize).ok_or(
1613        DcMixedError::SizeOverflow {
1614            offset: enc_start,
1615            size: size_u128,
1616        },
1617    )?;
1618
1619    let Some(payload) = bytes.get(payload_start..payload_end) else {
1620        return Err(DcMixedError::TruncatedEncapsulation {
1621            offset: enc_start,
1622            expected: payload_end.saturating_sub(enc_start),
1623            available: bytes.len().saturating_sub(enc_start),
1624        });
1625    };
1626
1627    if type_byte == TYPE_BINARY_METADATA {
1628        let (_, metadata) = metadata_region(bytes, size_end)?;
1629        crate::encapsulation::validate_metadata_with_policy(
1630            metadata, payload, policy,
1631        )
1632        .map_err(|error| DcMixedError::InvalidMetadata {
1633            offset: enc_start,
1634            message: format!("{error:#}"),
1635        })?;
1636    }
1637
1638    if let Some(expected_checksum) = expected_sha {
1639        let actual = Sha256::digest(payload);
1640        if actual.as_slice() != expected_checksum.as_slice() {
1641            let mut actual_arr = [0u8; 32];
1642            actual_arr.copy_from_slice(actual.as_slice());
1643            return Err(DcMixedError::ChecksumMismatch {
1644                offset: enc_start,
1645                expected: expected_checksum,
1646                actual: actual_arr,
1647            });
1648        }
1649    }
1650
1651    Ok(payload_end)
1652}
1653
1654fn metadata_region(
1655    bytes: &[u8],
1656    start: usize,
1657) -> Result<(usize, &DcStr), DcMixedError> {
1658    let invalid = |message: &str| DcMixedError::InvalidMetadata {
1659        offset: start,
1660        message: message.to_owned(),
1661    };
1662    let length_end = start
1663        .checked_add(16)
1664        .ok_or_else(|| invalid("Metadata length overflow"))?;
1665    let length = bytes
1666        .get(start..length_end)
1667        .ok_or_else(|| invalid("Truncated metadata length"))?;
1668    let mut encoded = [0u8; 16];
1669    encoded.copy_from_slice(length);
1670    let length = usize::try_from(u128::from_be_bytes(encoded))
1671        .map_err(|_| invalid("Metadata exceeds addressable memory"))?;
1672    let end = length_end
1673        .checked_add(length)
1674        .ok_or_else(|| invalid("Metadata length overflow"))?;
1675    let metadata = bytes
1676        .get(length_end..end)
1677        .ok_or_else(|| invalid("Truncated metadata"))?;
1678    let metadata = DcStr::from_bytes(metadata).map_err(|source| {
1679        DcMixedError::InvalidUtf8e128 {
1680            offset: length_end.saturating_add(source.valid_up_to()),
1681            source,
1682        }
1683    })?;
1684    Ok((end, metadata))
1685}
1686
1687/// Validates that `bytes` contains valid `DcMixed` format data.
1688///
1689/// # Errors
1690/// Returns `DcMixedError` describing the first encountered validation error.
1691pub fn validate_dcmst(bytes: &[u8]) -> Result<(), DcMixedError> {
1692    validate_dcmst_with_policy(bytes, &crate::DcProjectionPolicy::strict())
1693}
1694
1695fn validate_dcmst_with_policy(
1696    bytes: &[u8],
1697    policy: &crate::DcProjectionPolicy,
1698) -> Result<(), DcMixedError> {
1699    validate_header(bytes)?;
1700    let resolver = ctb_formats_dcdata::syntax::default_syntax_resolver();
1701
1702    let mut offset = DCMM_HEADER_LEN;
1703    let mut escaped = false;
1704    while offset < bytes.len() {
1705        let Some(slice) = bytes.get(offset..) else {
1706            break;
1707        };
1708        if !escaped
1709            && slice.starts_with(&DC_203_BYTES)
1710            && !is_non_encapsulating_dc203_at(slice, false, resolver.as_ref())
1711        {
1712            offset = validate_encapsulation_region(bytes, offset, policy)?;
1713            escaped = false;
1714        } else {
1715            let Some((val, char_len)) = decode_dctf_buf(slice) else {
1716                return Err(DcMixedError::InvalidUtf8e128 {
1717                    offset,
1718                    source: DcUtfError {
1719                        valid_up_to: 0,
1720                        error_len: determine_dctf_error_len(slice),
1721                    },
1722                });
1723            };
1724            escaped = !escaped
1725                && DcChar(val)
1726                    .fills_role_with(DcRole::Escape, resolver.as_ref());
1727            offset = offset.saturating_add(char_len);
1728        }
1729    }
1730
1731    Ok(())
1732}
1733
1734/// Slice alias for consistency.
1735pub type DcMstSlice = DcMstr;
1736
1737/// Decodes in-memory `.dcmm` bytes (`DcMixed2` or legacy `DcMixed1`) into a `DcMstring`.
1738#[must_use]
1739pub fn dcmm_to_dcmstring(
1740    bytes: &[u8],
1741) -> Result<(DcMstring, ctb_formats_utilities::FormatLog)> {
1742    dcmm_to_dcmstring_with_options(bytes, &DcmmStreamOptions::default())
1743}
1744
1745/// Decodes in-memory `.dcmm` bytes (`DcMixed2` or legacy `DcMixed1`) into a `DcMstring`
1746/// with explicit strict or permissive (`best_effort`) options.
1747pub fn dcmm_to_dcmstring_with_options(
1748    bytes: &[u8],
1749    options: &DcmmStreamOptions,
1750) -> Result<(DcMstring, ctb_formats_utilities::FormatLog)> {
1751    if !options.best_effort {
1752        if bytes.len() >= DCMM_HEADER_LEN
1753            && bytes.get(..5) == Some(DCMM_MAGIC.as_slice())
1754            && bytes.get(5..21) == Some(DCMM_UUID_V1.as_slice())
1755        {
1756            return dcmm1_to_dcmstring(bytes);
1757        }
1758        return dcmm2_to_dcmstring(bytes);
1759    }
1760    decode_dcmm_slice_best_effort(bytes, false)
1761}
1762
1763/// Decodes in-memory `DcMixed2` (`.dcmm`) bytes into a `DcMstring`.
1764pub fn dcmm2_to_dcmstring(
1765    bytes: &[u8],
1766) -> Result<(DcMstring, ctb_formats_utilities::FormatLog)> {
1767    let doc = DcMstring::from_slice(bytes).context(
1768        "Input bytes do not conform to valid DcMixed2 (.dcmm) format",
1769    )?;
1770    Ok((doc, ctb_formats_utilities::FormatLog::default()))
1771}
1772
1773/// Decodes in-memory `DcMixed2` (`.dcmm`) bytes into a `DcMstring` with explicit
1774/// strict or permissive (`best_effort`) options.
1775pub fn dcmm2_to_dcmstring_with_options(
1776    bytes: &[u8],
1777    options: &DcmmStreamOptions,
1778) -> Result<(DcMstring, ctb_formats_utilities::FormatLog)> {
1779    if !options.best_effort {
1780        return dcmm2_to_dcmstring(bytes);
1781    }
1782    decode_dcmm_slice_best_effort(bytes, false)
1783}
1784
1785/// Decodes legacy `DcMixed1` (`.dcmm` v1, using `DcUtf`) bytes into a `DcMstring`
1786/// with explicit strict or permissive (`best_effort`) options.
1787pub fn dcmm1_to_dcmstring_with_options(
1788    bytes: &[u8],
1789    options: &DcmmStreamOptions,
1790) -> Result<(DcMstring, ctb_formats_utilities::FormatLog)> {
1791    if !options.best_effort {
1792        return dcmm1_to_dcmstring(bytes);
1793    }
1794    decode_dcmm_slice_best_effort(bytes, true)
1795}
1796
1797fn decode_dcmm_slice_best_effort(
1798    bytes: &[u8],
1799    default_v1: bool,
1800) -> Result<(DcMstring, ctb_formats_utilities::FormatLog)> {
1801    let mut log = ctb_formats_utilities::FormatLog::default();
1802    let mut mst =
1803        DcMstring::with_capacity(bytes.len().saturating_add(DCMM_HEADER_LEN));
1804    let mut is_v1 = default_v1;
1805    let mut offset = 0usize;
1806    let mut had_valid_initial_header = false;
1807
1808    if bytes.len() >= DCMM_HEADER_LEN
1809        && bytes.get(..5) == Some(DCMM_MAGIC.as_slice())
1810    {
1811        if bytes.get(5..21) == Some(DCMM_UUID.as_slice()) {
1812            if default_v1 {
1813                log.warn("Expected DcMixed1 UUID at offset 5, found DcMixed2 UUID; decoding as DcMixed2");
1814            }
1815            is_v1 = false;
1816            had_valid_initial_header = true;
1817        } else if bytes.get(5..21) == Some(DCMM_UUID_V1.as_slice()) {
1818            is_v1 = true;
1819            had_valid_initial_header = true;
1820        } else {
1821            log.warn("Corrupted DcMixed header UUID at offset 5; synthesizing valid header");
1822        }
1823        offset = DCMM_HEADER_LEN;
1824    } else {
1825        log.warn("Missing or invalid DcMixed magic header at offset 0; reading in permissive mode");
1826    }
1827
1828    let resolver = ctb_formats_dcdata::syntax::default_syntax_resolver();
1829    let mut escaped = false;
1830
1831    while offset < bytes.len() {
1832        let Some(slice) = bytes.get(offset..) else {
1833            break;
1834        };
1835
1836        if !had_valid_initial_header
1837            && slice.len() >= DCMM_HEADER_LEN
1838            && slice.get(..5) == Some(DCMM_MAGIC.as_slice())
1839        {
1840            if slice.get(5..21) == Some(DCMM_UUID.as_slice()) {
1841                log.warn(&format!(
1842                    "Found embedded DcMixed2 header at offset {offset}; aligning stream"
1843                ));
1844                is_v1 = false;
1845                escaped = false;
1846                offset = offset.saturating_add(DCMM_HEADER_LEN);
1847                continue;
1848            } else if slice.get(5..21) == Some(DCMM_UUID_V1.as_slice()) {
1849                log.warn(&format!(
1850                    "Found embedded DcMixed1 header at offset {offset}; aligning stream"
1851                ));
1852                is_v1 = true;
1853                escaped = false;
1854                offset = offset.saturating_add(DCMM_HEADER_LEN);
1855                continue;
1856            }
1857        }
1858
1859        let dc203_bytes: &[u8] = if is_v1 {
1860            &DC_203_BYTES_V1
1861        } else {
1862            &DC_203_BYTES
1863        };
1864
1865        if !escaped
1866            && slice.starts_with(dc203_bytes)
1867            && !is_non_encapsulating_dc203_at(slice, is_v1, resolver.as_ref())
1868        {
1869            let dc203_len = dc203_bytes.len();
1870            let after_dc203 = offset.saturating_add(dc203_len);
1871            let size_start = after_dc203.saturating_add(1);
1872            let size_end = size_start.saturating_add(16);
1873
1874            let Some(&type_byte) = bytes.get(after_dc203) else {
1875                log.warn(&format!(
1876                    "Truncated binary encapsulation header at offset {offset}; substituting replacement character"
1877                ));
1878                mst.push_char(DcChar::from('\u{FFFD}'));
1879                offset = after_dc203.min(bytes.len());
1880                continue;
1881            };
1882
1883            let effective_type = if matches!(type_byte, 1 | 4) {
1884                log.warn(&format!(
1885                    "Unsupported legacy encapsulation type {type_byte} at offset {after_dc203}; treating as binary"
1886                ));
1887                if type_byte == 4 {
1888                    TYPE_BINARY_SHA256
1889                } else {
1890                    TYPE_BINARY
1891                }
1892            } else if matches!(
1893                type_byte,
1894                TYPE_BINARY | TYPE_BINARY_METADATA | TYPE_BINARY_SHA256
1895            ) {
1896                type_byte
1897            } else {
1898                log.warn(&format!(
1899                    "Invalid encapsulation type byte {type_byte} at offset {after_dc203}; substituting replacement character"
1900                ));
1901                mst.push_char(DcChar::from('\u{FFFD}'));
1902                offset = after_dc203;
1903                continue;
1904            };
1905
1906            let Some(size_bytes) = bytes.get(size_start..size_end) else {
1907                log.warn(&format!(
1908                    "Truncated binary encapsulation header at offset {offset}; substituting replacement character"
1909                ));
1910                mst.push_char(DcChar::from('\u{FFFD}'));
1911                offset = after_dc203.min(bytes.len());
1912                continue;
1913            };
1914
1915            let mut size_buf = [0u8; 16];
1916            size_buf.copy_from_slice(size_bytes);
1917            let size_u128 = u128::from_be_bytes(size_buf);
1918            let Ok(size_usize) = usize::try_from(size_u128) else {
1919                log.warn(&format!(
1920                    "Binary encapsulation size {size_u128} overflows memory at offset {offset}; substituting replacement character"
1921                ));
1922                mst.push_char(DcChar::from('\u{FFFD}'));
1923                offset = after_dc203;
1924                continue;
1925            };
1926
1927            match effective_type {
1928                TYPE_BINARY => {
1929                    let available = bytes.len().saturating_sub(size_end);
1930                    let actual_size = if size_usize > available {
1931                        log.warn(&format!(
1932                            "Truncated binary encapsulation at offset {offset}: expected {size_usize} bytes, found {available}"
1933                        ));
1934                        available
1935                    } else {
1936                        size_usize
1937                    };
1938                    let payload_end = size_end.saturating_add(actual_size);
1939                    if let Some(payload) = bytes.get(size_end..payload_end) {
1940                        let _ = mst.push_chunk(&DcMixed::Binary {
1941                            data: payload,
1942                            sha256: None,
1943                        });
1944                    }
1945                    offset = payload_end;
1946                }
1947                TYPE_BINARY_SHA256 => {
1948                    let sha_end = size_end.saturating_add(32);
1949                    let Some(sha_slice) = bytes.get(size_end..sha_end) else {
1950                        log.warn(&format!(
1951                            "Truncated SHA-256 encapsulation header at offset {offset}; substituting replacement character"
1952                        ));
1953                        mst.push_char(DcChar::from('\u{FFFD}'));
1954                        offset = after_dc203;
1955                        continue;
1956                    };
1957                    let mut expected_sha = [0u8; 32];
1958                    expected_sha.copy_from_slice(sha_slice);
1959                    let available = bytes.len().saturating_sub(sha_end);
1960                    let actual_size = if size_usize > available {
1961                        log.warn(&format!(
1962                            "Truncated SHA-256 encapsulation payload at offset {offset}: expected {size_usize} bytes, found {available}"
1963                        ));
1964                        available
1965                    } else {
1966                        size_usize
1967                    };
1968                    let payload_end = sha_end.saturating_add(actual_size);
1969                    if let Some(payload) = bytes.get(sha_end..payload_end) {
1970                        let actual = Sha256::digest(payload);
1971                        if actual.as_slice() == expected_sha.as_slice() {
1972                            let _ = mst.push_chunk(&DcMixed::Binary {
1973                                data: payload,
1974                                sha256: Some(expected_sha),
1975                            });
1976                        } else {
1977                            log.warn(&format!(
1978                                "SHA-256 checksum mismatch at offset {offset}; preserving payload"
1979                            ));
1980                            let _ = mst.push_chunk(&DcMixed::Binary {
1981                                data: payload,
1982                                sha256: None,
1983                            });
1984                        }
1985                    }
1986                    offset = payload_end;
1987                }
1988                TYPE_BINARY_METADATA => {
1989                    let meta_len_end = size_end.saturating_add(16);
1990                    let Some(meta_len_bytes) =
1991                        bytes.get(size_end..meta_len_end)
1992                    else {
1993                        log.warn(&format!(
1994                            "Truncated encapsulation metadata length at offset {offset}; substituting replacement character"
1995                        ));
1996                        mst.push_char(DcChar::from('\u{FFFD}'));
1997                        offset = after_dc203;
1998                        continue;
1999                    };
2000                    let mut meta_len_buf = [0u8; 16];
2001                    meta_len_buf.copy_from_slice(meta_len_bytes);
2002                    let Ok(meta_len) =
2003                        usize::try_from(u128::from_be_bytes(meta_len_buf))
2004                    else {
2005                        log.warn(&format!(
2006                            "Encapsulation metadata length overflows memory at offset {offset}; substituting replacement character"
2007                        ));
2008                        mst.push_char(DcChar::from('\u{FFFD}'));
2009                        offset = after_dc203;
2010                        continue;
2011                    };
2012                    let Some(meta_end) = meta_len_end.checked_add(meta_len)
2013                    else {
2014                        log.warn(&format!(
2015                            "Encapsulation metadata length overflows offset at {offset}; substituting replacement character"
2016                        ));
2017                        mst.push_char(DcChar::from('\u{FFFD}'));
2018                        offset = after_dc203;
2019                        continue;
2020                    };
2021                    let Some(meta_raw) = bytes.get(meta_len_end..meta_end)
2022                    else {
2023                        log.warn(&format!(
2024                            "Truncated encapsulation metadata at offset {offset}; substituting replacement character"
2025                        ));
2026                        mst.push_char(DcChar::from('\u{FFFD}'));
2027                        offset = after_dc203;
2028                        continue;
2029                    };
2030                    let available = bytes.len().saturating_sub(meta_end);
2031                    let actual_size = if size_usize > available {
2032                        log.warn(&format!(
2033                            "Truncated encapsulation payload at offset {offset}: expected {size_usize} bytes, found {available}"
2034                        ));
2035                        available
2036                    } else {
2037                        size_usize
2038                    };
2039                    let payload_end = meta_end.saturating_add(actual_size);
2040                    if let Some(payload) = bytes.get(meta_end..payload_end) {
2041                        let meta_res = if is_v1 {
2042                            DcString::from_dcutf(meta_raw.to_vec())
2043                                .map_err(anyhow::Error::from)
2044                        } else {
2045                            DcString::from_dctf(meta_raw.to_vec())
2046                                .map_err(anyhow::Error::from)
2047                        };
2048                        match meta_res {
2049                            Ok(meta_dcstring) => {
2050                                if let Err(err) = mst.push_binary_with_metadata(
2051                                    payload,
2052                                    &meta_dcstring,
2053                                ) {
2054                                    log.warn(&format!(
2055                                        "Invalid encapsulation metadata or checksum at offset {offset} ({err:#}); preserving raw payload"
2056                                    ));
2057                                    let _ = mst.push_chunk(&DcMixed::Binary {
2058                                        data: payload,
2059                                        sha256: None,
2060                                    });
2061                                }
2062                            }
2063                            Err(err) => {
2064                                log.warn(&format!(
2065                                    "Corrupted encapsulation metadata encoding at offset {offset} ({err:#}); preserving raw payload"
2066                                ));
2067                                let _ = mst.push_chunk(&DcMixed::Binary {
2068                                    data: payload,
2069                                    sha256: None,
2070                                });
2071                            }
2072                        }
2073                    }
2074                    offset = payload_end;
2075                }
2076                _ => {
2077                    log.warn(&format!(
2078                        "Invalid encapsulation type byte {type_byte} at offset {after_dc203}; substituting replacement character"
2079                    ));
2080                    mst.push_char(DcChar::from('\u{FFFD}'));
2081                    offset = after_dc203;
2082                }
2083            }
2084        } else {
2085            let decoded = if is_v1 {
2086                decode_utf_8e_128_buf(slice)
2087            } else {
2088                decode_dctf_buf(slice)
2089            };
2090            if let Some((val, char_len)) = decoded {
2091                let ch = DcChar(val);
2092                escaped = !escaped
2093                    && ch.fills_role_with(DcRole::Escape, resolver.as_ref());
2094                mst.push_char(ch);
2095                offset = offset.saturating_add(char_len);
2096            } else {
2097                escaped = false;
2098                let err_len_opt = if is_v1 {
2099                    determine_utf_8e_128_error_len(slice)
2100                } else {
2101                    determine_dctf_error_len(slice)
2102                };
2103                // Reason for fallback: when error_len is None (incomplete sequence at end of slice), consume the remaining bytes of the incomplete sequence.
2104                let step =
2105                    err_len_opt.unwrap_or(slice.len()).max(1).min(slice.len());
2106                log.warn(&format!(
2107                    "Invalid {} byte sequence at offset {offset} ({step} bytes); substituting U+FFFD",
2108                    if is_v1 { "DcUtf" } else { "DcTF" }
2109                ));
2110                mst.push_char(DcChar::from('\u{FFFD}'));
2111                offset = offset.saturating_add(step);
2112            }
2113        }
2114    }
2115
2116    Ok((mst, log))
2117}
2118
2119/// Encodes a `DcMstring` into `DcMixed2` (`.dcmm`) bytes.
2120pub fn dcmstring_to_dcmm(
2121    doc: &DcMstring,
2122) -> Result<(Vec<u8>, ctb_formats_utilities::FormatLog)> {
2123    dcmstring_to_dcmm2(doc)
2124}
2125
2126/// Encodes a `DcMstring` into `DcMixed2` (`.dcmm`) bytes.
2127pub fn dcmstring_to_dcmm2(
2128    doc: &DcMstring,
2129) -> Result<(Vec<u8>, ctb_formats_utilities::FormatLog)> {
2130    Ok((
2131        doc.as_bytes().to_vec(),
2132        ctb_formats_utilities::FormatLog::default(),
2133    ))
2134}
2135
2136struct SectionHashers {
2137    pairs: Vec<(
2138        SupportedHashFormat,
2139        ctb_formats_checksum::StreamingHasher,
2140        ctb_formats_checksum::StreamingHasher,
2141    )>,
2142}
2143
2144impl SectionHashers {
2145    fn new() -> Self {
2146        let mut pairs =
2147            Vec::with_capacity(SupportedHashFormat::ALL_FORMAT_IDS.len());
2148        for &fmt_id in SupportedHashFormat::ALL_FORMAT_IDS {
2149            if let Some(algo) = SupportedHashFormat::from_format_id(fmt_id) {
2150                pairs.push((
2151                    algo,
2152                    ctb_formats_checksum::StreamingHasher::new(algo),
2153                    ctb_formats_checksum::StreamingHasher::new(algo),
2154                ));
2155            }
2156        }
2157        Self { pairs }
2158    }
2159
2160    fn update(&mut self, src_bytes: &[u8], dst_bytes: &[u8]) {
2161        for (_algo, src_h, dst_h) in &mut self.pairs {
2162            src_h.update(src_bytes);
2163            dst_h.update(dst_bytes);
2164        }
2165    }
2166
2167    fn finalize_algorithm(
2168        self,
2169        algorithm: SupportedHashFormat,
2170    ) -> Result<(Vec<u8>, Vec<u8>)> {
2171        for (algo, src_h, dst_h) in self.pairs {
2172            if algo == algorithm {
2173                return Ok((src_h.finalize(), dst_h.finalize()));
2174            }
2175        }
2176        bail!("Section checksum algorithm {algorithm:?} is not initialized")
2177    }
2178}
2179
2180struct SectionContainerFrame {
2181    closer: DcChar,
2182    is_opaque_to_inner_openers: bool,
2183    section_hashers: Option<SectionHashers>,
2184}
2185
2186struct ClosedChecksummedSection {
2187    hashers: SectionHashers,
2188    saw_digest_tag: bool,
2189}
2190
2191impl ClosedChecksummedSection {
2192    fn recompute_typed_digest(
2193        self,
2194        meta_dcstring: &DcStr,
2195        payload: &[u8],
2196        src_offset: usize,
2197        resolver: &ctb_formats_dcdata::syntax::DatasetRuleResolver,
2198    ) -> Result<Vec<u8>> {
2199        let strict = crate::DcProjectionPolicy::strict();
2200        let parsed =
2201            crate::encapsulation::parse_metadata_with_policy_and_resolver(
2202                meta_dcstring,
2203                &strict,
2204                resolver,
2205            )?;
2206        ensure!(
2207            parsed.checksum.is_none(),
2208            "Nested checksum metadata on section digest is not supported"
2209        );
2210        let data_type = parsed
2211            .data_type
2212            .context("Section digest requires a hash type header")?;
2213        let Some(algorithm) =
2214            crate::encapsulation::ChecksumSpec::algorithm_for_digest_with_resolver(
2215                data_type,
2216                u64::try_from(payload.len())?,
2217                &strict,
2218                resolver,
2219            )?
2220        else {
2221            bail!("Section checksum algorithm is unsupported");
2222        };
2223        let (actual_src_digest, dst_digest) =
2224            self.hashers.finalize_algorithm(algorithm)?;
2225        ensure!(
2226            actual_src_digest.as_slice() == payload,
2227            "Section checksum mismatch at offset {src_offset}"
2228        );
2229        Ok(dst_digest)
2230    }
2231
2232    fn recompute_untyped_sha256_digest(
2233        self,
2234        payload: &[u8],
2235        src_offset: usize,
2236    ) -> Result<[u8; 32]> {
2237        ensure!(
2238            payload.len() == 32,
2239            "Untyped section digest at offset {src_offset} must be 32-byte SHA-256"
2240        );
2241        let (actual_src, dst_digest) = self
2242            .hashers
2243            .finalize_algorithm(SupportedHashFormat::Sha256)?;
2244        ensure!(
2245            actual_src.as_slice() == payload,
2246            "Section checksum mismatch at offset {src_offset}"
2247        );
2248        let mut out = [0_u8; 32];
2249        out.copy_from_slice(&dst_digest);
2250        Ok(out)
2251    }
2252}
2253
2254struct ChecksumSectionTracker {
2255    resolver: std::sync::Arc<ctb_formats_dcdata::syntax::DatasetRuleResolver>,
2256    escaped: bool,
2257    stack: Vec<SectionContainerFrame>,
2258    awaiting_digest: Option<ClosedChecksummedSection>,
2259}
2260
2261impl ChecksumSectionTracker {
2262    fn new() -> Self {
2263        Self {
2264            resolver: ctb_formats_dcdata::syntax::default_syntax_resolver()
2265                .clone(),
2266            escaped: false,
2267            stack: Vec::new(),
2268            awaiting_digest: None,
2269        }
2270    }
2271
2272    fn has_active_section(&self) -> bool {
2273        self.stack.iter().any(|f| f.section_hashers.is_some())
2274    }
2275
2276    fn update_active_sections(&mut self, src_bytes: &[u8], dst_bytes: &[u8]) {
2277        for frame in &mut self.stack {
2278            if let Some(hashers) = &mut frame.section_hashers {
2279                hashers.update(src_bytes, dst_bytes);
2280            }
2281        }
2282    }
2283
2284    fn on_char(
2285        &mut self,
2286        ch: DcChar,
2287        src_char_bytes: &[u8],
2288        dst_char_bytes: &[u8],
2289        src_start: usize,
2290    ) -> Result<()> {
2291        use ctb_formats_dcdata::dc_char::DcCharExt;
2292        use ctb_formats_dcdata::syntax::{
2293            CharTarget, DcRole, SyntaxRuleResolver,
2294        };
2295
2296        if let Some(closed) = &mut self.awaiting_digest {
2297            if !closed.saw_digest_tag {
2298                if !self.escaped
2299                    && ch.fills_role_with(
2300                        DcRole::SectionDigest,
2301                        self.resolver.as_ref(),
2302                    )
2303                {
2304                    closed.saw_digest_tag = true;
2305                    self.update_active_sections(src_char_bytes, dst_char_bytes);
2306                    return Ok(());
2307                }
2308                bail!(
2309                    "Expected Dc 545 (SectionDigest) after Dc 544 (EndChecksummedSection) at offset {src_start}"
2310                );
2311            }
2312            bail!(
2313                "Expected binary [checksum] after Dc 545 (SectionDigest) at offset {src_start}"
2314            );
2315        }
2316
2317        if self.escaped {
2318            self.escaped = false;
2319            self.update_active_sections(src_char_bytes, dst_char_bytes);
2320            return Ok(());
2321        }
2322
2323        if ch.fills_role_with(DcRole::Escape, self.resolver.as_ref())
2324            || ch.fills_role_with(
2325                DcRole::QuoteFollowingDcAsAtom,
2326                self.resolver.as_ref(),
2327            )
2328        {
2329            self.escaped = true;
2330            self.update_active_sections(src_char_bytes, dst_char_bytes);
2331            return Ok(());
2332        }
2333
2334        if self
2335            .stack
2336            .last()
2337            .is_some_and(|f| f.is_opaque_to_inner_openers)
2338        {
2339            if self.stack.last().is_some_and(|top| {
2340                top.closer == ch
2341                    || self
2342                        .resolver
2343                        .is_equivalent_to(ch.to_u128(), top.closer.to_u128())
2344            }) {
2345                self.stack.pop();
2346            }
2347            self.update_active_sections(src_char_bytes, dst_char_bytes);
2348            return Ok(());
2349        }
2350
2351        if self.stack.last().is_some_and(|top| {
2352            top.closer == ch
2353                || self
2354                    .resolver
2355                    .is_equivalent_to(ch.to_u128(), top.closer.to_u128())
2356        }) {
2357            if let Some(popped) = self.stack.pop() {
2358                self.update_active_sections(src_char_bytes, dst_char_bytes);
2359                if let Some(hashers) = popped.section_hashers {
2360                    self.awaiting_digest = Some(ClosedChecksummedSection {
2361                        hashers,
2362                        saw_digest_tag: false,
2363                    });
2364                }
2365            }
2366            return Ok(());
2367        }
2368
2369        if self.stack.iter().any(|f| {
2370            f.closer == ch
2371                || self
2372                    .resolver
2373                    .is_equivalent_to(ch.to_u128(), f.closer.to_u128())
2374        }) {
2375            bail!(
2376                "Unclosed inner container before closer {ch:?} at offset {src_start}"
2377            );
2378        }
2379
2380        self.update_active_sections(src_char_bytes, dst_char_bytes);
2381
2382        if !ch.fills_role_with(
2383            DcRole::StartEncapsulationBinary,
2384            self.resolver.as_ref(),
2385        ) && let Some(target) = CharTarget::from_u128(ch.to_u128())
2386        {
2387            if let Some(inner_closer) = self.resolver.closer_for_opener(&target)
2388            {
2389                let is_opaque_to_inner_openers = ch.fills_role_with(
2390                    DcRole::BeginNumber,
2391                    self.resolver.as_ref(),
2392                ) || ch.fills_role_with(
2393                    DcRole::BeginGraphNodeDefinition,
2394                    self.resolver.as_ref(),
2395                );
2396                let section_hashers = if ch.fills_role_with(
2397                    DcRole::BeginChecksummedSection,
2398                    self.resolver.as_ref(),
2399                ) {
2400                    Some(SectionHashers::new())
2401                } else {
2402                    None
2403                };
2404                self.stack.push(SectionContainerFrame {
2405                    closer: DcChar::from_u128(inner_closer),
2406                    is_opaque_to_inner_openers,
2407                    section_hashers,
2408                });
2409            }
2410        }
2411
2412        Ok(())
2413    }
2414
2415    fn on_binary_chunk(
2416        &mut self,
2417        src_offset: usize,
2418    ) -> Result<Option<ClosedChecksummedSection>> {
2419        self.escaped = false;
2420        if let Some(closed) = self.awaiting_digest.take() {
2421            ensure!(
2422                closed.saw_digest_tag,
2423                "Expected Dc 545 (SectionDigest) after Dc 544 (EndChecksummedSection) at offset {src_offset}"
2424            );
2425            return Ok(Some(closed));
2426        }
2427        Ok(None)
2428    }
2429
2430    fn finish(&self) -> Result<()> {
2431        if self.awaiting_digest.is_some() {
2432            bail!(
2433                "Missing Dc 545 (SectionDigest) or [checksum] after Dc 544 (EndChecksummedSection)"
2434            );
2435        }
2436        if self.has_active_section() {
2437            bail!(
2438                "Unclosed Dc 543 (BeginChecksummedSection) at end of document"
2439            );
2440        }
2441        Ok(())
2442    }
2443}
2444
2445/// Decodes legacy `DcMixed1` (`.dcmm` v1, using `DcUtf`) bytes into a `DcMstring` (`DcMixed2`).
2446pub fn dcmm1_to_dcmstring(
2447    bytes: &[u8],
2448) -> Result<(DcMstring, ctb_formats_utilities::FormatLog)> {
2449    if bytes.len() < DCMM_HEADER_LEN {
2450        return Err(DcMixedError::TooShort { len: bytes.len() }.into());
2451    }
2452    let Some(magic_slice) = bytes.get(..5) else {
2453        return Err(DcMixedError::TooShort { len: bytes.len() }.into());
2454    };
2455    if magic_slice != DCMM_MAGIC {
2456        let mut found = [0u8; 5];
2457        found.copy_from_slice(magic_slice);
2458        return Err(DcMixedError::InvalidMagic { found }.into());
2459    }
2460    let Some(uuid_slice) = bytes.get(5..21) else {
2461        return Err(DcMixedError::TooShort { len: bytes.len() }.into());
2462    };
2463    if uuid_slice != DCMM_UUID_V1 {
2464        let mut found = [0u8; 16];
2465        found.copy_from_slice(uuid_slice);
2466        return Err(DcMixedError::InvalidUuid { found }.into());
2467    }
2468
2469    let mut mst = DcMstring::with_capacity(bytes.len());
2470    let mut tracker = ChecksumSectionTracker::new();
2471    let mut offset = DCMM_HEADER_LEN;
2472    while offset < bytes.len() {
2473        let Some(slice) = bytes.get(offset..) else {
2474            break;
2475        };
2476        if !tracker.escaped
2477            && slice.starts_with(&DC_203_BYTES_V1)
2478            && !is_non_encapsulating_dc203_at(
2479                slice,
2480                true,
2481                tracker.resolver.as_ref(),
2482            )
2483        {
2484            let closed_section = tracker.on_binary_chunk(offset)?;
2485            let after_dc203 = offset.saturating_add(DC_203_BYTES_V1.len());
2486            let Some(&type_byte) = bytes.get(after_dc203) else {
2487                return Err(DcMixedError::TruncatedEncapsulation {
2488                    offset,
2489                    expected: DC_203_BYTES_V1.len().saturating_add(1),
2490                    available: bytes.len().saturating_sub(offset),
2491                }
2492                .into());
2493            };
2494            if matches!(type_byte, 1 | 4) {
2495                return Err(DcMixedError::UnsupportedLegacyType {
2496                    offset: after_dc203,
2497                    type_byte,
2498                }
2499                .into());
2500            }
2501            if !matches!(
2502                type_byte,
2503                TYPE_BINARY | TYPE_BINARY_METADATA | TYPE_BINARY_SHA256
2504            ) {
2505                return Err(DcMixedError::InvalidEncapsulationType {
2506                    offset: after_dc203,
2507                    type_byte,
2508                }
2509                .into());
2510            }
2511            let size_start = after_dc203.saturating_add(1);
2512            let size_end = size_start.saturating_add(16);
2513            let Some(size_bytes) = bytes.get(size_start..size_end) else {
2514                return Err(DcMixedError::TruncatedEncapsulation {
2515                    offset,
2516                    expected: DC_203_BYTES_V1.len().saturating_add(17),
2517                    available: bytes.len().saturating_sub(offset),
2518                }
2519                .into());
2520            };
2521            let mut size_buf = [0u8; 16];
2522            size_buf.copy_from_slice(size_bytes);
2523            let size_u128 = u128::from_be_bytes(size_buf);
2524            let Ok(size_usize) = usize::try_from(size_u128) else {
2525                return Err(DcMixedError::SizeOverflow {
2526                    offset,
2527                    size: size_u128,
2528                }
2529                .into());
2530            };
2531            match type_byte {
2532                TYPE_BINARY => {
2533                    let payload_end = size_end.checked_add(size_usize).ok_or(
2534                        DcMixedError::SizeOverflow {
2535                            offset,
2536                            size: size_u128,
2537                        },
2538                    )?;
2539                    let Some(payload) = bytes.get(size_end..payload_end) else {
2540                        return Err(DcMixedError::TruncatedEncapsulation {
2541                            offset,
2542                            expected: payload_end.saturating_sub(offset),
2543                            available: bytes.len().saturating_sub(offset),
2544                        }
2545                        .into());
2546                    };
2547                    let dst_encap_start = mst.len();
2548                    if let Some(closed) = closed_section {
2549                        let new_digest = closed
2550                            .recompute_untyped_sha256_digest(payload, offset)?;
2551                        mst.push_chunk(&DcMixed::Binary {
2552                            data: &new_digest,
2553                            sha256: None,
2554                        })?;
2555                    } else {
2556                        mst.push_chunk(&DcMixed::Binary {
2557                            data: payload,
2558                            sha256: None,
2559                        })?;
2560                    }
2561                    if tracker.has_active_section() {
2562                        if let (Some(src_encap), Some(dst_encap)) = (
2563                            bytes.get(offset..payload_end),
2564                            mst.as_bytes().get(dst_encap_start..),
2565                        ) {
2566                            tracker
2567                                .update_active_sections(src_encap, dst_encap);
2568                        }
2569                    }
2570                    offset = payload_end;
2571                }
2572                TYPE_BINARY_METADATA => {
2573                    let meta_len_end =
2574                        size_end.checked_add(16).ok_or_else(|| {
2575                            DcMixedError::InvalidMetadata {
2576                                offset: size_end,
2577                                message: "Metadata length overflow".to_owned(),
2578                            }
2579                        })?;
2580                    let Some(meta_len_bytes) =
2581                        bytes.get(size_end..meta_len_end)
2582                    else {
2583                        return Err(DcMixedError::InvalidMetadata {
2584                            offset: size_end,
2585                            message: "Truncated metadata length".to_owned(),
2586                        }
2587                        .into());
2588                    };
2589                    let mut meta_len_buf = [0u8; 16];
2590                    meta_len_buf.copy_from_slice(meta_len_bytes);
2591                    let meta_len =
2592                        usize::try_from(u128::from_be_bytes(meta_len_buf))
2593                            .map_err(|_| DcMixedError::InvalidMetadata {
2594                                offset: size_end,
2595                                message: "Metadata exceeds addressable memory"
2596                                    .to_owned(),
2597                            })?;
2598                    let meta_end = meta_len_end
2599                        .checked_add(meta_len)
2600                        .ok_or_else(|| DcMixedError::InvalidMetadata {
2601                            offset: size_end,
2602                            message: "Metadata length overflow".to_owned(),
2603                        })?;
2604                    let Some(meta_dcutf) = bytes.get(meta_len_end..meta_end)
2605                    else {
2606                        return Err(DcMixedError::InvalidMetadata {
2607                            offset: size_end,
2608                            message: "Truncated metadata".to_owned(),
2609                        }
2610                        .into());
2611                    };
2612                    let meta_dcstring = DcString::from_dcutf(
2613                        meta_dcutf.to_vec(),
2614                    )
2615                    .map_err(|source| DcMixedError::InvalidUtf8e128 {
2616                        offset: meta_len_end
2617                            .saturating_add(source.valid_up_to()),
2618                        source,
2619                    })?;
2620                    let payload_end = meta_end.checked_add(size_usize).ok_or(
2621                        DcMixedError::SizeOverflow {
2622                            offset,
2623                            size: size_u128,
2624                        },
2625                    )?;
2626                    let Some(payload) = bytes.get(meta_end..payload_end) else {
2627                        return Err(DcMixedError::TruncatedEncapsulation {
2628                            offset,
2629                            expected: payload_end.saturating_sub(offset),
2630                            available: bytes.len().saturating_sub(offset),
2631                        }
2632                        .into());
2633                    };
2634                    let dst_encap_start = mst.len();
2635                    if let Some(closed) = closed_section {
2636                        let new_digest = closed.recompute_typed_digest(
2637                            &meta_dcstring,
2638                            payload,
2639                            offset,
2640                            tracker.resolver.as_ref(),
2641                        )?;
2642                        mst.push_binary_with_metadata(
2643                            &new_digest,
2644                            &meta_dcstring,
2645                        )
2646                        .map_err(|err| {
2647                            DcMixedError::InvalidMetadata {
2648                                offset,
2649                                message: format!("{err:#}"),
2650                            }
2651                        })?;
2652                    } else {
2653                        mst.push_binary_with_metadata(payload, &meta_dcstring)
2654                            .map_err(|err| DcMixedError::InvalidMetadata {
2655                                offset,
2656                                message: format!("{err:#}"),
2657                            })?;
2658                    }
2659                    if tracker.has_active_section() {
2660                        if let (Some(src_encap), Some(dst_encap)) = (
2661                            bytes.get(offset..payload_end),
2662                            mst.as_bytes().get(dst_encap_start..),
2663                        ) {
2664                            tracker
2665                                .update_active_sections(src_encap, dst_encap);
2666                        }
2667                    }
2668                    offset = payload_end;
2669                }
2670                TYPE_BINARY_SHA256 => {
2671                    let sha_end = size_end.saturating_add(32);
2672                    let Some(sha_slice) = bytes.get(size_end..sha_end) else {
2673                        return Err(DcMixedError::TruncatedEncapsulation {
2674                            offset,
2675                            expected: sha_end.saturating_sub(offset),
2676                            available: bytes.len().saturating_sub(offset),
2677                        }
2678                        .into());
2679                    };
2680                    let mut expected_sha = [0u8; 32];
2681                    expected_sha.copy_from_slice(sha_slice);
2682                    let payload_end = sha_end.checked_add(size_usize).ok_or(
2683                        DcMixedError::SizeOverflow {
2684                            offset,
2685                            size: size_u128,
2686                        },
2687                    )?;
2688                    let Some(payload) = bytes.get(sha_end..payload_end) else {
2689                        return Err(DcMixedError::TruncatedEncapsulation {
2690                            offset,
2691                            expected: payload_end.saturating_sub(offset),
2692                            available: bytes.len().saturating_sub(offset),
2693                        }
2694                        .into());
2695                    };
2696                    let actual = Sha256::digest(payload);
2697                    if actual.as_slice() != expected_sha.as_slice() {
2698                        let mut actual_arr = [0u8; 32];
2699                        actual_arr.copy_from_slice(actual.as_slice());
2700                        return Err(DcMixedError::ChecksumMismatch {
2701                            offset,
2702                            expected: expected_sha,
2703                            actual: actual_arr,
2704                        }
2705                        .into());
2706                    }
2707                    let dst_encap_start = mst.len();
2708                    if let Some(closed) = closed_section {
2709                        let new_digest = closed
2710                            .recompute_untyped_sha256_digest(payload, offset)?;
2711                        let new_sha_digest = Sha256::digest(new_digest);
2712                        let mut new_sha = [0_u8; 32];
2713                        new_sha.copy_from_slice(new_sha_digest.as_slice());
2714                        mst.push_chunk(&DcMixed::Binary {
2715                            data: &new_digest,
2716                            sha256: Some(new_sha),
2717                        })?;
2718                    } else {
2719                        mst.push_chunk(&DcMixed::Binary {
2720                            data: payload,
2721                            sha256: Some(expected_sha),
2722                        })?;
2723                    }
2724                    if tracker.has_active_section() {
2725                        if let (Some(src_encap), Some(dst_encap)) = (
2726                            bytes.get(offset..payload_end),
2727                            mst.as_bytes().get(dst_encap_start..),
2728                        ) {
2729                            tracker
2730                                .update_active_sections(src_encap, dst_encap);
2731                        }
2732                    }
2733                    offset = payload_end;
2734                }
2735                _ => {
2736                    return Err(DcMixedError::InvalidEncapsulationType {
2737                        offset: after_dc203,
2738                        type_byte,
2739                    }
2740                    .into());
2741                }
2742            }
2743        } else {
2744            let Some((val, char_len)) = decode_utf_8e_128_buf(slice) else {
2745                return Err(DcMixedError::InvalidUtf8e128 {
2746                    offset,
2747                    source: DcUtfError {
2748                        valid_up_to: 0,
2749                        error_len: determine_utf_8e_128_error_len(slice),
2750                    },
2751                }
2752                .into());
2753            };
2754            let dst_start = mst.len();
2755            let ch = DcChar(val);
2756            mst.push_char(ch);
2757            let dst_end = mst.len();
2758            let next_offset = offset.saturating_add(char_len);
2759            if let (Some(src_char), Some(dst_char)) = (
2760                bytes.get(offset..next_offset),
2761                mst.as_bytes().get(dst_start..dst_end),
2762            ) {
2763                tracker.on_char(ch, src_char, dst_char, offset)?;
2764            }
2765            offset = next_offset;
2766        }
2767    }
2768    tracker.finish()?;
2769
2770    Ok((mst, ctb_formats_utilities::FormatLog::default()))
2771}
2772
2773/// Encodes a `DcMstring` into legacy `DcMixed1` (`.dcmm` v1, using `DcUtf`) bytes.
2774pub fn dcmstring_to_dcmm1(
2775    doc: &DcMstring,
2776) -> Result<(Vec<u8>, ctb_formats_utilities::FormatLog)> {
2777    let bytes = doc.as_bytes();
2778    let mut out = Vec::with_capacity(bytes.len());
2779    out.extend_from_slice(&DCMM_MAGIC);
2780    out.extend_from_slice(&DCMM_UUID_V1);
2781
2782    let mut tracker = ChecksumSectionTracker::new();
2783    let mut char_buf = [0u8; 24];
2784    let mut offset = DCMM_HEADER_LEN;
2785    while offset < bytes.len() {
2786        let Some(slice) = bytes.get(offset..) else {
2787            break;
2788        };
2789        if !tracker.escaped
2790            && slice.starts_with(&DC_203_BYTES)
2791            && !is_non_encapsulating_dc203_at(
2792                slice,
2793                false,
2794                tracker.resolver.as_ref(),
2795            )
2796        {
2797            let closed_section = tracker.on_binary_chunk(offset)?;
2798            let after_dc203 = offset.saturating_add(DC_203_BYTES.len());
2799            let Some(&type_byte) = bytes.get(after_dc203) else {
2800                return Err(DcMixedError::TruncatedEncapsulation {
2801                    offset,
2802                    expected: DC_203_BYTES.len().saturating_add(1),
2803                    available: bytes.len().saturating_sub(offset),
2804                }
2805                .into());
2806            };
2807            if matches!(type_byte, 1 | 4) {
2808                return Err(DcMixedError::UnsupportedLegacyType {
2809                    offset: after_dc203,
2810                    type_byte,
2811                }
2812                .into());
2813            }
2814            if !matches!(
2815                type_byte,
2816                TYPE_BINARY | TYPE_BINARY_METADATA | TYPE_BINARY_SHA256
2817            ) {
2818                return Err(DcMixedError::InvalidEncapsulationType {
2819                    offset: after_dc203,
2820                    type_byte,
2821                }
2822                .into());
2823            }
2824            let size_start = after_dc203.saturating_add(1);
2825            let size_end = size_start.saturating_add(16);
2826            let Some(size_bytes) = bytes.get(size_start..size_end) else {
2827                return Err(DcMixedError::TruncatedEncapsulation {
2828                    offset,
2829                    expected: DC_203_BYTES.len().saturating_add(17),
2830                    available: bytes.len().saturating_sub(offset),
2831                }
2832                .into());
2833            };
2834            let mut size_buf = [0u8; 16];
2835            size_buf.copy_from_slice(size_bytes);
2836            let size_u128 = u128::from_be_bytes(size_buf);
2837            let Ok(size_usize) = usize::try_from(size_u128) else {
2838                return Err(DcMixedError::SizeOverflow {
2839                    offset,
2840                    size: size_u128,
2841                }
2842                .into());
2843            };
2844            match type_byte {
2845                TYPE_BINARY => {
2846                    let payload_end = size_end.checked_add(size_usize).ok_or(
2847                        DcMixedError::SizeOverflow {
2848                            offset,
2849                            size: size_u128,
2850                        },
2851                    )?;
2852                    let Some(payload) = bytes.get(size_end..payload_end) else {
2853                        return Err(DcMixedError::TruncatedEncapsulation {
2854                            offset,
2855                            expected: payload_end.saturating_sub(offset),
2856                            available: bytes.len().saturating_sub(offset),
2857                        }
2858                        .into());
2859                    };
2860                    let dst_encap_start = out.len();
2861                    if let Some(closed) = closed_section {
2862                        let new_digest = closed
2863                            .recompute_untyped_sha256_digest(payload, offset)?;
2864                        out.extend_from_slice(&DC_203_BYTES_V1);
2865                        out.push(TYPE_BINARY);
2866                        out.extend_from_slice(
2867                            &u128::try_from(new_digest.len())?.to_be_bytes(),
2868                        );
2869                        out.extend_from_slice(&new_digest);
2870                    } else {
2871                        out.extend_from_slice(&DC_203_BYTES_V1);
2872                        out.push(TYPE_BINARY);
2873                        out.extend_from_slice(
2874                            &u128::try_from(payload.len())?.to_be_bytes(),
2875                        );
2876                        out.extend_from_slice(payload);
2877                    }
2878                    if tracker.has_active_section() {
2879                        if let (Some(src_encap), Some(dst_encap)) = (
2880                            bytes.get(offset..payload_end),
2881                            out.get(dst_encap_start..),
2882                        ) {
2883                            tracker
2884                                .update_active_sections(src_encap, dst_encap);
2885                        }
2886                    }
2887                    offset = payload_end;
2888                }
2889                TYPE_BINARY_METADATA => {
2890                    let meta_len_end =
2891                        size_end.checked_add(16).ok_or_else(|| {
2892                            DcMixedError::InvalidMetadata {
2893                                offset: size_end,
2894                                message: "Metadata length overflow".to_owned(),
2895                            }
2896                        })?;
2897                    let Some(meta_len_bytes) =
2898                        bytes.get(size_end..meta_len_end)
2899                    else {
2900                        return Err(DcMixedError::InvalidMetadata {
2901                            offset: size_end,
2902                            message: "Truncated metadata length".to_owned(),
2903                        }
2904                        .into());
2905                    };
2906                    let mut meta_len_buf = [0u8; 16];
2907                    meta_len_buf.copy_from_slice(meta_len_bytes);
2908                    let meta_len =
2909                        usize::try_from(u128::from_be_bytes(meta_len_buf))
2910                            .map_err(|_| DcMixedError::InvalidMetadata {
2911                                offset: size_end,
2912                                message: "Metadata exceeds addressable memory"
2913                                    .to_owned(),
2914                            })?;
2915                    let meta_end = meta_len_end
2916                        .checked_add(meta_len)
2917                        .ok_or_else(|| DcMixedError::InvalidMetadata {
2918                            offset: size_end,
2919                            message: "Metadata length overflow".to_owned(),
2920                        })?;
2921                    let Some(meta_dctf) = bytes.get(meta_len_end..meta_end)
2922                    else {
2923                        return Err(DcMixedError::InvalidMetadata {
2924                            offset: size_end,
2925                            message: "Truncated metadata".to_owned(),
2926                        }
2927                        .into());
2928                    };
2929                    let meta_dcstr =
2930                        DcStr::from_bytes(meta_dctf).map_err(|source| {
2931                            DcMixedError::InvalidUtf8e128 {
2932                                offset: meta_len_end
2933                                    .saturating_add(source.valid_up_to()),
2934                                source,
2935                            }
2936                        })?;
2937                    let payload_end = meta_end.checked_add(size_usize).ok_or(
2938                        DcMixedError::SizeOverflow {
2939                            offset,
2940                            size: size_u128,
2941                        },
2942                    )?;
2943                    let Some(payload) = bytes.get(meta_end..payload_end) else {
2944                        return Err(DcMixedError::TruncatedEncapsulation {
2945                            offset,
2946                            expected: payload_end.saturating_sub(offset),
2947                            available: bytes.len().saturating_sub(offset),
2948                        }
2949                        .into());
2950                    };
2951                    let mut meta_dcutf = Vec::with_capacity(meta_dcstr.len());
2952                    for ch in meta_dcstr.chars() {
2953                        let n = encode_utf_8e_128_buf(&mut char_buf, ch.0);
2954                        if let Some(s) = char_buf.get(..n) {
2955                            meta_dcutf.extend_from_slice(s);
2956                        }
2957                    }
2958                    let dst_encap_start = out.len();
2959                    if let Some(closed) = closed_section {
2960                        let new_digest = closed.recompute_typed_digest(
2961                            meta_dcstr,
2962                            payload,
2963                            offset,
2964                            tracker.resolver.as_ref(),
2965                        )?;
2966                        out.extend_from_slice(&DC_203_BYTES_V1);
2967                        out.push(TYPE_BINARY_METADATA);
2968                        out.extend_from_slice(
2969                            &u128::try_from(new_digest.len())?.to_be_bytes(),
2970                        );
2971                        out.extend_from_slice(
2972                            &u128::try_from(meta_dcutf.len())?.to_be_bytes(),
2973                        );
2974                        out.extend_from_slice(&meta_dcutf);
2975                        out.extend_from_slice(&new_digest);
2976                    } else {
2977                        out.extend_from_slice(&DC_203_BYTES_V1);
2978                        out.push(TYPE_BINARY_METADATA);
2979                        out.extend_from_slice(
2980                            &u128::try_from(payload.len())?.to_be_bytes(),
2981                        );
2982                        out.extend_from_slice(
2983                            &u128::try_from(meta_dcutf.len())?.to_be_bytes(),
2984                        );
2985                        out.extend_from_slice(&meta_dcutf);
2986                        out.extend_from_slice(payload);
2987                    }
2988                    if tracker.has_active_section() {
2989                        if let (Some(src_encap), Some(dst_encap)) = (
2990                            bytes.get(offset..payload_end),
2991                            out.get(dst_encap_start..),
2992                        ) {
2993                            tracker
2994                                .update_active_sections(src_encap, dst_encap);
2995                        }
2996                    }
2997                    offset = payload_end;
2998                }
2999                TYPE_BINARY_SHA256 => {
3000                    let sha_end = size_end.saturating_add(32);
3001                    let Some(sha_slice) = bytes.get(size_end..sha_end) else {
3002                        return Err(DcMixedError::TruncatedEncapsulation {
3003                            offset,
3004                            expected: sha_end.saturating_sub(offset),
3005                            available: bytes.len().saturating_sub(offset),
3006                        }
3007                        .into());
3008                    };
3009                    let mut expected_sha = [0u8; 32];
3010                    expected_sha.copy_from_slice(sha_slice);
3011                    let payload_end = sha_end.checked_add(size_usize).ok_or(
3012                        DcMixedError::SizeOverflow {
3013                            offset,
3014                            size: size_u128,
3015                        },
3016                    )?;
3017                    let Some(payload) = bytes.get(sha_end..payload_end) else {
3018                        return Err(DcMixedError::TruncatedEncapsulation {
3019                            offset,
3020                            expected: payload_end.saturating_sub(offset),
3021                            available: bytes.len().saturating_sub(offset),
3022                        }
3023                        .into());
3024                    };
3025                    let dst_encap_start = out.len();
3026                    if let Some(closed) = closed_section {
3027                        let new_digest = closed
3028                            .recompute_untyped_sha256_digest(payload, offset)?;
3029                        let new_sha = Sha256::digest(new_digest);
3030                        out.extend_from_slice(&DC_203_BYTES_V1);
3031                        out.push(TYPE_BINARY_SHA256);
3032                        out.extend_from_slice(
3033                            &u128::try_from(new_digest.len())?.to_be_bytes(),
3034                        );
3035                        out.extend_from_slice(new_sha.as_slice());
3036                        out.extend_from_slice(&new_digest);
3037                    } else {
3038                        out.extend_from_slice(&DC_203_BYTES_V1);
3039                        out.push(TYPE_BINARY_SHA256);
3040                        out.extend_from_slice(
3041                            &u128::try_from(payload.len())?.to_be_bytes(),
3042                        );
3043                        out.extend_from_slice(&expected_sha);
3044                        out.extend_from_slice(payload);
3045                    }
3046                    if tracker.has_active_section() {
3047                        if let (Some(src_encap), Some(dst_encap)) = (
3048                            bytes.get(offset..payload_end),
3049                            out.get(dst_encap_start..),
3050                        ) {
3051                            tracker
3052                                .update_active_sections(src_encap, dst_encap);
3053                        }
3054                    }
3055                    offset = payload_end;
3056                }
3057                _ => {
3058                    return Err(DcMixedError::InvalidEncapsulationType {
3059                        offset: after_dc203,
3060                        type_byte,
3061                    }
3062                    .into());
3063                }
3064            }
3065        } else {
3066            let Some((val, char_len)) = decode_dctf_buf(slice) else {
3067                return Err(DcMixedError::InvalidUtf8e128 {
3068                    offset,
3069                    source: DcUtfError {
3070                        valid_up_to: 0,
3071                        error_len: determine_dctf_error_len(slice),
3072                    },
3073                }
3074                .into());
3075            };
3076            let dst_start = out.len();
3077            let n = encode_utf_8e_128_buf(&mut char_buf, val);
3078            if let Some(s) = char_buf.get(..n) {
3079                out.extend_from_slice(s);
3080            }
3081            let dst_end = out.len();
3082            let next_offset = offset.saturating_add(char_len);
3083            if let (Some(src_char), Some(dst_char)) =
3084                (bytes.get(offset..next_offset), out.get(dst_start..dst_end))
3085            {
3086                tracker.on_char(DcChar(val), src_char, dst_char, offset)?;
3087            }
3088            offset = next_offset;
3089        }
3090    }
3091    tracker.finish()?;
3092
3093    Ok((out, ctb_formats_utilities::FormatLog::default()))
3094}
3095
3096/// Options controlling streaming validation and copying of `.dcmm` streams.
3097#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3098pub struct DcmmStreamOptions {
3099    /// When `true`, streaming validation does not abort on malformed sequences
3100    /// or checksum mismatches; instead, best-effort recovery is applied and
3101    /// warnings are recorded in the returned `FormatLog`.
3102    /// When `false` (default / strict mode), any error aborts immediately.
3103    pub best_effort: bool,
3104}
3105
3106/// Refills a sliding buffer from a reader up to `min_needed` bytes or EOF.
3107fn refill_stream_buffer<R: std::io::Read>(
3108    reader: &mut R,
3109    buffer: &mut Vec<u8>,
3110    min_needed: usize,
3111    eof_reached: &mut bool,
3112) -> Result<()> {
3113    let mut chunk = [0u8; 16 * 1024];
3114    while buffer.len() < min_needed && !*eof_reached {
3115        let n = reader.read(&mut chunk)?;
3116        if n == 0 {
3117            *eof_reached = true;
3118            break;
3119        }
3120        if let Some(slice) = chunk.get(..n) {
3121            buffer.extend_from_slice(slice);
3122        }
3123    }
3124    Ok(())
3125}
3126
3127/// Streams an encapsulation payload in chunks with bounded memory, updating an
3128/// optional hasher and verifying complete length.
3129#[expect(
3130    clippy::too_many_arguments,
3131    reason = "Streaming encapsulation helper requires stream offsets and diagnostic log"
3132)]
3133fn stream_encapsulation_payload<R: std::io::Read, W: std::io::Write>(
3134    reader: &mut R,
3135    writer: &mut W,
3136    buffer: &mut Vec<u8>,
3137    eof_reached: &mut bool,
3138    payload_size: usize,
3139    total_hdr_len: usize,
3140    enc_start: usize,
3141    mut hasher: Option<&mut ctb_formats_checksum::StreamingHasher>,
3142    mut section_tracker: Option<&mut ChecksumSectionTracker>,
3143    bytes_written: &mut u64,
3144    stream_offset: &mut usize,
3145    options: &DcmmStreamOptions,
3146    log: &mut ctb_formats_utilities::FormatLog,
3147) -> Result<()> {
3148    let mut remaining = payload_size;
3149    while remaining > 0 {
3150        if !buffer.is_empty() {
3151            let to_take = remaining.min(buffer.len());
3152            if let Some(slice) = buffer.get(..to_take) {
3153                if let Some(h) = hasher.as_deref_mut() {
3154                    h.update(slice);
3155                }
3156                if let Some(t) = section_tracker.as_deref_mut() {
3157                    if t.has_active_section() {
3158                        t.update_active_sections(slice, slice);
3159                    }
3160                }
3161                writer.write_all(slice)?;
3162                let to_take_u64 = u64::try_from(to_take)?;
3163                *bytes_written = bytes_written.saturating_add(to_take_u64);
3164                *stream_offset = stream_offset.saturating_add(to_take);
3165                remaining = remaining.saturating_sub(to_take);
3166            }
3167            buffer.drain(..to_take);
3168            continue;
3169        }
3170
3171        let mut chunk = [0u8; 64 * 1024];
3172        let to_read = remaining.min(chunk.len());
3173        let Some(slot) = chunk.get_mut(..to_read) else {
3174            break;
3175        };
3176        let n = reader.read(slot)?;
3177        if n == 0 {
3178            *eof_reached = true;
3179            break;
3180        }
3181        if let Some(slice) = chunk.get(..n) {
3182            if let Some(h) = hasher.as_deref_mut() {
3183                h.update(slice);
3184            }
3185            if let Some(t) = section_tracker.as_deref_mut() {
3186                if t.has_active_section() {
3187                    t.update_active_sections(slice, slice);
3188                }
3189            }
3190            writer.write_all(slice)?;
3191            let n_u64 = u64::try_from(n)?;
3192            *bytes_written = bytes_written.saturating_add(n_u64);
3193            *stream_offset = stream_offset.saturating_add(n);
3194            remaining = remaining.saturating_sub(n);
3195        }
3196    }
3197
3198    if remaining > 0 {
3199        if !options.best_effort {
3200            return Err(DcMixedError::TruncatedEncapsulation {
3201                offset: enc_start,
3202                expected: total_hdr_len.saturating_add(payload_size),
3203                available: total_hdr_len
3204                    .saturating_add(payload_size.saturating_sub(remaining)),
3205            }
3206            .into());
3207        }
3208        log.warn(&format!(
3209            "Truncated binary encapsulation at offset {enc_start}: missing {remaining} bytes"
3210        ));
3211    }
3212    Ok(())
3213}
3214
3215/// Validates the 21-byte DcMM header from reader, then streams the verified
3216/// `.dcmm` stream to writer with strict validation.
3217/// Returns the total bytes written.
3218pub fn validate_and_copy_dcmm_stream<R: std::io::Read, W: std::io::Write>(
3219    reader: &mut R,
3220    writer: &mut W,
3221) -> Result<u64> {
3222    let (bytes_written, log) = validate_and_copy_dcmm_stream_with_options(
3223        reader,
3224        writer,
3225        &DcmmStreamOptions::default(),
3226    )?;
3227    log.auto_log();
3228    Ok(bytes_written)
3229}
3230
3231/// Validates and copies a `.dcmm` stream from reader to writer according to
3232/// the specified validation options.
3233///
3234/// Under strict mode (`options.best_effort == false`), encounters of truncated
3235/// or malformed headers, invalid UTF-8e-128 text sequences, invalid encapsulation
3236/// headers, or checksum mismatches abort immediately and return the corresponding
3237/// [`DcMixedError`].
3238///
3239/// Under best-effort mode (`options.best_effort == true`), the stream copies as
3240/// much data as possible, substitutes corrupted text with replacement characters
3241/// (`\u{FFFD}`), ignores checksum mismatches, and records diagnostic warnings in
3242/// the returned [`FormatLog`].
3243pub fn validate_and_copy_dcmm_stream_with_options<
3244    R: std::io::Read,
3245    W: std::io::Write,
3246>(
3247    reader: &mut R,
3248    writer: &mut W,
3249    options: &DcmmStreamOptions,
3250) -> Result<(u64, ctb_formats_utilities::FormatLog)> {
3251    let mut log = ctb_formats_utilities::FormatLog::default();
3252    let mut bytes_written: u64 = 0;
3253    let mut stream_offset: usize = 0;
3254
3255    // 1. Validate Header (21 bytes)
3256    let mut header_buf = [0u8; DCMM_HEADER_LEN];
3257    let mut header_read = 0;
3258    while header_read < DCMM_HEADER_LEN {
3259        let Some(slot) = header_buf.get_mut(header_read..) else {
3260            break;
3261        };
3262        let n = reader.read(slot)?;
3263        if n == 0 {
3264            break;
3265        }
3266        header_read = header_read.saturating_add(n);
3267    }
3268
3269    let mut buffer: Vec<u8> = Vec::with_capacity(64 * 1024);
3270    let mut eof_reached = false;
3271    let mut is_v1 = false;
3272
3273    if header_read < DCMM_HEADER_LEN {
3274        if !options.best_effort {
3275            return Err(DcMixedError::TooShort { len: header_read }.into());
3276        }
3277        log.warn(&format!(
3278            "Truncated DcMixed header ({header_read} bytes, expected 21 bytes); synthesizing valid header"
3279        ));
3280        writer.write_all(&DCMM_MAGIC)?;
3281        writer.write_all(&DCMM_UUID)?;
3282        let hdr_len_u64 = u64::try_from(DCMM_HEADER_LEN)?;
3283        bytes_written = bytes_written.saturating_add(hdr_len_u64);
3284        stream_offset = stream_offset.saturating_add(DCMM_HEADER_LEN);
3285        if let Some(leftover) = header_buf.get(..header_read) {
3286            buffer.extend_from_slice(leftover);
3287        }
3288    } else {
3289        let magic_matches =
3290            header_buf.get(..5).is_some_and(|m| m == DCMM_MAGIC);
3291        let uuid_matches =
3292            header_buf.get(5..21).is_some_and(|u| u == DCMM_UUID);
3293        let uuid_v1_matches =
3294            header_buf.get(5..21).is_some_and(|u| u == DCMM_UUID_V1);
3295
3296        if magic_matches && uuid_v1_matches {
3297            is_v1 = true;
3298            writer.write_all(&DCMM_MAGIC)?;
3299            writer.write_all(&DCMM_UUID)?;
3300            let hdr_len_u64 = u64::try_from(DCMM_HEADER_LEN)?;
3301            bytes_written = bytes_written.saturating_add(hdr_len_u64);
3302            stream_offset = stream_offset.saturating_add(DCMM_HEADER_LEN);
3303        } else if magic_matches && uuid_matches {
3304            writer.write_all(&header_buf)?;
3305            let hdr_len_u64 = u64::try_from(DCMM_HEADER_LEN)?;
3306            bytes_written = bytes_written.saturating_add(hdr_len_u64);
3307            stream_offset = stream_offset.saturating_add(DCMM_HEADER_LEN);
3308        } else if !options.best_effort {
3309            if !magic_matches {
3310                let mut found = [0u8; 5];
3311                if let Some(m) = header_buf.get(..5) {
3312                    found.copy_from_slice(m);
3313                }
3314                return Err(DcMixedError::InvalidMagic { found }.into());
3315            }
3316            let mut found = [0u8; 16];
3317            if let Some(u) = header_buf.get(5..21) {
3318                found.copy_from_slice(u);
3319            }
3320            return Err(DcMixedError::InvalidUuid { found }.into());
3321        } else {
3322            log.warn("Corrupted DcMixed header magic or UUID; synthesizing valid header");
3323            writer.write_all(&DCMM_MAGIC)?;
3324            writer.write_all(&DCMM_UUID)?;
3325            let hdr_len_u64 = u64::try_from(DCMM_HEADER_LEN)?;
3326            bytes_written = bytes_written.saturating_add(hdr_len_u64);
3327            stream_offset = stream_offset.saturating_add(DCMM_HEADER_LEN);
3328        }
3329    }
3330
3331    let dc203_bytes: &[u8] = if is_v1 {
3332        &DC_203_BYTES_V1
3333    } else {
3334        &DC_203_BYTES
3335    };
3336    let dc203_len = dc203_bytes.len();
3337    let encap_type_idx = dc203_len;
3338    let encap_size_start = dc203_len.saturating_add(1);
3339    let encap_size_end = encap_size_start.saturating_add(16);
3340    let encap_sha256_end = encap_size_end.saturating_add(32);
3341    let encap_meta_len_end = encap_size_end.saturating_add(16);
3342
3343    let mut tracker = ChecksumSectionTracker::new();
3344    let mut transcoded_text: Vec<u8> = if is_v1 {
3345        Vec::with_capacity(64 * 1024)
3346    } else {
3347        Vec::new()
3348    };
3349    let mut escaped = false;
3350
3351    // 2. Stream & Validate Payload
3352    loop {
3353        if buffer.len() < 24 && !eof_reached {
3354            refill_stream_buffer(
3355                reader,
3356                &mut buffer,
3357                64 * 1024,
3358                &mut eof_reached,
3359            )?;
3360        }
3361
3362        if buffer.is_empty() && eof_reached {
3363            break;
3364        }
3365
3366        // Check if buffer starts with an encapsulation header
3367        if !eof_reached
3368            && !escaped
3369            && (buffer.starts_with(dc203_bytes)
3370                || dc203_bytes.starts_with(&buffer))
3371        {
3372            refill_stream_buffer(
3373                reader,
3374                &mut buffer,
3375                dc203_len.saturating_add(24),
3376                &mut eof_reached,
3377            )?;
3378        }
3379        let is_encapsulation = !escaped
3380            && buffer.starts_with(dc203_bytes)
3381            && !is_non_encapsulating_dc203_at(
3382                &buffer,
3383                is_v1,
3384                tracker.resolver.as_ref(),
3385            );
3386
3387        if is_encapsulation {
3388            let enc_start = stream_offset;
3389            let closed_section = if is_v1 {
3390                match tracker.on_binary_chunk(enc_start) {
3391                    Ok(cs) => cs,
3392                    Err(err) => {
3393                        if !options.best_effort {
3394                            return Err(err);
3395                        }
3396                        log.warn(&format!("{err:#}"));
3397                        None
3398                    }
3399                }
3400            } else {
3401                None
3402            };
3403
3404            if buffer.len() < encap_size_start && !eof_reached {
3405                refill_stream_buffer(
3406                    reader,
3407                    &mut buffer,
3408                    encap_size_start,
3409                    &mut eof_reached,
3410                )?;
3411            }
3412            if buffer.len() < encap_size_start {
3413                if !options.best_effort {
3414                    return Err(DcMixedError::TruncatedEncapsulation {
3415                        offset: enc_start,
3416                        expected: encap_size_start,
3417                        available: buffer.len(),
3418                    }
3419                    .into());
3420                }
3421                log.warn(&format!(
3422                    "Truncated encapsulation header at offset {enc_start}"
3423                ));
3424                writer.write_all(&buffer)?;
3425                let len_u64 = u64::try_from(buffer.len())?;
3426                bytes_written = bytes_written.saturating_add(len_u64);
3427                buffer.clear();
3428                break;
3429            }
3430
3431            let Some(&type_byte) = buffer.get(encap_type_idx) else {
3432                unreachable!()
3433            };
3434            let mut effective_type = type_byte;
3435
3436            if matches!(type_byte, 1 | 4) {
3437                if !options.best_effort {
3438                    return Err(DcMixedError::UnsupportedLegacyType {
3439                        offset: enc_start.saturating_add(encap_type_idx),
3440                        type_byte,
3441                    }
3442                    .into());
3443                }
3444                log.warn(&format!(
3445                    "Unsupported legacy encapsulation type {type_byte} at offset {}; treating as binary",
3446                    enc_start.saturating_add(encap_type_idx)
3447                ));
3448                effective_type = if type_byte == 4 {
3449                    TYPE_BINARY_SHA256
3450                } else {
3451                    TYPE_BINARY
3452                };
3453            } else if type_byte != TYPE_BINARY
3454                && type_byte != TYPE_BINARY_METADATA
3455                && type_byte != TYPE_BINARY_SHA256
3456            {
3457                if !options.best_effort {
3458                    return Err(DcMixedError::InvalidEncapsulationType {
3459                        offset: enc_start.saturating_add(encap_type_idx),
3460                        type_byte,
3461                    }
3462                    .into());
3463                }
3464                log.warn(&format!(
3465                    "Invalid encapsulation type {type_byte} at offset {}",
3466                    enc_start.saturating_add(encap_type_idx)
3467                ));
3468                writer.write_all("\u{FFFD}".as_bytes())?;
3469                let rep_len = u64::try_from("\u{FFFD}".len())?;
3470                bytes_written = bytes_written.saturating_add(rep_len);
3471                stream_offset = stream_offset.saturating_add(encap_size_start);
3472                buffer.drain(..encap_size_start);
3473                continue;
3474            }
3475
3476            // Read payload size (16 bytes at encap_size_start..encap_size_end)
3477            if buffer.len() < encap_size_end && !eof_reached {
3478                refill_stream_buffer(
3479                    reader,
3480                    &mut buffer,
3481                    encap_size_end,
3482                    &mut eof_reached,
3483                )?;
3484            }
3485            if buffer.len() < encap_size_end {
3486                if !options.best_effort {
3487                    return Err(DcMixedError::TruncatedEncapsulation {
3488                        offset: enc_start,
3489                        expected: encap_size_end,
3490                        available: buffer.len(),
3491                    }
3492                    .into());
3493                }
3494                log.warn(&format!(
3495                    "Truncated encapsulation size header at offset {enc_start}"
3496                ));
3497                writer.write_all(&buffer)?;
3498                let len_u64 = u64::try_from(buffer.len())?;
3499                bytes_written = bytes_written.saturating_add(len_u64);
3500                buffer.clear();
3501                break;
3502            }
3503
3504            let mut size_buf = [0u8; 16];
3505            if let Some(s) = buffer.get(encap_size_start..encap_size_end) {
3506                size_buf.copy_from_slice(s);
3507            }
3508            let size_u128 = u128::from_be_bytes(size_buf);
3509            let payload_size = if let Ok(s) = usize::try_from(size_u128) {
3510                s
3511            } else {
3512                if !options.best_effort {
3513                    return Err(DcMixedError::SizeOverflow {
3514                        offset: enc_start,
3515                        size: size_u128,
3516                    }
3517                    .into());
3518                }
3519                log.warn(&format!(
3520                    "Encapsulation size {size_u128} overflows addressable memory at offset {enc_start}"
3521                ));
3522                usize::MAX
3523            };
3524
3525            match effective_type {
3526                TYPE_BINARY => {
3527                    let total_hdr_len = encap_size_end;
3528                    if let Some(closed) = closed_section {
3529                        let total_len = total_hdr_len
3530                            .checked_add(payload_size)
3531                            .ok_or(DcMixedError::SizeOverflow {
3532                                offset: enc_start,
3533                                size: size_u128,
3534                            })?;
3535                        if buffer.len() < total_len && !eof_reached {
3536                            refill_stream_buffer(
3537                                reader,
3538                                &mut buffer,
3539                                total_len,
3540                                &mut eof_reached,
3541                            )?;
3542                        }
3543                        let Some(payload) =
3544                            buffer.get(total_hdr_len..total_len)
3545                        else {
3546                            return Err(DcMixedError::TruncatedEncapsulation {
3547                                offset: enc_start,
3548                                expected: total_len,
3549                                available: buffer.len(),
3550                            }
3551                            .into());
3552                        };
3553                        let new_digest = closed
3554                            .recompute_untyped_sha256_digest(
3555                                payload, enc_start,
3556                            )?;
3557                        let mut dst_encap = Vec::with_capacity(
3558                            ENCAP_SIZE_END.saturating_add(new_digest.len()),
3559                        );
3560                        dst_encap.extend_from_slice(&DC_203_BYTES);
3561                        dst_encap.push(TYPE_BINARY);
3562                        dst_encap.extend_from_slice(
3563                            &u128::try_from(new_digest.len())?.to_be_bytes(),
3564                        );
3565                        dst_encap.extend_from_slice(&new_digest);
3566                        if tracker.has_active_section() {
3567                            if let Some(src_encap) = buffer.get(..total_len) {
3568                                tracker.update_active_sections(
3569                                    src_encap, &dst_encap,
3570                                );
3571                            }
3572                        }
3573                        writer.write_all(&dst_encap)?;
3574                        bytes_written = bytes_written
3575                            .saturating_add(u64::try_from(dst_encap.len())?);
3576                        stream_offset = stream_offset.saturating_add(total_len);
3577                        buffer.drain(..total_len);
3578                    } else {
3579                        if is_v1 {
3580                            let mut dst_hdr = [0u8; ENCAP_SIZE_END];
3581                            if let Some(slot) = dst_hdr.get_mut(..4) {
3582                                slot.copy_from_slice(&DC_203_BYTES);
3583                            }
3584                            if let Some(slot) = dst_hdr.get_mut(ENCAP_TYPE_IDX)
3585                            {
3586                                *slot = TYPE_BINARY;
3587                            }
3588                            if let Some(slot) = dst_hdr
3589                                .get_mut(ENCAP_SIZE_START..ENCAP_SIZE_END)
3590                            {
3591                                slot.copy_from_slice(&size_buf);
3592                            }
3593                            if tracker.has_active_section() {
3594                                if let Some(src_hdr) =
3595                                    buffer.get(..total_hdr_len)
3596                                {
3597                                    tracker.update_active_sections(
3598                                        src_hdr, &dst_hdr,
3599                                    );
3600                                }
3601                            }
3602                            writer.write_all(&dst_hdr)?;
3603                            bytes_written = bytes_written
3604                                .saturating_add(u64::try_from(dst_hdr.len())?);
3605                        } else {
3606                            if let Some(hdr) = buffer.get(..total_hdr_len) {
3607                                writer.write_all(hdr)?;
3608                            }
3609                            let hdr_len_u64 = u64::try_from(total_hdr_len)?;
3610                            bytes_written =
3611                                bytes_written.saturating_add(hdr_len_u64);
3612                        }
3613                        stream_offset =
3614                            stream_offset.saturating_add(total_hdr_len);
3615                        buffer.drain(..total_hdr_len);
3616
3617                        stream_encapsulation_payload(
3618                            reader,
3619                            writer,
3620                            &mut buffer,
3621                            &mut eof_reached,
3622                            payload_size,
3623                            total_hdr_len,
3624                            enc_start,
3625                            None,
3626                            is_v1.then_some(&mut tracker),
3627                            &mut bytes_written,
3628                            &mut stream_offset,
3629                            options,
3630                            &mut log,
3631                        )?;
3632                    }
3633                }
3634                TYPE_BINARY_SHA256 => {
3635                    let total_hdr_len = encap_sha256_end;
3636                    if buffer.len() < total_hdr_len && !eof_reached {
3637                        refill_stream_buffer(
3638                            reader,
3639                            &mut buffer,
3640                            total_hdr_len,
3641                            &mut eof_reached,
3642                        )?;
3643                    }
3644                    if buffer.len() < total_hdr_len {
3645                        if !options.best_effort {
3646                            return Err(DcMixedError::TruncatedEncapsulation {
3647                                offset: enc_start,
3648                                expected: total_hdr_len,
3649                                available: buffer.len(),
3650                            }
3651                            .into());
3652                        }
3653                        log.warn(&format!("Truncated SHA-256 encapsulation header at offset {enc_start}"));
3654                        writer.write_all(&buffer)?;
3655                        let len_u64 = u64::try_from(buffer.len())?;
3656                        bytes_written = bytes_written.saturating_add(len_u64);
3657                        buffer.clear();
3658                        break;
3659                    }
3660
3661                    let mut expected_sha = [0u8; 32];
3662                    if let Some(sha_slice) =
3663                        buffer.get(encap_size_end..encap_sha256_end)
3664                    {
3665                        expected_sha.copy_from_slice(sha_slice);
3666                    }
3667
3668                    if let Some(closed) = closed_section {
3669                        let total_len = total_hdr_len
3670                            .checked_add(payload_size)
3671                            .ok_or(DcMixedError::SizeOverflow {
3672                                offset: enc_start,
3673                                size: size_u128,
3674                            })?;
3675                        if buffer.len() < total_len && !eof_reached {
3676                            refill_stream_buffer(
3677                                reader,
3678                                &mut buffer,
3679                                total_len,
3680                                &mut eof_reached,
3681                            )?;
3682                        }
3683                        let Some(payload) =
3684                            buffer.get(total_hdr_len..total_len)
3685                        else {
3686                            return Err(DcMixedError::TruncatedEncapsulation {
3687                                offset: enc_start,
3688                                expected: total_len,
3689                                available: buffer.len(),
3690                            }
3691                            .into());
3692                        };
3693                        let actual = Sha256::digest(payload);
3694                        if actual.as_slice() != expected_sha.as_slice() {
3695                            let mut actual_arr = [0u8; 32];
3696                            actual_arr.copy_from_slice(actual.as_slice());
3697                            return Err(DcMixedError::ChecksumMismatch {
3698                                offset: enc_start,
3699                                expected: expected_sha,
3700                                actual: actual_arr,
3701                            }
3702                            .into());
3703                        }
3704                        let new_digest = closed
3705                            .recompute_untyped_sha256_digest(
3706                                payload, enc_start,
3707                            )?;
3708                        let new_sha = Sha256::digest(new_digest);
3709                        let mut dst_encap = Vec::with_capacity(
3710                            ENCAP_SHA256_END.saturating_add(new_digest.len()),
3711                        );
3712                        dst_encap.extend_from_slice(&DC_203_BYTES);
3713                        dst_encap.push(TYPE_BINARY_SHA256);
3714                        dst_encap.extend_from_slice(
3715                            &u128::try_from(new_digest.len())?.to_be_bytes(),
3716                        );
3717                        dst_encap.extend_from_slice(new_sha.as_slice());
3718                        dst_encap.extend_from_slice(&new_digest);
3719                        if tracker.has_active_section() {
3720                            if let Some(src_encap) = buffer.get(..total_len) {
3721                                tracker.update_active_sections(
3722                                    src_encap, &dst_encap,
3723                                );
3724                            }
3725                        }
3726                        writer.write_all(&dst_encap)?;
3727                        bytes_written = bytes_written
3728                            .saturating_add(u64::try_from(dst_encap.len())?);
3729                        stream_offset = stream_offset.saturating_add(total_len);
3730                        buffer.drain(..total_len);
3731                    } else {
3732                        if is_v1 {
3733                            let mut dst_hdr = [0u8; ENCAP_SHA256_END];
3734                            if let Some(slot) = dst_hdr.get_mut(..4) {
3735                                slot.copy_from_slice(&DC_203_BYTES);
3736                            }
3737                            if let Some(slot) = dst_hdr.get_mut(ENCAP_TYPE_IDX)
3738                            {
3739                                *slot = TYPE_BINARY_SHA256;
3740                            }
3741                            if let Some(slot) = dst_hdr
3742                                .get_mut(ENCAP_SIZE_START..ENCAP_SIZE_END)
3743                            {
3744                                slot.copy_from_slice(&size_buf);
3745                            }
3746                            if let Some(slot) = dst_hdr
3747                                .get_mut(ENCAP_SIZE_END..ENCAP_SHA256_END)
3748                            {
3749                                slot.copy_from_slice(&expected_sha);
3750                            }
3751                            if tracker.has_active_section() {
3752                                if let Some(src_hdr) =
3753                                    buffer.get(..total_hdr_len)
3754                                {
3755                                    tracker.update_active_sections(
3756                                        src_hdr, &dst_hdr,
3757                                    );
3758                                }
3759                            }
3760                            writer.write_all(&dst_hdr)?;
3761                            bytes_written = bytes_written
3762                                .saturating_add(u64::try_from(dst_hdr.len())?);
3763                        } else {
3764                            if let Some(hdr) = buffer.get(..total_hdr_len) {
3765                                writer.write_all(hdr)?;
3766                            }
3767                            let hdr_len_u64 = u64::try_from(total_hdr_len)?;
3768                            bytes_written =
3769                                bytes_written.saturating_add(hdr_len_u64);
3770                        }
3771                        stream_offset =
3772                            stream_offset.saturating_add(total_hdr_len);
3773                        buffer.drain(..total_hdr_len);
3774
3775                        let mut hasher =
3776                            Some(ctb_formats_checksum::StreamingHasher::new(
3777                                SupportedHashFormat::Sha256,
3778                            ));
3779
3780                        stream_encapsulation_payload(
3781                            reader,
3782                            writer,
3783                            &mut buffer,
3784                            &mut eof_reached,
3785                            payload_size,
3786                            total_hdr_len,
3787                            enc_start,
3788                            hasher.as_mut(),
3789                            is_v1.then_some(&mut tracker),
3790                            &mut bytes_written,
3791                            &mut stream_offset,
3792                            options,
3793                            &mut log,
3794                        )?;
3795
3796                        if let Some(h) = hasher {
3797                            let actual_digest = h.finalize();
3798                            if actual_digest.as_slice()
3799                                != expected_sha.as_slice()
3800                            {
3801                                if !options.best_effort {
3802                                    let mut actual_arr = [0u8; 32];
3803                                    actual_arr.copy_from_slice(&actual_digest);
3804                                    return Err(
3805                                        DcMixedError::ChecksumMismatch {
3806                                            offset: enc_start,
3807                                            expected: expected_sha,
3808                                            actual: actual_arr,
3809                                        }
3810                                        .into(),
3811                                    );
3812                                }
3813                                log.warn(&format!(
3814                                    "SHA-256 checksum mismatch at offset {enc_start}: expected {expected_sha:?}, actual {actual_digest:?}"
3815                                ));
3816                            }
3817                        }
3818                    }
3819                }
3820                TYPE_BINARY_METADATA => {
3821                    if buffer.len() < encap_meta_len_end && !eof_reached {
3822                        refill_stream_buffer(
3823                            reader,
3824                            &mut buffer,
3825                            encap_meta_len_end,
3826                            &mut eof_reached,
3827                        )?;
3828                    }
3829                    if buffer.len() < encap_meta_len_end {
3830                        if !options.best_effort {
3831                            return Err(DcMixedError::InvalidMetadata {
3832                                offset: enc_start
3833                                    .saturating_add(encap_size_end),
3834                                message: "Truncated metadata length".to_owned(),
3835                            }
3836                            .into());
3837                        }
3838                        log.warn(&format!(
3839                            "Truncated metadata length at offset {enc_start}"
3840                        ));
3841                        writer.write_all(&buffer)?;
3842                        let len_u64 = u64::try_from(buffer.len())?;
3843                        bytes_written = bytes_written.saturating_add(len_u64);
3844                        buffer.clear();
3845                        break;
3846                    }
3847
3848                    let mut meta_len_buf = [0u8; 16];
3849                    if let Some(s) =
3850                        buffer.get(encap_size_end..encap_meta_len_end)
3851                    {
3852                        meta_len_buf.copy_from_slice(s);
3853                    }
3854                    let meta_len_u128 = u128::from_be_bytes(meta_len_buf);
3855                    let meta_len = if let Ok(l) = usize::try_from(meta_len_u128)
3856                    {
3857                        l
3858                    } else {
3859                        if !options.best_effort {
3860                            return Err(DcMixedError::InvalidMetadata {
3861                                offset: enc_start
3862                                    .saturating_add(encap_size_end),
3863                                message: "Metadata exceeds addressable memory"
3864                                    .to_owned(),
3865                            }
3866                            .into());
3867                        }
3868                        log.warn(&format!("Metadata exceeds addressable memory at offset {enc_start}"));
3869                        0
3870                    };
3871
3872                    let total_hdr_len =
3873                        encap_meta_len_end.saturating_add(meta_len);
3874                    if buffer.len() < total_hdr_len && !eof_reached {
3875                        refill_stream_buffer(
3876                            reader,
3877                            &mut buffer,
3878                            total_hdr_len,
3879                            &mut eof_reached,
3880                        )?;
3881                    }
3882                    if buffer.len() < total_hdr_len {
3883                        if !options.best_effort {
3884                            return Err(DcMixedError::InvalidMetadata {
3885                                offset: enc_start
3886                                    .saturating_add(encap_size_end),
3887                                message: "Truncated metadata".to_owned(),
3888                            }
3889                            .into());
3890                        }
3891                        log.warn(&format!(
3892                            "Truncated metadata at offset {enc_start}"
3893                        ));
3894                        writer.write_all(&buffer)?;
3895                        let len_u64 = u64::try_from(buffer.len())?;
3896                        bytes_written = bytes_written.saturating_add(len_u64);
3897                        buffer.clear();
3898                        break;
3899                    }
3900
3901                    let Some(meta_bytes) =
3902                        buffer.get(encap_meta_len_end..total_hdr_len)
3903                    else {
3904                        unreachable!(
3905                            "Buffer length was verified to be >= total_hdr_len"
3906                        );
3907                    };
3908                    let meta_owned: Option<DcString> = if is_v1 {
3909                        match DcString::from_dcutf(meta_bytes.to_vec()) {
3910                            Ok(s) => Some(s),
3911                            Err(source) => {
3912                                if !options.best_effort {
3913                                    return Err(
3914                                        DcMixedError::InvalidUtf8e128 {
3915                                            offset: enc_start
3916                                                .saturating_add(
3917                                                    encap_meta_len_end,
3918                                                )
3919                                                .saturating_add(
3920                                                    source.valid_up_to(),
3921                                                ),
3922                                            source,
3923                                        }
3924                                        .into(),
3925                                    );
3926                                }
3927                                log.warn(&format!(
3928                                    "Invalid DcUtf in encapsulation metadata at offset {}",
3929                                    enc_start.saturating_add(encap_meta_len_end)
3930                                ));
3931                                None
3932                            }
3933                        }
3934                    } else {
3935                        match DcStr::from_bytes(meta_bytes) {
3936                            Ok(s) => Some(s.to_owned()),
3937                            Err(source) => {
3938                                if !options.best_effort {
3939                                    return Err(
3940                                        DcMixedError::InvalidUtf8e128 {
3941                                            offset: enc_start
3942                                                .saturating_add(
3943                                                    encap_meta_len_end,
3944                                                )
3945                                                .saturating_add(
3946                                                    source.valid_up_to(),
3947                                                ),
3948                                            source,
3949                                        }
3950                                        .into(),
3951                                    );
3952                                }
3953                                log.warn(&format!(
3954                                    "Invalid DcTF in encapsulation metadata at offset {}",
3955                                    enc_start.saturating_add(encap_meta_len_end)
3956                                ));
3957                                None
3958                            }
3959                        }
3960                    };
3961
3962                    if let Some(closed) = closed_section {
3963                        let total_len = total_hdr_len
3964                            .checked_add(payload_size)
3965                            .ok_or(DcMixedError::SizeOverflow {
3966                                offset: enc_start,
3967                                size: size_u128,
3968                            })?;
3969                        if buffer.len() < total_len && !eof_reached {
3970                            refill_stream_buffer(
3971                                reader,
3972                                &mut buffer,
3973                                total_len,
3974                                &mut eof_reached,
3975                            )?;
3976                        }
3977                        let Some(payload) =
3978                            buffer.get(total_hdr_len..total_len)
3979                        else {
3980                            return Err(DcMixedError::TruncatedEncapsulation {
3981                                offset: enc_start,
3982                                expected: total_len,
3983                                available: buffer.len(),
3984                            }
3985                            .into());
3986                        };
3987                        let meta_ref = meta_owned.as_deref().context(
3988                            "Section digest metadata must be valid DcTF",
3989                        )?;
3990                        let new_digest = closed.recompute_typed_digest(
3991                            meta_ref,
3992                            payload,
3993                            enc_start,
3994                            tracker.resolver.as_ref(),
3995                        )?;
3996                        let meta_dctf_bytes = meta_ref.as_bytes();
3997                        let mut dst_encap = Vec::with_capacity(
3998                            ENCAP_META_LEN_END
3999                                .saturating_add(meta_dctf_bytes.len())
4000                                .saturating_add(new_digest.len()),
4001                        );
4002                        dst_encap.extend_from_slice(&DC_203_BYTES);
4003                        dst_encap.push(TYPE_BINARY_METADATA);
4004                        dst_encap.extend_from_slice(
4005                            &u128::try_from(new_digest.len())?.to_be_bytes(),
4006                        );
4007                        dst_encap.extend_from_slice(
4008                            &u128::try_from(meta_dctf_bytes.len())?
4009                                .to_be_bytes(),
4010                        );
4011                        dst_encap.extend_from_slice(meta_dctf_bytes);
4012                        dst_encap.extend_from_slice(&new_digest);
4013                        if tracker.has_active_section() {
4014                            if let Some(src_encap) = buffer.get(..total_len) {
4015                                tracker.update_active_sections(
4016                                    src_encap, &dst_encap,
4017                                );
4018                            }
4019                        }
4020                        writer.write_all(&dst_encap)?;
4021                        bytes_written = bytes_written
4022                            .saturating_add(u64::try_from(dst_encap.len())?);
4023                        stream_offset = stream_offset.saturating_add(total_len);
4024                        buffer.drain(..total_len);
4025                    } else {
4026                        let checksum_spec = if let Some(meta) =
4027                            meta_owned.as_deref()
4028                        {
4029                            match crate::encapsulation::parse_checksum_spec(
4030                                meta,
4031                            ) {
4032                                Ok(cs) => cs,
4033                                Err(err) => {
4034                                    if !options.best_effort {
4035                                        return Err(
4036                                            DcMixedError::InvalidMetadata {
4037                                                offset: enc_start,
4038                                                message: format!("{err:#}"),
4039                                            }
4040                                            .into(),
4041                                        );
4042                                    }
4043                                    log.warn(&format!("Invalid metadata syntax at offset {enc_start}: {err:#}"));
4044                                    None
4045                                }
4046                            }
4047                        } else {
4048                            None
4049                        };
4050
4051                        if is_v1 {
4052                            // Reason for fallback: when section metadata is absent (meta_owned is None), metadata payload defaults to an empty byte slice.
4053                            let meta_dctf_bytes = meta_owned
4054                                .as_deref()
4055                                .map_or(&[][..], DcStr::as_bytes);
4056                            let mut dst_hdr = Vec::with_capacity(
4057                                ENCAP_META_LEN_END
4058                                    .saturating_add(meta_dctf_bytes.len()),
4059                            );
4060                            dst_hdr.extend_from_slice(&DC_203_BYTES);
4061                            dst_hdr.push(TYPE_BINARY_METADATA);
4062                            dst_hdr.extend_from_slice(&size_buf);
4063                            dst_hdr.extend_from_slice(
4064                                &u128::try_from(meta_dctf_bytes.len())?
4065                                    .to_be_bytes(),
4066                            );
4067                            dst_hdr.extend_from_slice(meta_dctf_bytes);
4068                            if tracker.has_active_section() {
4069                                if let Some(src_hdr) =
4070                                    buffer.get(..total_hdr_len)
4071                                {
4072                                    tracker.update_active_sections(
4073                                        src_hdr, &dst_hdr,
4074                                    );
4075                                }
4076                            }
4077                            writer.write_all(&dst_hdr)?;
4078                            bytes_written = bytes_written
4079                                .saturating_add(u64::try_from(dst_hdr.len())?);
4080                        } else {
4081                            if let Some(hdr) = buffer.get(..total_hdr_len) {
4082                                writer.write_all(hdr)?;
4083                            }
4084                            let hdr_len_u64 = u64::try_from(total_hdr_len)?;
4085                            bytes_written =
4086                                bytes_written.saturating_add(hdr_len_u64);
4087                        }
4088                        stream_offset =
4089                            stream_offset.saturating_add(total_hdr_len);
4090                        buffer.drain(..total_hdr_len);
4091
4092                        let mut hasher = checksum_spec.as_ref().map(|spec| {
4093                            ctb_formats_checksum::StreamingHasher::new(
4094                                spec.algorithm,
4095                            )
4096                        });
4097
4098                        stream_encapsulation_payload(
4099                            reader,
4100                            writer,
4101                            &mut buffer,
4102                            &mut eof_reached,
4103                            payload_size,
4104                            total_hdr_len,
4105                            enc_start,
4106                            hasher.as_mut(),
4107                            is_v1.then_some(&mut tracker),
4108                            &mut bytes_written,
4109                            &mut stream_offset,
4110                            options,
4111                            &mut log,
4112                        )?;
4113
4114                        if let (Some(h), Some(spec)) = (hasher, checksum_spec) {
4115                            let actual_digest = h.finalize();
4116                            if actual_digest != spec.expected_digest {
4117                                if !options.best_effort {
4118                                    return Err(DcMixedError::InvalidMetadata {
4119                                        offset: enc_start,
4120                                        message: format!(
4121                                            "Encapsulation checksum mismatch ({:?})",
4122                                            spec.algorithm
4123                                        ),
4124                                    }.into());
4125                                }
4126                                log.warn(&format!(
4127                                    "Encapsulation checksum mismatch ({:?}) at offset {enc_start}",
4128                                    spec.algorithm
4129                                ));
4130                            }
4131                        }
4132                    }
4133                }
4134                _ => unreachable!(),
4135            }
4136        } else {
4137            // Text Region
4138            let mut pos = 0;
4139            if is_v1 {
4140                transcoded_text.clear();
4141            }
4142            let mut dctf_buf = [0u8; 24];
4143            while pos < buffer.len() {
4144                let Some(slice) = buffer.get(pos..) else {
4145                    break;
4146                };
4147                if pos > 0
4148                    && !escaped
4149                    && (slice.starts_with(dc203_bytes)
4150                        || (!eof_reached && dc203_bytes.starts_with(slice)))
4151                {
4152                    break;
4153                }
4154                let decoded = if is_v1 {
4155                    decode_utf_8e_128_buf(slice)
4156                } else {
4157                    decode_dctf_buf(slice)
4158                };
4159                if let Some((val, char_len)) = decoded {
4160                    let ch = DcChar(val);
4161                    escaped = !escaped
4162                        && ch.fills_role_with(
4163                            DcRole::Escape,
4164                            tracker.resolver.as_ref(),
4165                        );
4166                    if is_v1 {
4167                        let dctf_len = encode_dctf_buf(&mut dctf_buf, val);
4168                        if let (Some(src_char), Some(dst_char)) =
4169                            (slice.get(..char_len), dctf_buf.get(..dctf_len))
4170                        {
4171                            if let Err(err) = tracker.on_char(
4172                                ch,
4173                                src_char,
4174                                dst_char,
4175                                stream_offset.saturating_add(pos),
4176                            ) {
4177                                if !options.best_effort {
4178                                    return Err(err);
4179                                }
4180                                log.warn(&format!("{err:#}"));
4181                            }
4182                            transcoded_text.extend_from_slice(dst_char);
4183                        }
4184                    }
4185                    pos = pos.saturating_add(char_len);
4186                } else {
4187                    if !eof_reached && slice.len() < 24 {
4188                        break;
4189                    }
4190                    escaped = false;
4191                    let err_len = if is_v1 {
4192                        determine_utf_8e_128_error_len(slice)
4193                    } else {
4194                        determine_dctf_error_len(slice)
4195                    };
4196                    if !options.best_effort {
4197                        return Err(DcMixedError::InvalidUtf8e128 {
4198                            offset: stream_offset.saturating_add(pos),
4199                            source: DcUtfError {
4200                                valid_up_to: 0,
4201                                error_len: err_len,
4202                            },
4203                        }
4204                        .into());
4205                    }
4206                    if pos > 0 {
4207                        if is_v1 {
4208                            writer.write_all(&transcoded_text)?;
4209                            let len_u64 = u64::try_from(transcoded_text.len())?;
4210                            bytes_written =
4211                                bytes_written.saturating_add(len_u64);
4212                            transcoded_text.clear();
4213                        } else if let Some(valid_slice) = buffer.get(..pos) {
4214                            writer.write_all(valid_slice)?;
4215                            let len_u64 = u64::try_from(pos)?;
4216                            bytes_written =
4217                                bytes_written.saturating_add(len_u64);
4218                        }
4219                        stream_offset = stream_offset.saturating_add(pos);
4220                        buffer.drain(..pos);
4221                        pos = 0;
4222                    }
4223                    // Reason for fallback: when error length cannot be determined from truncated sequence, consume remaining buffer in best-effort recovery.
4224                    let step = err_len
4225                        .unwrap_or(buffer.len())
4226                        .max(1)
4227                        .min(buffer.len());
4228                    log.warn(&format!(
4229                        "Invalid DcTF sequence at offset {stream_offset}: substituting replacement character"
4230                    ));
4231                    writer.write_all("\u{FFFD}".as_bytes())?;
4232                    let rep_len = u64::try_from("\u{FFFD}".len())?;
4233                    bytes_written = bytes_written.saturating_add(rep_len);
4234                    stream_offset = stream_offset.saturating_add(step);
4235                    buffer.drain(..step);
4236                    continue;
4237                }
4238            }
4239
4240            if pos > 0 {
4241                if is_v1 {
4242                    writer.write_all(&transcoded_text)?;
4243                    let len_u64 = u64::try_from(transcoded_text.len())?;
4244                    bytes_written = bytes_written.saturating_add(len_u64);
4245                    transcoded_text.clear();
4246                } else if let Some(valid_slice) = buffer.get(..pos) {
4247                    writer.write_all(valid_slice)?;
4248                    let len_u64 = u64::try_from(pos)?;
4249                    bytes_written = bytes_written.saturating_add(len_u64);
4250                }
4251                stream_offset = stream_offset.saturating_add(pos);
4252                buffer.drain(..pos);
4253            } else if eof_reached && !buffer.is_empty() {
4254                if !options.best_effort {
4255                    return Err(DcMixedError::InvalidUtf8e128 {
4256                        offset: stream_offset,
4257                        source: DcUtfError {
4258                            valid_up_to: 0,
4259                            error_len: if is_v1 {
4260                                determine_utf_8e_128_error_len(&buffer)
4261                            } else {
4262                                determine_dctf_error_len(&buffer)
4263                            },
4264                        },
4265                    }
4266                    .into());
4267                }
4268                log.warn(&format!(
4269                    "Incomplete DcTF sequence at end of stream (offset {stream_offset})"
4270                ));
4271                writer.write_all("\u{FFFD}".as_bytes())?;
4272                let rep_len = u64::try_from("\u{FFFD}".len())?;
4273                bytes_written = bytes_written.saturating_add(rep_len);
4274                stream_offset = stream_offset.saturating_add(buffer.len());
4275                buffer.clear();
4276            }
4277        }
4278    }
4279
4280    if is_v1 {
4281        if let Err(err) = tracker.finish() {
4282            if !options.best_effort {
4283                return Err(err);
4284            }
4285            log.warn(&format!("{err:#}"));
4286        }
4287    }
4288
4289    Ok((bytes_written, log))
4290}
4291
4292#[cfg(test)]
4293#[allow(
4294    clippy::panic,
4295    clippy::expect_used,
4296    clippy::unwrap_used,
4297    clippy::unwrap_in_result,
4298    clippy::panic_in_result_fn,
4299    clippy::indexing_slicing,
4300    clippy::arithmetic_side_effects,
4301    reason = "Standard repository test boilerplate"
4302)]
4303mod tests {
4304    use super::*;
4305    use ctb_formats_dcdata::dc_char::DcCharExt;
4306
4307    #[crate::ctb_test]
4308    fn test_dc_203_bytes_constant() {
4309        let encoded = DC_START_ENCAPSULATION_BINARY.encode();
4310        assert_eq!(encoded, DC_203_BYTES.to_vec());
4311    }
4312
4313    #[crate::ctb_test]
4314    fn test_empty_dcmst() {
4315        let mst = DcMstring::new();
4316        assert_eq!(mst.len(), 21);
4317        assert!(mst.is_empty());
4318        assert_eq!(mst.header(), &mst.as_bytes()[..21]);
4319        assert_eq!(mst.payload_len(), 0);
4320        assert_eq!(mst.payload_bytes(), b"");
4321        assert_eq!(mst.chunks().count(), 0);
4322
4323        // Validation of empty DcMstring succeeds
4324        validate_dcmst(mst.as_bytes()).unwrap();
4325    }
4326
4327    #[crate::ctb_test]
4328    fn test_header_validation_failures() {
4329        // Too short
4330        let err = validate_dcmst(b"short").unwrap_err();
4331        assert_eq!(err, DcMixedError::TooShort { len: 5 });
4332
4333        // Bad magic
4334        let mut bad_magic = [0u8; 21];
4335        bad_magic[..5].copy_from_slice(b"BADMM");
4336        bad_magic[5..].copy_from_slice(&DCMM_UUID);
4337        let err = validate_dcmst(&bad_magic).unwrap_err();
4338        assert_eq!(err, DcMixedError::InvalidMagic { found: *b"BADMM" });
4339
4340        // Bad UUID
4341        let mut bad_uuid = [0u8; 21];
4342        bad_uuid[..5].copy_from_slice(&DCMM_MAGIC);
4343        let err = validate_dcmst(&bad_uuid).unwrap_err();
4344        assert!(matches!(err, DcMixedError::InvalidUuid { .. }));
4345    }
4346
4347    #[crate::ctb_test]
4348    fn test_legacy_codec_conversion_fixture() -> Result<()> {
4349        let mut legacy = vec![
4350            0x44, 0x63, 0x4d, 0x4d, 0x00, 0xd5, 0xab, 0x81, 0x9e, 0x9b, 0x8e,
4351            0x4d, 0x61, 0xad, 0xbc, 0x93, 0x3e, 0x88, 0x51, 0xe7, 0x9a, 0x41,
4352            0xff, 0x87, 0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xff, 0x84,
4353            0x84, 0x90, 0x83, 0x8b, 0x00,
4354        ];
4355        legacy.extend_from_slice(&3u128.to_be_bytes());
4356        legacy.extend_from_slice(&[0xff, 0x80, 0x41, 0x42]);
4357
4358        let mut expected = vec![
4359            0x44, 0x63, 0x4d, 0x4d, 0x00, 0xb0, 0x32, 0x7a, 0x84, 0xb7, 0x45,
4360            0x49, 0x2c, 0xb3, 0x9d, 0x77, 0xc2, 0x82, 0x7e, 0x3a, 0x6f, 0x41,
4361            0xff, 0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xf4, 0x90, 0x83,
4362            0x8b, 0x02,
4363        ];
4364        expected.extend_from_slice(&3u128.to_be_bytes());
4365        expected.extend_from_slice(&0u128.to_be_bytes());
4366        expected.extend_from_slice(&[0xff, 0x80, 0x41, 0x42]);
4367
4368        let (converted, _) = dcmm1_to_dcmstring(&legacy)?;
4369        assert_eq!(converted.as_bytes(), expected);
4370
4371        let mut malformed = legacy[..21].to_vec();
4372        malformed.extend_from_slice(&[0xe1, 0x80, 0x41]);
4373        let error = dcmm1_to_dcmstring(&malformed).unwrap_err();
4374        assert!(matches!(
4375            error.downcast_ref::<DcMixedError>(),
4376            Some(DcMixedError::InvalidUtf8e128 { offset: 21, .. })
4377        ));
4378
4379        let options = DcmmStreamOptions { best_effort: true };
4380        let (recovered, log) =
4381            dcmm1_to_dcmstring_with_options(&malformed, &options)?;
4382        assert_eq!(recovered.payload_bytes(), &[0xef, 0xbf, 0xbd, 0x41]);
4383        assert!(log.has_warnings());
4384
4385        malformed.pop();
4386        let (recovered, log) =
4387            dcmm1_to_dcmstring_with_options(&malformed, &options)?;
4388        assert_eq!(recovered.payload_bytes(), &[0xef, 0xbf, 0xbd]);
4389        assert!(log.has_warnings());
4390        Ok(())
4391    }
4392
4393    #[crate::ctb_test]
4394    fn test_push_and_chunks_mixed() {
4395        let mut mst = DcMstring::new();
4396        mst.push_str("ArchiveHeader\n");
4397        let payload1 = b"Hello, direct binary payload!";
4398        mst.push_binary(payload1);
4399        mst.push_str("\nSeparator\n");
4400        let payload2 = b"Checksummed binary content!";
4401        mst.push_binary_with_sha256(payload2).unwrap();
4402
4403        validate_dcmst(mst.as_bytes()).unwrap();
4404
4405        let chunks: Vec<DcMixed<'_>> = mst.chunks().collect();
4406        assert_eq!(chunks.len(), 4);
4407
4408        assert_eq!(chunks[0].as_text().unwrap(), "ArchiveHeader\n");
4409        assert_eq!(chunks[1].as_binary(), Some(payload1.as_slice()));
4410        assert_eq!(chunks[1].sha256(), None);
4411        assert!(chunks[1].verify_checksum());
4412
4413        assert_eq!(chunks[2].as_text().unwrap(), "\nSeparator\n");
4414        assert_eq!(chunks[3].as_binary(), Some(payload2.as_slice()));
4415        let DcMixed::BinaryWithMetadata { metadata, .. } = &chunks[3] else {
4416            panic!("Expected metadata-bearing binary chunk");
4417        };
4418        assert!(
4419            crate::encapsulation::parse_metadata(metadata)
4420                .unwrap()
4421                .checksum
4422                .is_some()
4423        );
4424        assert!(chunks[3].verify_checksum());
4425    }
4426
4427    #[crate::ctb_test]
4428    fn test_checksum_mismatch_detection() {
4429        let mut mst = DcMstring::new();
4430        let payload = b"Sensitive data";
4431        mst.push_binary_with_sha256(payload).unwrap();
4432
4433        let mut corrupted = mst.into_bytes();
4434        // Mutate a byte in the payload
4435        let last_idx = corrupted.len() - 1;
4436        corrupted[last_idx] ^= 0xFF;
4437
4438        let err = validate_dcmst(&corrupted).unwrap_err();
4439        assert!(matches!(err, DcMixedError::InvalidMetadata { .. }));
4440    }
4441
4442    #[crate::ctb_test]
4443    fn test_rejects_retired_dcutf_types() -> Result<()> {
4444        for type_byte in [1, 4] {
4445            let payload = b"legacy";
4446            let mut bytes = DcMstring::new().into_bytes();
4447            bytes.extend_from_slice(&DC_203_BYTES);
4448            bytes.push(type_byte);
4449            let type_offset = bytes.len().saturating_sub(1);
4450            let truncated = bytes.clone();
4451            bytes.extend_from_slice(
4452                &u128::try_from(payload.len())?.to_be_bytes(),
4453            );
4454            if type_byte == 4 {
4455                bytes.extend_from_slice(&ctb_formats_checksum::sha256(payload));
4456            }
4457            bytes.extend_from_slice(payload);
4458            let expected = DcMixedError::UnsupportedLegacyType {
4459                offset: type_offset,
4460                type_byte,
4461            };
4462            assert_eq!(validate_dcmst(&truncated), Err(expected.clone()));
4463            assert_eq!(validate_dcmst(&bytes), Err(expected.clone()));
4464            assert_eq!(DcMstr::from_bytes(&bytes), Err(expected.clone()));
4465            assert_eq!(DcMstring::from_slice(&bytes), Err(expected.clone()));
4466            assert_eq!(DcMstring::from_bytes(bytes), Err(expected.clone()));
4467            assert!(expected.to_string().contains("use type 2"));
4468        }
4469        Ok(())
4470    }
4471
4472    #[crate::ctb_test]
4473    fn test_textual_encapsulation_is_invalid_mixed_mode() -> Result<()> {
4474        let mut text = DcString::new();
4475        for dc in [203, 127, 204] {
4476            text.push(DcChar::from_short(dc));
4477        }
4478        let mut bytes = DcMstring::new().into_bytes();
4479        bytes.extend_from_slice(text.as_bytes());
4480        assert!(validate_dcmst(&bytes).is_err());
4481        Ok(())
4482    }
4483
4484    #[crate::ctb_test]
4485    fn test_conversion_rejects_unrepresentable_dc_sequences() -> Result<()> {
4486        let mut text = DcString::new();
4487        for dc in [314, 999, 203, 127] {
4488            text.push(DcChar::from_short(dc));
4489        }
4490        DcMstring::from_dc_string(&text).unwrap_err();
4491        Ok(())
4492    }
4493
4494    #[crate::ctb_test]
4495    fn test_conversion_preserves_checksum_metadata() -> Result<()> {
4496        let mut mixed = DcMstring::new();
4497        mixed.push_binary_with_sha256(b"payload").unwrap();
4498        validate_dcmst(mixed.as_bytes())?;
4499        let text = mixed.to_dc_string()?;
4500        let restored = DcMstring::from_dc_string(&text)?;
4501        validate_dcmst(restored.as_bytes())?;
4502        assert_eq!(restored.as_bytes(), mixed.as_bytes());
4503        assert!(restored.chunks().all(|chunk| chunk.verify_checksum()));
4504        assert_eq!(restored.to_dc_string()?.as_bytes(), text.as_bytes());
4505        let (bytes, _) = crate::converters::utf8::dcmstring_to_dcutf(&mixed)?;
4506        let (imported, _) =
4507            crate::converters::utf8::dcutf_to_dcmstring(&bytes)?;
4508        assert_eq!(imported.as_bytes(), mixed.as_bytes());
4509        let (bytes, _) =
4510            crate::converters::dctext::dcmstring_to_dctext(&mixed)?;
4511        let (imported, _) =
4512            crate::converters::dctext::dctext_to_dcmstring(&bytes)?;
4513        assert_eq!(imported.as_bytes(), mixed.as_bytes());
4514        let (bytes, _) = crate::converters::dcts::dcmstring_to_dcts(&mixed)?;
4515        let (imported, _) = crate::converters::dcts::dcts_to_dcmstring(&bytes)?;
4516        assert_eq!(imported.as_bytes(), mixed.as_bytes());
4517        let (bytes, _) = crate::converters::dcal::dcmstring_to_dcal(&mixed)?;
4518        let (imported, _) = crate::converters::dcal::dcal_to_dcmstring(&bytes)?;
4519        assert_eq!(imported.as_bytes(), mixed.as_bytes());
4520        let (bytes, _) = crate::converters::eite::dcmstring_to_dcil(&mixed)?;
4521        let (imported, _) = crate::converters::eite::dcil_to_dcmstring(&bytes)?;
4522        assert_eq!(imported.as_bytes(), mixed.as_bytes());
4523        let mut binary = DcMstring::new();
4524        binary.push_binary(b"payload");
4525        let (exported, _) =
4526            crate::converters::utf8::dcmstring_to_dcutf(&binary)?;
4527        let (imported, _) =
4528            crate::converters::utf8::dcutf_to_dcmstring(&exported)?;
4529        assert_eq!(imported.as_bytes(), binary.as_bytes());
4530        Ok(())
4531    }
4532
4533    #[crate::ctb_test]
4534    fn test_round_trip_conversion_with_dc_string() {
4535        let mut original_mst = DcMstring::new();
4536        original_mst.push_str("File: test.bin\nSize: 12\n");
4537        let bin_data = b"Binary 12345";
4538        original_mst.push_binary(bin_data);
4539        original_mst.push_str("\nFooter");
4540
4541        // Convert DcMstring -> DcString (encodes binary as base64 between Dc 203 and Dc 204)
4542        let dc_string = original_mst.to_dc_string().unwrap();
4543
4544        // Convert DcString -> DcMstring (decodes base64 back to direct binary)
4545        let round_tripped = DcMstring::from_dc_string(&dc_string).unwrap();
4546
4547        let chunks: Vec<DcMixed<'_>> = round_tripped.chunks().collect();
4548        assert_eq!(chunks.len(), 3);
4549        assert_eq!(chunks[0].as_text().unwrap(), "File: test.bin\nSize: 12\n");
4550        assert_eq!(chunks[1].as_binary(), Some(bin_data.as_slice()));
4551        assert_eq!(chunks[2].as_text().unwrap(), "\nFooter");
4552    }
4553
4554    #[crate::ctb_test]
4555    fn test_large_archive_payload_efficiency() {
4556        let mut mst = DcMstring::new();
4557        mst.push_str("FILE archive.tar\n");
4558        // 1 MB binary payload
4559        let large_payload = vec![0x42u8; 1024 * 1024];
4560        mst.push_binary_with_sha256(&large_payload).unwrap();
4561
4562        let DcMixed::BinaryWithMetadata { metadata, .. } =
4563            mst.chunks().nth(1).unwrap()
4564        else {
4565            panic!("Expected metadata-bearing binary chunk");
4566        };
4567        assert_eq!(
4568            mst.len(),
4569            21 + "FILE archive.tar\n".len()
4570                + DC_203_BYTES.len()
4571                + 1
4572                + 16
4573                + 16
4574                + metadata.len()
4575                + (1024 * 1024)
4576        );
4577
4578        let slice = DcMstr::from_bytes(mst.as_bytes()).unwrap();
4579        let chunks: Vec<DcMixed<'_>> = slice.chunks().collect();
4580        assert_eq!(chunks.len(), 2);
4581        assert_eq!(chunks[1].as_binary().unwrap().len(), 1024 * 1024);
4582        assert!(chunks[1].verify_checksum());
4583    }
4584
4585    #[crate::ctb_test]
4586    fn test_mutation_clear_and_truncate() {
4587        let mut mst = DcMstring::new();
4588        mst.push_str("Sample text");
4589        let mark = mst.len();
4590        mst.push_binary(b"payload");
4591
4592        mst.truncate(mark);
4593        assert_eq!(mst.payload_bytes(), b"Sample text");
4594
4595        mst.clear();
4596        assert!(mst.is_empty());
4597        assert_eq!(mst.len(), 21);
4598    }
4599
4600    struct OneByteReader<'a> {
4601        slice: &'a [u8],
4602    }
4603
4604    impl std::io::Read for OneByteReader<'_> {
4605        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
4606            if self.slice.is_empty() || buf.is_empty() {
4607                return Ok(0);
4608            }
4609            if let Some(first) = self.slice.first().copied() {
4610                if let Some(target) = buf.first_mut() {
4611                    *target = first;
4612                }
4613                self.slice = self.slice.get(1..).unwrap_or(&[]);
4614                Ok(1)
4615            } else {
4616                Ok(0)
4617            }
4618        }
4619    }
4620
4621    #[crate::ctb_test]
4622    fn test_validate_and_copy_dcmm_stream_strict_success() -> Result<()> {
4623        // 1. Empty document
4624        let empty = DcMstring::new();
4625        let mut out = Vec::new();
4626        let written =
4627            validate_and_copy_dcmm_stream(&mut empty.as_bytes(), &mut out)?;
4628        assert_eq!(written, 21);
4629        assert_eq!(out, empty.as_bytes());
4630
4631        // 2. Text only document
4632        let mut text_doc = DcMstring::new();
4633        text_doc.push_str("Hello, world! Unicode: 🚀 — DcText streaming test.");
4634        let mut out = Vec::new();
4635        let written =
4636            validate_and_copy_dcmm_stream(&mut text_doc.as_bytes(), &mut out)?;
4637        assert_eq!(written, u64::try_from(text_doc.len())?);
4638        assert_eq!(out, text_doc.as_bytes());
4639
4640        // 3. Document with binary payloads: unchecksummed, metadata sha256, type 3 sha256
4641        let mut mixed = DcMstring::new();
4642        mixed.push_str("Text preamble\n");
4643        mixed.push_binary(b"Binary payload 1");
4644        mixed.push_str("\nMiddle text\n");
4645        mixed.push_binary_with_sha256(b"Sha256 payload 2")?;
4646        mixed.push_str("\nTrailing text\n");
4647
4648        // Add a TYPE_BINARY_SHA256 chunk manually to verify type 3 streaming
4649        let raw_type3_payload = b"Direct SHA256 binary 3";
4650        let sha_digest = ctb_formats_checksum::sha256(raw_type3_payload);
4651        let mut mixed_bytes = mixed.into_bytes();
4652        mixed_bytes.extend_from_slice(&DC_203_BYTES);
4653        mixed_bytes.push(TYPE_BINARY_SHA256);
4654        mixed_bytes.extend_from_slice(
4655            &u128::try_from(raw_type3_payload.len())?.to_be_bytes(),
4656        );
4657        mixed_bytes.extend_from_slice(&sha_digest);
4658        mixed_bytes.extend_from_slice(raw_type3_payload);
4659
4660        let mut out = Vec::new();
4661        let written = validate_and_copy_dcmm_stream(
4662            &mut mixed_bytes.as_slice(),
4663            &mut out,
4664        )?;
4665        assert_eq!(written, u64::try_from(mixed_bytes.len())?);
4666        assert_eq!(out, mixed_bytes);
4667        Ok(())
4668    }
4669
4670    #[crate::ctb_test]
4671    fn test_validate_and_copy_dcmm_stream_strict_failures() -> Result<()> {
4672        let mut out = Vec::new();
4673
4674        // Header too short
4675        let err =
4676            validate_and_copy_dcmm_stream(&mut b"short".as_slice(), &mut out)
4677                .unwrap_err();
4678        let dc_err = err.downcast_ref::<DcMixedError>().expect("DcMixedError");
4679        assert_eq!(*dc_err, DcMixedError::TooShort { len: 5 });
4680
4681        // Invalid magic
4682        let mut bad_magic = [0u8; 21];
4683        bad_magic[..5].copy_from_slice(b"BADMM");
4684        bad_magic[5..].copy_from_slice(&DCMM_UUID);
4685        let err =
4686            validate_and_copy_dcmm_stream(&mut bad_magic.as_slice(), &mut out)
4687                .unwrap_err();
4688        let dc_err = err.downcast_ref::<DcMixedError>().expect("DcMixedError");
4689        assert_eq!(*dc_err, DcMixedError::InvalidMagic { found: *b"BADMM" });
4690
4691        // Invalid UUID
4692        let mut bad_uuid = [0u8; 21];
4693        bad_uuid[..5].copy_from_slice(&DCMM_MAGIC);
4694        let err =
4695            validate_and_copy_dcmm_stream(&mut bad_uuid.as_slice(), &mut out)
4696                .unwrap_err();
4697        let dc_err = err.downcast_ref::<DcMixedError>().expect("DcMixedError");
4698        assert!(matches!(*dc_err, DcMixedError::InvalidUuid { .. }));
4699
4700        // Invalid UTF-8e-128 sequence in text
4701        let mut bad_text = DcMstring::new().into_bytes();
4702        bad_text.extend_from_slice(b"Valid text\x80Invalid byte");
4703        let err =
4704            validate_and_copy_dcmm_stream(&mut bad_text.as_slice(), &mut out)
4705                .unwrap_err();
4706        let dc_err = err.downcast_ref::<DcMixedError>().expect("DcMixedError");
4707        assert!(matches!(
4708            *dc_err,
4709            DcMixedError::InvalidUtf8e128 { offset: 31, .. }
4710        ));
4711
4712        // Incomplete UTF-8e-128 sequence at EOF
4713        let mut incomplete_text = DcMstring::new().into_bytes();
4714        incomplete_text.extend_from_slice(b"Valid text\xC2"); // C2 needs continuation byte
4715        let err = validate_and_copy_dcmm_stream(
4716            &mut incomplete_text.as_slice(),
4717            &mut out,
4718        )
4719        .unwrap_err();
4720        let dc_err = err.downcast_ref::<DcMixedError>().expect("DcMixedError");
4721        assert!(matches!(
4722            *dc_err,
4723            DcMixedError::InvalidUtf8e128 { offset: 31, .. }
4724        ));
4725
4726        // Unsupported legacy encapsulation type 1
4727        let mut legacy_1 = DcMstring::new().into_bytes();
4728        legacy_1.extend_from_slice(&DC_203_BYTES);
4729        legacy_1.push(1);
4730        legacy_1.extend_from_slice(&10u128.to_be_bytes());
4731        legacy_1.extend_from_slice(b"0123456789");
4732        let err =
4733            validate_and_copy_dcmm_stream(&mut legacy_1.as_slice(), &mut out)
4734                .unwrap_err();
4735        let dc_err = err.downcast_ref::<DcMixedError>().expect("DcMixedError");
4736        assert_eq!(
4737            *dc_err,
4738            DcMixedError::UnsupportedLegacyType {
4739                offset: 25,
4740                type_byte: 1
4741            }
4742        );
4743
4744        // Unsupported legacy encapsulation type 4
4745        let mut legacy_4 = DcMstring::new().into_bytes();
4746        legacy_4.extend_from_slice(&DC_203_BYTES);
4747        legacy_4.push(4);
4748        legacy_4.extend_from_slice(&10u128.to_be_bytes());
4749        legacy_4.extend_from_slice(&[0u8; 32]);
4750        legacy_4.extend_from_slice(b"0123456789");
4751        let err =
4752            validate_and_copy_dcmm_stream(&mut legacy_4.as_slice(), &mut out)
4753                .unwrap_err();
4754        let dc_err = err.downcast_ref::<DcMixedError>().expect("DcMixedError");
4755        assert_eq!(
4756            *dc_err,
4757            DcMixedError::UnsupportedLegacyType {
4758                offset: 25,
4759                type_byte: 4
4760            }
4761        );
4762
4763        // Unknown encapsulation type byte
4764        let mut unknown_type = DcMstring::new().into_bytes();
4765        unknown_type.extend_from_slice(&DC_203_BYTES);
4766        unknown_type.push(99);
4767        unknown_type.extend_from_slice(&5u128.to_be_bytes());
4768        unknown_type.extend_from_slice(b"12345");
4769        let err = validate_and_copy_dcmm_stream(
4770            &mut unknown_type.as_slice(),
4771            &mut out,
4772        )
4773        .unwrap_err();
4774        let dc_err = err.downcast_ref::<DcMixedError>().expect("DcMixedError");
4775        assert_eq!(
4776            *dc_err,
4777            DcMixedError::InvalidEncapsulationType {
4778                offset: 25,
4779                type_byte: 99
4780            }
4781        );
4782
4783        // Truncated encapsulation payload
4784        let mut truncated_payload = DcMstring::new().into_bytes();
4785        truncated_payload.extend_from_slice(&DC_203_BYTES);
4786        truncated_payload.push(TYPE_BINARY);
4787        truncated_payload.extend_from_slice(&100u128.to_be_bytes());
4788        truncated_payload.extend_from_slice(b"only 10 bytes");
4789        let err = validate_and_copy_dcmm_stream(
4790            &mut truncated_payload.as_slice(),
4791            &mut out,
4792        )
4793        .unwrap_err();
4794        let dc_err = err.downcast_ref::<DcMixedError>().expect("DcMixedError");
4795        assert!(matches!(
4796            *dc_err,
4797            DcMixedError::TruncatedEncapsulation {
4798                offset: 21,
4799                expected: 121,
4800                ..
4801            }
4802        ));
4803
4804        // Checksum mismatch in type 3 (TYPE_BINARY_SHA256)
4805        let payload = b"Hello binary";
4806        let mut bad_sha3 = DcMstring::new().into_bytes();
4807        bad_sha3.extend_from_slice(&DC_203_BYTES);
4808        bad_sha3.push(TYPE_BINARY_SHA256);
4809        bad_sha3
4810            .extend_from_slice(&u128::try_from(payload.len())?.to_be_bytes());
4811        bad_sha3.extend_from_slice(&[0xEEu8; 32]); // wrong sha
4812        bad_sha3.extend_from_slice(payload);
4813        let err =
4814            validate_and_copy_dcmm_stream(&mut bad_sha3.as_slice(), &mut out)
4815                .unwrap_err();
4816        let dc_err = err.downcast_ref::<DcMixedError>().expect("DcMixedError");
4817        assert!(matches!(
4818            *dc_err,
4819            DcMixedError::ChecksumMismatch { offset: 21, .. }
4820        ));
4821
4822        // Checksum mismatch in type 2 (TYPE_BINARY_METADATA)
4823        let mut doc = DcMstring::new();
4824        doc.push_binary_with_sha256(b"original payload")?;
4825        let mut corrupted_meta = doc.into_bytes();
4826        let last_idx = corrupted_meta.len().saturating_sub(1);
4827        if let Some(b) = corrupted_meta.get_mut(last_idx) {
4828            *b ^= 0xFF;
4829        }
4830        let err = validate_and_copy_dcmm_stream(
4831            &mut corrupted_meta.as_slice(),
4832            &mut out,
4833        )
4834        .unwrap_err();
4835        let dc_err = err.downcast_ref::<DcMixedError>().expect("DcMixedError");
4836        assert!(matches!(
4837            *dc_err,
4838            DcMixedError::InvalidMetadata { offset: 21, .. }
4839        ));
4840
4841        Ok(())
4842    }
4843
4844    #[crate::ctb_test]
4845    fn test_validate_and_copy_dcmm_stream_best_effort() -> Result<()> {
4846        let best_effort_opts = DcmmStreamOptions { best_effort: true };
4847
4848        // 1. Corrupted header is synthesized
4849        let bad_header_data = b"NOT_A_VALID_HEADER___rest of stream".to_vec();
4850        let mut out = Vec::new();
4851        let (written, log) = validate_and_copy_dcmm_stream_with_options(
4852            &mut bad_header_data.as_slice(),
4853            &mut out,
4854            &best_effort_opts,
4855        )?;
4856        assert!(log.has_warnings());
4857        assert!(out.starts_with(&DCMM_MAGIC));
4858        assert!(written >= 21);
4859
4860        // 2. Corrupted UTF-8e-128 sequence replaces invalid bytes with \u{FFFD}
4861        let mut bad_text = DcMstring::new().into_bytes();
4862        bad_text.extend_from_slice(b"Pre\x80Post");
4863        let mut out = Vec::new();
4864        let (written, log) = validate_and_copy_dcmm_stream_with_options(
4865            &mut bad_text.as_slice(),
4866            &mut out,
4867            &best_effort_opts,
4868        )?;
4869        assert!(log.has_warnings());
4870        assert_eq!(written, u64::try_from(out.len())?);
4871        let out_str = String::from_utf8_lossy(&out[21..]);
4872        assert!(out_str.contains("Pre\u{FFFD}Post"));
4873
4874        // 3. Checksum mismatch in best-effort mode streams payload and logs warning
4875        let payload = b"Corrupted checksum payload";
4876        let mut bad_sha = DcMstring::new().into_bytes();
4877        bad_sha.extend_from_slice(&DC_203_BYTES);
4878        bad_sha.push(TYPE_BINARY_SHA256);
4879        bad_sha
4880            .extend_from_slice(&u128::try_from(payload.len())?.to_be_bytes());
4881        bad_sha.extend_from_slice(&[0x11u8; 32]); // wrong checksum
4882        bad_sha.extend_from_slice(payload);
4883        let mut out = Vec::new();
4884        let (written, log) = validate_and_copy_dcmm_stream_with_options(
4885            &mut bad_sha.as_slice(),
4886            &mut out,
4887            &best_effort_opts,
4888        )?;
4889        assert!(log.has_warnings());
4890        assert_eq!(written, u64::try_from(bad_sha.len())?);
4891        assert_eq!(out, bad_sha);
4892
4893        // 4. Truncated payload in best-effort mode copies available bytes and logs warning
4894        let mut truncated = DcMstring::new().into_bytes();
4895        truncated.extend_from_slice(&DC_203_BYTES);
4896        truncated.push(TYPE_BINARY);
4897        truncated.extend_from_slice(&1000u128.to_be_bytes()); // claims 1000 bytes
4898        truncated.extend_from_slice(b"actual payload only 23 bytes");
4899        let mut out = Vec::new();
4900        let (written, log) = validate_and_copy_dcmm_stream_with_options(
4901            &mut truncated.as_slice(),
4902            &mut out,
4903            &best_effort_opts,
4904        )?;
4905        assert!(log.has_warnings());
4906        assert_eq!(written, u64::try_from(truncated.len())?);
4907        assert_eq!(out, truncated);
4908
4909        Ok(())
4910    }
4911
4912    #[crate::ctb_test]
4913    fn test_validate_and_copy_dcmm_stream_fragmented_reads() -> Result<()> {
4914        let mut mixed = DcMstring::new();
4915        mixed.push_str("Fragmented text chunk 1\n");
4916        mixed.push_binary(b"Fragmented binary payload 1");
4917        mixed.push_str("\nFragmented text chunk 2 with Unicode 🦀 emoji\n");
4918        mixed.push_binary_with_sha256(
4919            b"Fragmented checksummed binary payload 2",
4920        )?;
4921        mixed.push_str("\nFinal footer\n");
4922
4923        let input_bytes = mixed.into_bytes();
4924        let mut reader = OneByteReader {
4925            slice: &input_bytes,
4926        };
4927        let mut out = Vec::new();
4928
4929        let written = validate_and_copy_dcmm_stream(&mut reader, &mut out)?;
4930        assert_eq!(written, u64::try_from(input_bytes.len())?);
4931        assert_eq!(out, input_bytes);
4932        Ok(())
4933    }
4934
4935    #[crate::ctb_test]
4936    fn test_dcmm1_and_dcmstring_checksummed_section_conversion() -> Result<()> {
4937        use ctb_formats_dcdata::dc::{
4938            DC_BEGIN_CHECKSUMMED_SECTION, DC_BEGIN_KV_MAP, DC_BEGIN_KV_PAIR,
4939            DC_BOOLEAN_FALSE, DC_BOOLEAN_TRUE, DC_END_CHECKSUMMED_SECTION,
4940            DC_END_KV_MAP, DC_END_KV_PAIR, DC_LIST_ELEMENT_SEPARATOR,
4941            DC_SECTION_DIGEST,
4942        };
4943        const DC_TYPE_WILDCARD: DcChar = DcChar::from_short(275);
4944
4945        let mut doc = DcMstring::new();
4946        doc.push_char(DC_BEGIN_CHECKSUMMED_SECTION);
4947        let body_start = doc.len();
4948        doc.push_char(DC_BEGIN_KV_MAP);
4949        doc.push_char(DC_TYPE_WILDCARD);
4950        doc.push_char(DC_TYPE_WILDCARD);
4951        doc.push_char(DC_BEGIN_KV_PAIR);
4952        doc.push_char(DC_BOOLEAN_TRUE);
4953        doc.push_char(DC_LIST_ELEMENT_SEPARATOR);
4954        doc.push_char(DC_BOOLEAN_FALSE);
4955        doc.push_char(DC_END_KV_PAIR);
4956        doc.push_char(DC_END_KV_MAP);
4957        let body_end = doc.len();
4958        doc.push_char(DC_END_CHECKSUMMED_SECTION);
4959        let digest =
4960            ctb_formats_checksum::sha256(&doc.as_bytes()[body_start..body_end]);
4961        doc.push_char(DC_SECTION_DIGEST);
4962        doc.push_checksum(ctb_utilities::format_id::DC_SHA256, &digest)?;
4963
4964        crate::navigator::validate_dc_mixed_strict(&doc)?;
4965
4966        let (dcmm1_bytes, _) = dcmstring_to_dcmm1(&doc)?;
4967        // DcMixed1 uses 6-byte DcUtf sequences for short Dcs instead of 4-byte DcTF sequences,
4968        // so the serialized section body is longer in DcMixed1 than in DcMixed2.
4969        assert!(dcmm1_bytes.len() > doc.len());
4970
4971        let (restored, _) = dcmm1_to_dcmstring(&dcmm1_bytes)?;
4972        crate::navigator::validate_dc_mixed_strict(&restored)?;
4973        assert_eq!(restored.as_bytes(), doc.as_bytes());
4974
4975        // Also verify bounded-memory streaming of DcMixed1 (with 1-byte fragmented reads)
4976        // produces the exact same DcMixed2 output and recomputed section checksum.
4977        let mut one_byte_reader = OneByteReader {
4978            slice: &dcmm1_bytes,
4979        };
4980        let mut streamed_out = Vec::new();
4981        let written = validate_and_copy_dcmm_stream(
4982            &mut one_byte_reader,
4983            &mut streamed_out,
4984        )?;
4985        assert_eq!(written, u64::try_from(doc.len())?);
4986        assert_eq!(streamed_out.as_slice(), doc.as_bytes());
4987
4988        // Tamper with the last byte of the digest in DcMixed1 and verify
4989        // dcmm1_to_dcmstring rejects the corrupted section checksum.
4990        let mut corrupted_dcmm1 = dcmm1_bytes.clone();
4991        let last_dcmm1 = corrupted_dcmm1.len() - 1;
4992        corrupted_dcmm1[last_dcmm1] ^= 0xFF;
4993        let err = dcmm1_to_dcmstring(&corrupted_dcmm1).unwrap_err();
4994        assert!(
4995            format!("{err:#}").contains("Section checksum mismatch"),
4996            "unexpected error: {err:#}"
4997        );
4998
4999        // Tamper with the last byte of the digest in DcMstring and verify
5000        // dcmstring_to_dcmm1 rejects the corrupted section checksum.
5001        let mut corrupted_doc_bytes = doc.as_bytes().to_vec();
5002        let last_v2 = corrupted_doc_bytes.len() - 1;
5003        corrupted_doc_bytes[last_v2] ^= 0xFF;
5004        let corrupted_doc = DcMstring::from_bytes(corrupted_doc_bytes)?;
5005        let err_v2 = dcmstring_to_dcmm1(&corrupted_doc).unwrap_err();
5006        assert!(
5007            format!("{err_v2:#}").contains("Section checksum mismatch"),
5008            "unexpected error: {err_v2:#}"
5009        );
5010
5011        // Build a section with an unsupported digest algorithm (Md5, format Dc 217) and verify
5012        // dcmstring_to_dcmm1 rejects it explicitly.
5013        let mut unsupported_doc = DcMstring::new();
5014        unsupported_doc.push_char(DC_BEGIN_CHECKSUMMED_SECTION);
5015        unsupported_doc.push_char(DC_BOOLEAN_TRUE);
5016        unsupported_doc.push_char(DC_END_CHECKSUMMED_SECTION);
5017        unsupported_doc.push_char(DC_SECTION_DIGEST);
5018        unsupported_doc.push_checksum(DcChar::from_format(217), &[0u8; 16])?;
5019        dcmstring_to_dcmm1(&unsupported_doc).unwrap_err();
5020
5021        // Quoted checksummed section inside a literal frame (260..261) must also have
5022        // its digest verified and recomputed across DcMixed2 <-> DcMixed1 conversion.
5023        let mut quoted_doc = DcMstring::new();
5024        quoted_doc.push_char(ctb_formats_dcdata::dc::DC_BEGIN_LITERAL);
5025        quoted_doc.push_char(ctb_formats_dcdata::dc::DC_BEGIN_TYPE_DEF);
5026        quoted_doc.push_char(ctb_formats_dcdata::dc::DC_TYPE_STRING);
5027        quoted_doc.push_char(ctb_formats_dcdata::dc::DC_END_TYPE_DEF);
5028        quoted_doc.push_char(DC_BEGIN_CHECKSUMMED_SECTION);
5029        let quoted_body_start = quoted_doc.len();
5030        quoted_doc.push_char(DC_BOOLEAN_TRUE);
5031        let quoted_body_end = quoted_doc.len();
5032        let quoted_digest = ctb_formats_checksum::sha256(
5033            &quoted_doc.as_bytes()[quoted_body_start..quoted_body_end],
5034        );
5035        quoted_doc.push_char(DC_END_CHECKSUMMED_SECTION);
5036        quoted_doc.push_char(DC_SECTION_DIGEST);
5037        quoted_doc.push_checksum(
5038            ctb_utilities::format_id::DC_SHA256,
5039            &quoted_digest,
5040        )?;
5041        quoted_doc.push_char(ctb_formats_dcdata::dc::DC_END_LITERAL);
5042
5043        let (quoted_dcmm1, _) = dcmstring_to_dcmm1(&quoted_doc)?;
5044        assert_ne!(quoted_dcmm1.as_slice(), quoted_doc.as_bytes());
5045        let (quoted_roundtrip, _) = dcmm1_to_dcmstring(&quoted_dcmm1)?;
5046        assert_eq!(quoted_roundtrip.as_bytes(), quoted_doc.as_bytes());
5047
5048        // Unclosed inner container inside a checksummed section must fail conversion
5049        // rather than truncating the container stack and hashing a partial span.
5050        let mut unclosed_inner = DcMstring::new();
5051        unclosed_inner.push_char(DC_BEGIN_CHECKSUMMED_SECTION);
5052        let unclosed_start = unclosed_inner.len();
5053        unclosed_inner.push_char(ctb_formats_dcdata::dc::DC_BEGIN_LIST);
5054        unclosed_inner.push_char(DC_BOOLEAN_TRUE);
5055        let unclosed_end = unclosed_inner.len();
5056        let unclosed_digest = ctb_formats_checksum::sha256(
5057            &unclosed_inner.as_bytes()[unclosed_start..unclosed_end],
5058        );
5059        unclosed_inner.push_char(DC_END_CHECKSUMMED_SECTION);
5060        unclosed_inner.push_char(DC_SECTION_DIGEST);
5061        unclosed_inner.push_checksum(
5062            ctb_utilities::format_id::DC_SHA256,
5063            &unclosed_digest,
5064        )?;
5065        dcmstring_to_dcmm1(&unclosed_inner).unwrap_err();
5066
5067        Ok(())
5068    }
5069
5070    #[crate::ctb_test]
5071    fn test_navigator_dcmm1_file_read_span_as_mstring() -> Result<()> {
5072        use ctb_formats_dcdata::dc::{DC_BEGIN_IDENTIFIER, DC_END_IDENTIFIER};
5073
5074        let mut doc = DcMstring::new();
5075        doc.push_char(DC_BEGIN_IDENTIFIER);
5076        doc.push_str("legacy_span");
5077        doc.push_char(DC_END_IDENTIFIER);
5078
5079        let (dcmm1_bytes, _) = dcmstring_to_dcmm1(&doc)?;
5080        let temp_dir = tempfile::tempdir()?;
5081        let file_path = temp_dir.path().join("legacy.dcmm");
5082        std::fs::write(&file_path, &dcmm1_bytes)?;
5083
5084        let file = std::fs::File::open(&file_path)?;
5085        let mut nav =
5086            crate::navigator::DcDocumentNavigator::from_dcmm_file(file, 0)?;
5087        assert!(nav.is_v1_encoding());
5088        let stub = nav
5089            .next_sibling_stub(&crate::DcProjectionPolicy::strict())?
5090            .expect("Expected identifier stub");
5091        let span_mstr = nav.read_span_as_mstring(stub.outer_span)?;
5092        assert_eq!(span_mstr.payload_bytes(), doc.payload_bytes());
5093        Ok(())
5094    }
5095
5096    #[crate::ctb_test]
5097    fn test_invalid_encapsulation_type_reported_before_size_overflow()
5098    -> Result<()> {
5099        // When an invalid encapsulation type byte (e.g. 99) is followed by 16 bytes
5100        // whose u128 value exceeds usize::MAX, validation must report
5101        // InvalidEncapsulationType rather than a bogus SizeOverflow.
5102        let mut bad_bytes = DcMstring::new().into_bytes();
5103        bad_bytes.extend_from_slice(&DC_203_BYTES);
5104        bad_bytes.push(99);
5105        bad_bytes.extend_from_slice(&u128::MAX.to_be_bytes());
5106        assert_eq!(
5107            validate_dcmst(&bad_bytes),
5108            Err(DcMixedError::InvalidEncapsulationType {
5109                offset: 25,
5110                type_byte: 99,
5111            })
5112        );
5113        Ok(())
5114    }
5115
5116    #[crate::ctb_test]
5117    fn test_non_encapsulating_dc203_character_token_roundtrip() -> Result<()> {
5118        // Dc 203 appearing as an atomic character token (e.g. standalone at EOF or
5119        // followed by non-encapsulation Dcs such as in graph node definitions
5120        // `298 605 203 299` or `584 203 572`) must validate, iterate, and roundtrip
5121        // cleanly without being misread as a binary encapsulation header.
5122        let (standalone_203, _) =
5123            crate::converters::dcal::dcsh_to_dcmstring_with_options(
5124                b"203", false,
5125            )?;
5126        validate_dcmst(standalone_203.as_bytes())?;
5127        let chunks: Vec<_> = standalone_203.chunks().collect();
5128        assert_eq!(chunks.len(), 1);
5129        assert_eq!(
5130            standalone_203.to_dc_string()?.chars().collect::<Vec<_>>(),
5131            vec![DcChar::from_short(203)]
5132        );
5133
5134        let (node_seq, _) =
5135            crate::converters::dcal::dcsh_to_dcmstring_with_options(
5136                b"298 605 203 299",
5137                false,
5138            )?;
5139        validate_dcmst(node_seq.as_bytes())?;
5140        let dc_str = node_seq.to_dc_string()?;
5141        assert_eq!(
5142            dc_str.chars().collect::<Vec<_>>(),
5143            vec![
5144                DcChar::from_short(298),
5145                DcChar::from_short(605),
5146                DcChar::from_short(203),
5147                DcChar::from_short(299),
5148            ]
5149        );
5150        let restored = DcMstring::from_dc_str(&dc_str)?;
5151        assert_eq!(restored.as_bytes(), node_seq.as_bytes());
5152
5153        let (dcmm1, _) = dcmstring_to_dcmm1(&node_seq)?;
5154        let (from_dcmm1, _) = dcmm1_to_dcmstring(&dcmm1)?;
5155        assert_eq!(from_dcmm1.as_bytes(), node_seq.as_bytes());
5156
5157        let mut streamed = Vec::new();
5158        let written = validate_and_copy_dcmm_stream(
5159            &mut node_seq.as_bytes(),
5160            &mut streamed,
5161        )?;
5162        assert_eq!(written, u64::try_from(node_seq.len())?);
5163        assert_eq!(streamed.as_slice(), node_seq.as_bytes());
5164        Ok(())
5165    }
5166
5167    #[crate::ctb_test]
5168    fn test_escaped_dc203_followed_by_encapsulation_type_bytes_roundtrips()
5169    -> Result<()> {
5170        // Explicit `255 203` (`Dc 255 "Ignore following Dc"` + `Dc 203 "Begin encapsulated binary data"`)
5171        // followed immediately by U+0000 (`0x00`), U+0002 (`0x02`), or U+0003 (`0x03`)
5172        // must never be misparsed as a binary encapsulation header (`TYPE_BINARY_NO_METADATA`,
5173        // `TYPE_BINARY_METADATA`, or `TYPE_BINARY_CHECKSUM`).
5174        for input in [
5175            b"641 255 203 u0".as_slice(),
5176            b"641 255 203 u2".as_slice(),
5177            b"641 255 203 u3".as_slice(),
5178        ] {
5179            let (mstr, _) =
5180                crate::converters::dcal::dcsh_to_dcmstring_with_options(
5181                    input, false,
5182                )?;
5183            validate_dcmst(mstr.as_bytes())?;
5184            let chunks: Vec<_> = mstr.chunks().collect();
5185            assert_eq!(chunks.len(), 1);
5186            assert!(matches!(chunks[0], DcMixed::Text(_)));
5187            let dc_str = mstr.to_dc_string()?;
5188            let restored = DcMstring::from_dc_str(&dc_str)?;
5189            assert_eq!(restored.as_bytes(), mstr.as_bytes());
5190
5191            let (dcmm1, _) = dcmstring_to_dcmm1(&mstr)?;
5192            let (from_dcmm1, _) = dcmm1_to_dcmstring(&dcmm1)?;
5193            assert_eq!(from_dcmm1.as_bytes(), mstr.as_bytes());
5194
5195            let (best_effort, diags) =
5196                decode_dcmm_slice_best_effort(mstr.as_bytes(), false)?;
5197            assert!(!diags.has_warnings());
5198            assert_eq!(best_effort.as_bytes(), mstr.as_bytes());
5199
5200            let mut streamed = Vec::new();
5201            let written = validate_and_copy_dcmm_stream(
5202                &mut mstr.as_bytes(),
5203                &mut streamed,
5204            )?;
5205            assert_eq!(written, u64::try_from(mstr.len())?);
5206            assert_eq!(streamed.as_slice(), mstr.as_bytes());
5207        }
5208
5209        // Conversely, `255 255` followed by an actual binary encapsulation block (`203 ...`)
5210        // has the first `255` escaping the second `255`, leaving `203` unescaped so that
5211        // the binary encapsulation block is still recognized and preserved.
5212        let mut doc = DcMstring::new();
5213        doc.push_char(DcChar::from_short(255));
5214        doc.push_char(DcChar::from_short(255));
5215        doc.push_binary(b"abc");
5216        validate_dcmst(doc.as_bytes())?;
5217        let chunks: Vec<_> = doc.chunks().collect();
5218        assert_eq!(chunks.len(), 2);
5219        assert!(matches!(chunks[0], DcMixed::Text(_)));
5220        assert!(matches!(
5221            chunks[1],
5222            DcMixed::BinaryWithMetadata { data: b"abc", .. }
5223        ));
5224        let dc_str = doc.to_dc_string()?;
5225        let restored = DcMstring::from_dc_str(&dc_str)?;
5226        assert_eq!(restored.as_bytes(), doc.as_bytes());
5227
5228        Ok(())
5229    }
5230}