ctb_formats_dcstring/converters/
utf8.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//! Conversions between `DcList` (`&[u128]`) and UTF-8 (`&[u8]`).
21//!
22//! `DcList` is a superset format of UTF-8, where values `0..=0x10FFFF` directly
23//! represent Unicode scalar codepoints, and `SHORT_DC_OFFSET` (`1_114_112`)
24//! offsets short EITE Document Character IDs. Unmappable `DcList` values can
25//! be encapsulated into UTF-8 using `dcl_basenb` (base17) armoring, replaced
26//! with UTF-8 replacement characters (`U+FFFD`), or skipped.
27
28#[allow(
29    unused_imports,
30    clippy::wildcard_imports,
31    reason = "Standard workspace module prelude"
32)]
33use ctb_utilities::*;
34
35use anyhow::{Result, anyhow};
36use const_default::ConstDefault;
37
38use ctb_formats_dcdata::syntax::{DcRole, SyntaxRuleResolver};
39use ctb_formats_eite::dc::dc_encapsulated_raw_to_bytes;
40use ctb_formats_eite::encoding::basenb::{
41    byte_array_from_basenb_17_utf8, byte_array_to_basenb_17_utf8,
42    is_basenb_char,
43};
44use ctb_formats_utf8::{UTF8_REPLACEMENT_CHARACTER, first_char_of_utf8_string};
45use ctb_formats_utilities::{ConversionOutput, FormatLog};
46
47use super::dctext::{DcList, dclist_to_dcutf, dcutf_to_dclist};
48use ctb_formats_dcdata::dc::SHORT_DC_REGION_START;
49
50/// Raw 16-byte array for Start UUID: `1880aba3-21df-42b2-9c96-e32cd647ffc5`
51pub const DCL_BASENB_START_UUID_RAW: [u8; 16] = [
52    0x18, 0x80, 0xab, 0xa3, 0x21, 0xdf, 0x42, 0xb2, 0x9c, 0x96, 0xe3, 0x2c,
53    0xd6, 0x47, 0xff, 0xc5,
54];
55
56/// Raw 16-byte array for End UUID: `27efca19-0439-4bec-b58f-dfff5cd8db9f`
57pub const DCL_BASENB_END_UUID_RAW: [u8; 16] = [
58    0x27, 0xef, 0xca, 0x19, 0x04, 0x39, 0x4b, 0xec, 0xb5, 0x8f, 0xdf, 0xff,
59    0x5c, 0xd8, 0xdb, 0x9f,
60];
61
62/// Returns the base17 UTF-8 bytes for the `DcList` start UUID sentinel.
63pub fn dcl_basenb_start_uuid_bytes() -> Result<Vec<u8>> {
64    byte_array_to_basenb_17_utf8(&DCL_BASENB_START_UUID_RAW)
65}
66
67/// Returns the base17 UTF-8 bytes for the `DcList` end UUID sentinel.
68pub fn dcl_basenb_end_uuid_bytes() -> Result<Vec<u8>> {
69    byte_array_to_basenb_17_utf8(&DCL_BASENB_END_UUID_RAW)
70}
71
72/// Policy for normalizing Document Characters and Unicode during conversion.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, clap::ValueEnum)]
74pub enum DcNormalizationMode {
75    /// Do not normalize characters; replace any characters that cannot be
76    /// represented as-is in the target format with replacement characters.
77    #[default]
78    #[value(name = "none")]
79    None,
80    /// Normalize only the specific characters that cannot be represented
81    /// as-is in the target format (default in permissive mode).
82    #[value(name = "as-needed")]
83    RequiredByTarget,
84    /// Normalize all deprecated Document Characters to their canonical or
85    /// preferred replacements and normalize Unicode text (NFC).
86    #[value(name = "all")]
87    All,
88}
89
90impl ConstDefault for DcNormalizationMode {
91    const DEFAULT: Self = Self::None;
92}
93
94/// Configuration settings for `DcList` to/from UTF-8 conversion.
95#[derive(Debug, Clone)]
96pub struct DcListUtf8Settings {
97    /// Enable `dcl_basenb` (base17) encoding for unmappable Dcs in output/input.
98    pub dcl_basenb_enabled: bool,
99    /// If true, `dcl_basenb` regions are raw runs of base17 characters without
100    /// UUID sentinels.
101    pub dcl_basenb_fragment_enabled: bool,
102    /// If true, fail strictly on fragment decoding errors instead of emitting a warning.
103    pub dcl_basenb_fragment_strict: bool,
104    /// Skip unmappable characters entirely when outputting to UTF-8 (when
105    /// `dcl_basenb_enabled` is false).
106    pub skip_unmappable: bool,
107    /// When true, map short Dcs to their corresponding Unicode output character
108    /// (if available), and parse legacy base64 UTF-8 embeds (`191..192`) in input documents.
109    pub canonicalize_equivalent_dcs: bool,
110    /// Normalization mode for Document Characters and Unicode text.
111    pub normalization: DcNormalizationMode,
112    /// Recover malformed encapsulated text with U+FFFD and warnings instead
113    /// of returning an error.
114    pub permissive: bool,
115    /// Enable debug logging.
116    pub debug: bool,
117}
118
119impl Default for DcListUtf8Settings {
120    fn default() -> Self {
121        Self::DEFAULT
122    }
123}
124
125impl ConstDefault for DcListUtf8Settings {
126    const DEFAULT: Self = Self {
127        dcl_basenb_enabled: false,
128        dcl_basenb_fragment_enabled: false,
129        dcl_basenb_fragment_strict: true,
130        skip_unmappable: false,
131        canonicalize_equivalent_dcs: false,
132        normalization: DcNormalizationMode::None,
133        permissive: false,
134        debug: false,
135    };
136}
137
138/// Normalizes all deprecated Document Characters (to their canonical or preferred
139/// replacements) and normalizes contiguous Unicode runs to NFC in a `DcList`.
140pub fn normalize_dclist_all(
141    dclist: &[u128],
142    permissive: bool,
143    log: &mut FormatLog,
144) -> Result<DcList> {
145    let resolver = ctb_formats_dcdata::syntax::default_syntax_resolver();
146    let mut step1 = Vec::with_capacity(dclist.len());
147    let mut i = 0;
148
149    while i < dclist.len() {
150        let Some(&dc) = dclist.get(i) else { break };
151        // Reason for fallback: if usize index fails u64 conversion, fallback 0 is used for log position.
152        let idx_u64 = u64::try_from(i).unwrap_or(0);
153
154        if resolver.matches_named_type_starter("text_encoding_control", dc) {
155            if permissive {
156                log.export_warning(
157                    idx_u64,
158                    &format!("Stripped text encoding control Dc {dc}"),
159                );
160            }
161            i = i.saturating_add(1);
162            continue;
163        }
164
165        if resolver.token_fills_role(dc, DcRole::StartEncapsulationUtf8) {
166            let (decoded, next) = decode_utf8_encapsulation(
167                dclist,
168                i,
169                permissive,
170                resolver.as_ref(),
171                log,
172            )?;
173            let decoded_dcs = super::document_dc_string(&decoded)?.to_dclist();
174            let norm_decoded =
175                normalize_dclist_all(&decoded_dcs, permissive, log)?;
176            step1.extend(norm_decoded);
177            i = next;
178            continue;
179        }
180
181        if let Some(target) =
182            ctb_formats_dcdata::syntax::CharTarget::from_u128(dc)
183        {
184            if resolver.is_deprecated(&target) {
185                let canon_dc = resolver.canonical_token(dc);
186                if canon_dc != dc {
187                    if permissive {
188                        log.export_warning(
189                            idx_u64,
190                            &format!(
191                                "Normalized deprecated character {target} to canonical token {canon_dc}"
192                            ),
193                        );
194                    }
195                    step1.push(canon_dc);
196                    i = i.saturating_add(1);
197                    continue;
198                }
199                if let Some(pref) = resolver.preferred_replacement(&target) {
200                    let pref_u128 = pref.to_u128();
201                    if pref_u128 != dc {
202                        if permissive {
203                            log.export_warning(
204                                idx_u64,
205                                &format!(
206                                    "Normalized deprecated character {target} to preferred replacement {pref}"
207                                ),
208                            );
209                        }
210                        step1.push(pref_u128);
211                        i = i.saturating_add(1);
212                        continue;
213                    }
214                }
215                if let Some(text) = resolver.unicode_text_mapping(dc, false) {
216                    if permissive {
217                        log.export_warning(
218                            idx_u64,
219                            &format!(
220                                "Normalized deprecated character {target} to \"{text}\""
221                            ),
222                        );
223                    }
224                    for ch in text.chars() {
225                        step1.push(u128::from(u32::from(ch)));
226                    }
227                    i = i.saturating_add(1);
228                    continue;
229                }
230            }
231        }
232
233        step1.push(dc);
234        i = i.saturating_add(1);
235    }
236
237    // Pass 2: Normalize contiguous runs of Unicode scalar codepoints to NFC
238    let mut out = Vec::with_capacity(step1.len());
239    let mut unicode_run = String::new();
240    let mut run_start_idx = 0usize;
241
242    let flush_unicode_run = |run: &mut String,
243                             start_idx: usize,
244                             dest: &mut Vec<u128>,
245                             log_out: &mut FormatLog| {
246        if !run.is_empty() {
247            if ctb_formats_unicode::is_nfc_normalized(run) {
248                for ch in run.chars() {
249                    dest.push(u128::from(u32::from(ch)));
250                }
251            } else {
252                let nfc = ctb_formats_unicode::normalize_nfc(run);
253                if permissive {
254                    // Reason for fallback: if usize index fails u64 conversion, fallback 0 is used for log position.
255                    let idx_u64 = u64::try_from(start_idx).unwrap_or(0);
256                    log_out.export_warning(
257                        idx_u64,
258                        "Normalized Unicode text sequence to NFC",
259                    );
260                }
261                for ch in nfc.chars() {
262                    dest.push(u128::from(u32::from(ch)));
263                }
264            }
265            run.clear();
266        }
267    };
268
269    for (idx, &dc) in step1.iter().enumerate() {
270        if dc <= 0x10_FFFF
271            && let Ok(cp_u32) = u32::try_from(dc)
272            && let Some(ch) = char::from_u32(cp_u32)
273        {
274            if unicode_run.is_empty() {
275                run_start_idx = idx;
276            }
277            unicode_run.push(ch);
278        } else {
279            flush_unicode_run(
280                &mut unicode_run,
281                run_start_idx,
282                &mut out,
283                log,
284            );
285            out.push(dc);
286        }
287    }
288    flush_unicode_run(&mut unicode_run, run_start_idx, &mut out, log);
289
290    Ok(out)
291}
292
293/// Normalizes all deprecated Document Characters (to their canonical or preferred
294/// replacements) and normalizes Unicode text chunks to NFC in a `DcMstr`,
295/// preserving binary chunks intact.
296pub fn normalize_dcmstring_all(
297    doc: &crate::DcMstr,
298    permissive: bool,
299) -> Result<(crate::DcMstring, FormatLog)> {
300    let mut normalized = crate::DcMstring::new();
301    let mut log = FormatLog::default();
302    for chunk in doc.chunks() {
303        if let crate::DcMixedChunk::Text(text) = chunk {
304            let dclist = text.to_dclist();
305            let norm_dclist =
306                normalize_dclist_all(&dclist, permissive, &mut log)?;
307            for dc in norm_dclist {
308                normalized.push_char(crate::DcChar::from_u128(dc));
309            }
310        } else {
311            normalized.push_chunk(&chunk)?;
312        }
313    }
314    Ok((normalized, log))
315}
316
317/// Converts a `DcList` (`&[u128]`) into UTF-8 bytes (`Vec<u8>`).
318pub fn dclist_to_utf8(
319    dclist: &[u128],
320    settings: &DcListUtf8Settings,
321) -> Result<ConversionOutput<Vec<u8>>> {
322    let mut log = FormatLog::default();
323    let owned_normalized;
324    let dclist: &[u128] = if settings.normalization == DcNormalizationMode::All {
325        owned_normalized =
326            normalize_dclist_all(dclist, settings.permissive, &mut log)?;
327        &owned_normalized
328    } else {
329        dclist
330    };
331    let normalize_for_target = settings.canonicalize_equivalent_dcs
332        || settings.normalization != DcNormalizationMode::None;
333
334    let mut out = Vec::new();
335    let mut unmappables: Vec<u128> = Vec::new();
336    let mut found_any_unmappables = false;
337    let max_short_u128 = u128::try_from(
338        ctb_formats_dcdata::maximum_known_short_dc(),
339    )
340    .map_err(|e| anyhow!("Failed to convert maximum_known_short_dc: {e}"))?;
341
342    let start_uuid_bytes = dcl_basenb_start_uuid_bytes()?;
343    let end_uuid_bytes = dcl_basenb_end_uuid_bytes()?;
344
345    let resolver = ctb_formats_dcdata::syntax::default_syntax_resolver();
346    let mut i = 0;
347    while i < dclist.len() {
348        let Some(&dc) = dclist.get(i) else { break };
349
350        if normalize_for_target
351            && resolver.matches_named_type_starter("text_encoding_control", dc)
352        {
353            if settings.permissive {
354                // Reason for fallback: if usize index fails u64 conversion, fallback 0 is used for log position.
355                let idx_u64 = u64::try_from(i).unwrap_or(0);
356                log.export_warning(
357                    idx_u64,
358                    &format!("Stripped text encoding control Dc {dc}"),
359                );
360            }
361            i = i.saturating_add(1);
362            continue;
363        }
364
365        // Case 1: Standard Unicode codepoint (0..=0x10FFFF, excluding surrogates)
366        if dc <= 0x10_FFFF {
367            if let Ok(cp_u32) = u32::try_from(dc) {
368                if let Some(ch) = char::from_u32(cp_u32) {
369                    flush_unmappables(
370                        &mut out,
371                        &mut unmappables,
372                        &mut found_any_unmappables,
373                        false,
374                        settings,
375                        &start_uuid_bytes,
376                    )?;
377                    let mut buf = [0u8; 4];
378                    let encoded = ch.encode_utf8(&mut buf);
379                    out.extend_from_slice(encoded.as_bytes());
380                    i = i.saturating_add(1);
381                    continue;
382                }
383            }
384        }
385
386        // Case 2: Short Dc offset range (SHORT_DC_REGION_START..=SHORT_DC_REGION_START + max_short)
387        if dc >= SHORT_DC_REGION_START {
388            let diff = dc.saturating_sub(SHORT_DC_REGION_START);
389            if diff <= max_short_u128 {
390                if normalize_for_target {
391                    // Sub-case 2a: Legacy base64 UTF-8 sequence starting with DcRole::StartEncapsulationUtf8 (191)
392                    if resolver
393                        .token_fills_role(dc, DcRole::StartEncapsulationUtf8)
394                    {
395                        let (decoded, next) = decode_utf8_encapsulation(
396                            dclist,
397                            i,
398                            settings.permissive,
399                            resolver.as_ref(),
400                            &mut log,
401                        )?;
402                        flush_unmappables(
403                            &mut out,
404                            &mut unmappables,
405                            &mut found_any_unmappables,
406                            false,
407                            settings,
408                            &start_uuid_bytes,
409                        )?;
410                        let (bytes, decoded_log) =
411                            dcmstr_to_utf8_with_options(&decoded, settings)?;
412                        log.merge(&decoded_log);
413                        out.extend_from_slice(&bytes);
414                        i = next;
415                        continue;
416                    }
417
418                    // Sub-case 2b: Standard short Dc to UTF-8 mapping
419                    let canon_dc = resolver.canonical_token(dc);
420                    if canon_dc <= 0x10_FFFF {
421                        if let Ok(cp_u32) = u32::try_from(canon_dc) {
422                            if let Some(ch) = char::from_u32(cp_u32) {
423                                flush_unmappables(
424                                    &mut out,
425                                    &mut unmappables,
426                                    &mut found_any_unmappables,
427                                    false,
428                                    settings,
429                                    &start_uuid_bytes,
430                                )?;
431                                if settings.permissive {
432                                    // Reason for fallback: if usize index fails u64 conversion, fallback 0 is used for log position.
433                                    let idx_u64 = u64::try_from(i).unwrap_or(0);
434                                    log.export_warning(
435                                        idx_u64,
436                                        &format!(
437                                            "Canonicalized equivalent short Dc {diff} to '{ch}'"
438                                        ),
439                                    );
440                                }
441                                let mut buf = [0u8; 4];
442                                let encoded = ch.encode_utf8(&mut buf);
443                                out.extend_from_slice(encoded.as_bytes());
444                                i = i.saturating_add(1);
445                                continue;
446                            }
447                        }
448                    }
449                    if let Some(text) = resolver.unicode_text_mapping(dc, true)
450                    {
451                        flush_unmappables(
452                            &mut out,
453                            &mut unmappables,
454                            &mut found_any_unmappables,
455                            false,
456                            settings,
457                            &start_uuid_bytes,
458                        )?;
459                        if settings.permissive {
460                            // Reason for fallback: if usize index fails u64 conversion, fallback 0 is used for log position.
461                            let idx_u64 = u64::try_from(i).unwrap_or(0);
462                            log.export_warning(
463                                idx_u64,
464                                &format!(
465                                    "Canonicalized equivalent short Dc {diff} to \"{text}\""
466                                ),
467                            );
468                        }
469                        out.extend_from_slice(text.as_bytes());
470                        i = i.saturating_add(1);
471                        continue;
472                    }
473                }
474            }
475        }
476
477        // Case 3: Unmappable Dc
478        if settings.dcl_basenb_enabled {
479            unmappables.push(dc);
480        } else {
481            // Reason for fallback: if usize index fails u64 conversion, fallback 0 is used for log position.
482            let idx_u64 = u64::try_from(i).unwrap_or(0);
483            if settings.permissive {
484                log.export_warning(
485                    idx_u64,
486                    &format!("Dc {dc} has no UTF-8 mapping"),
487                );
488            } else {
489                log.export_error(
490                    idx_u64,
491                    &format!("Dc {dc} has no UTF-8 mapping"),
492                );
493            }
494            if !settings.skip_unmappable {
495                out.extend_from_slice(UTF8_REPLACEMENT_CHARACTER);
496            }
497        }
498
499        i = i.saturating_add(1);
500    }
501
502    // Flush any remaining unmappables
503    flush_unmappables(
504        &mut out,
505        &mut unmappables,
506        &mut found_any_unmappables,
507        true,
508        settings,
509        &start_uuid_bytes,
510    )?;
511
512    // Append end UUID sentinel if armoring was active
513    if settings.dcl_basenb_enabled
514        && found_any_unmappables
515        && !settings.dcl_basenb_fragment_enabled
516    {
517        out.extend_from_slice(&end_uuid_bytes);
518    }
519
520    Ok(ConversionOutput::new(out, log))
521}
522
523fn decode_utf8_encapsulation(
524    dcs: &[u128],
525    start: usize,
526    permissive: bool,
527    resolver: &dyn SyntaxRuleResolver,
528    log: &mut FormatLog,
529) -> Result<(crate::DcMstring, usize)> {
530    let mut end = start.saturating_add(1);
531    let mut terminated = false;
532    let mut first_invalid = None;
533    let mut digits = Vec::new();
534    while let Some(&token) = dcs.get(end) {
535        if resolver.token_fills_role(token, DcRole::EndEncapsulationUtf8) {
536            terminated = true;
537            break;
538        }
539        if resolver.token_fills_role(token, DcRole::StartEncapsulationUtf8) {
540            break;
541        }
542        if resolver
543            .matches_named_type_starter("base64_transport_control", token)
544        {
545            end = end.saturating_add(1);
546            continue;
547        }
548        if let Some(digit) = resolver.base64_digit_value(token) {
549            digits.push(
550                ctb_formats_dcdata::dc_number_minimal::dc_base64_digit_to_char(
551                    digit,
552                )
553                .to_short()?,
554            );
555        } else if resolver.token_fills_role(token, DcRole::Base64Padding) {
556            digits.push(
557                crate::DcChar::from_u128(resolver.canonical_token(token))
558                    .to_short()?,
559            );
560        } else {
561            first_invalid.get_or_insert(end);
562        }
563        end = end.saturating_add(1);
564    }
565    let next = if terminated {
566        end.saturating_add(1)
567    } else if let Some(invalid) = first_invalid {
568        invalid
569    } else {
570        end
571    };
572    let decoded = if !terminated || first_invalid.is_some() {
573        Err(anyhow!(
574            "Unterminated or malformed encapsulated UTF-8 payload"
575        ))
576    } else {
577        dc_encapsulated_raw_to_bytes(&digits)
578    };
579    let bytes = match decoded {
580        Ok(bytes) => bytes,
581        Err(error) if permissive => {
582            log.import_warning(
583                u64::try_from(start)?,
584                &format!("{error}; substituting U+FFFD"),
585            );
586            return Ok((crate::DcMstring::from("\u{FFFD}"), next));
587        }
588        Err(error) => return Err(error),
589    };
590    let (doc, decoded_log) = utf8_to_dcmstring_with_options(&bytes, permissive)
591        .context("Invalid encapsulated UTF-8")?;
592    log.merge(&decoded_log);
593    Ok((doc, next))
594}
595
596/// Validates legacy UTF-8 encapsulations, repairing damaged payloads only
597/// when permissive mode is enabled. Valid text, framing, and binary chunks
598/// are preserved without normalization.
599///
600/// # Errors
601/// Returns an error for malformed encapsulated text in strict mode or for
602/// invalid document data.
603pub fn repair_utf8_encapsulations(
604    doc: &crate::DcMstr,
605    permissive: bool,
606) -> Result<(crate::DcMstring, FormatLog)> {
607    let resolver = ctb_formats_dcdata::syntax::default_syntax_resolver();
608    let mut repaired = crate::DcMstring::new();
609    let mut log = FormatLog::default();
610    for chunk in doc.chunks() {
611        if let crate::DcMixedChunk::Text(text) = chunk {
612            let tokens: Vec<_> = text.chars().map(|ch| ch.to_long()).collect();
613            let mut cursor = 0;
614            while let Some(&token) = tokens.get(cursor) {
615                if resolver
616                    .token_fills_role(token, DcRole::StartEncapsulationUtf8)
617                {
618                    let warning_count = log.get_warnings().len();
619                    let (decoded, next) = decode_utf8_encapsulation(
620                        &tokens,
621                        cursor,
622                        permissive,
623                        resolver.as_ref(),
624                        &mut log,
625                    )?;
626                    if log.get_warnings().len() == warning_count {
627                        for &original in tokens
628                            .get(cursor..next)
629                            .context("Invalid UTF-8 encapsulation boundary")?
630                        {
631                            repaired
632                                .push_char(crate::DcChar::from_u128(original));
633                        }
634                    } else {
635                        repaired.push_dc_str(&decoded.to_dc_string()?);
636                    }
637                    cursor = next;
638                } else {
639                    repaired.push_char(crate::DcChar::from_u128(token));
640                    cursor = cursor.saturating_add(1);
641                }
642            }
643        } else {
644            repaired.push_chunk(&chunk)?;
645        }
646    }
647    Ok((repaired, log))
648}
649
650/// Flush accumulated unmappables using `dclist_to_dcutf` and `byte_array_to_basenb_17_utf8`.
651fn flush_unmappables(
652    out: &mut Vec<u8>,
653    unmappables: &mut Vec<u128>,
654    found_any_unmappables: &mut bool,
655    force: bool,
656    settings: &DcListUtf8Settings,
657    start_uuid_bytes: &[u8],
658) -> Result<()> {
659    if settings.dcl_basenb_enabled
660        && (force || !unmappables.is_empty())
661        && !unmappables.is_empty()
662    {
663        if !*found_any_unmappables && !settings.dcl_basenb_fragment_enabled {
664            out.extend_from_slice(start_uuid_bytes);
665        }
666        *found_any_unmappables = true;
667
668        let dcutf_bytes = dclist_to_dcutf(unmappables);
669        let encoded_base17 = byte_array_to_basenb_17_utf8(&dcutf_bytes)?;
670        out.extend_from_slice(&encoded_base17);
671
672        unmappables.clear();
673    }
674    Ok(())
675}
676
677/// Decodes UTF-8 bytes (`&[u8]`) into a `DcList` (`Vec<u128>`).
678pub fn dclist_from_utf8(
679    utf8_bytes: &[u8],
680    settings: &DcListUtf8Settings,
681) -> Result<ConversionOutput<DcList>> {
682    let mut log = FormatLog::default();
683    let mut result = Vec::new();
684    let mut remaining = utf8_bytes;
685
686    let start_uuid_bytes = dcl_basenb_start_uuid_bytes()?;
687    let end_uuid_bytes = dcl_basenb_end_uuid_bytes()?;
688
689    while !remaining.is_empty() {
690        if settings.dcl_basenb_enabled {
691            let is_start_basenb = if settings.dcl_basenb_fragment_enabled {
692                if let Ok((first_char, consumed)) =
693                    first_char_of_utf8_string(remaining)
694                {
695                    consumed > 0 && is_basenb_char(&first_char)
696                } else {
697                    false
698                }
699            } else {
700                remaining.starts_with(&start_uuid_bytes)
701            };
702
703            if is_start_basenb {
704                if !settings.dcl_basenb_fragment_enabled {
705                    if let Some(rem) = remaining.get(start_uuid_bytes.len()..) {
706                        remaining = rem;
707                    } else {
708                        remaining = &[];
709                    }
710                }
711
712                let end_pos = if settings.dcl_basenb_fragment_enabled {
713                    let mut consumed_total = 0;
714                    while consumed_total < remaining.len() {
715                        let Some(sub) = remaining.get(consumed_total..) else {
716                            break;
717                        };
718                        if let Ok((ch_bytes, ch_len)) =
719                            first_char_of_utf8_string(sub)
720                        {
721                            if ch_len == 0 || !is_basenb_char(&ch_bytes) {
722                                break;
723                            }
724                            consumed_total =
725                                consumed_total.saturating_add(ch_len);
726                        } else {
727                            break;
728                        }
729                    }
730                    Some(consumed_total)
731                } else {
732                    remaining
733                        .windows(end_uuid_bytes.len())
734                        .position(|w| w == end_uuid_bytes)
735                };
736
737                if let Some(pos) = end_pos {
738                    let Some(inner_region) = remaining.get(..pos) else {
739                        break;
740                    };
741                    let mut basenb_run = Vec::new();
742                    let mut inner_rem = inner_region;
743
744                    while !inner_rem.is_empty() {
745                        if let Ok((ch_bytes, ch_len)) =
746                            first_char_of_utf8_string(inner_rem)
747                        {
748                            if ch_len > 0 && is_basenb_char(&ch_bytes) {
749                                basenb_run.extend_from_slice(&ch_bytes);
750                            } else {
751                                if !basenb_run.is_empty() {
752                                    match byte_array_from_basenb_17_utf8(
753                                        &basenb_run,
754                                    ) {
755                                        Ok(dcutf_bytes) => {
756                                            result.extend(dcutf_to_dclist(
757                                                &dcutf_bytes,
758                                            ));
759                                        }
760                                        Err(e) => {
761                                            let msg = format!(
762                                                "Failed to decode dcl_basenb 17 run: {e}"
763                                            );
764                                            if settings
765                                                .dcl_basenb_fragment_strict
766                                            {
767                                                log.import_error(0, &msg);
768                                            } else {
769                                                log.import_warning(0, &msg);
770                                            }
771                                        }
772                                    }
773                                    basenb_run.clear();
774                                }
775                                if ch_len > 0 {
776                                    if let Ok(s) =
777                                        std::str::from_utf8(&ch_bytes)
778                                    {
779                                        for ch in s.chars() {
780                                            result.push(u128::from(u32::from(
781                                                ch,
782                                            )));
783                                        }
784                                    }
785                                }
786                            }
787                            if let Some(rem) = inner_rem.get(ch_len..) {
788                                inner_rem = rem;
789                            } else {
790                                inner_rem = &[];
791                            }
792                        } else {
793                            break;
794                        }
795                    }
796
797                    if !basenb_run.is_empty() {
798                        match byte_array_from_basenb_17_utf8(&basenb_run) {
799                            Ok(dcutf_bytes) => {
800                                result.extend(dcutf_to_dclist(&dcutf_bytes));
801                            }
802                            Err(e) => {
803                                let msg = format!(
804                                    "Failed to decode dcl_basenb 17 run: {e}"
805                                );
806                                if settings.dcl_basenb_fragment_strict {
807                                    log.import_error(0, &msg);
808                                } else {
809                                    log.import_warning(0, &msg);
810                                }
811                            }
812                        }
813                        basenb_run.clear();
814                    }
815
816                    if settings.dcl_basenb_fragment_enabled {
817                        if let Some(rem) = remaining.get(pos..) {
818                            remaining = rem;
819                        } else {
820                            remaining = &[];
821                        }
822                    } else if let Some(rem) = remaining
823                        .get(pos.saturating_add(end_uuid_bytes.len())..)
824                    {
825                        remaining = rem;
826                    } else {
827                        remaining = &[];
828                    }
829                    continue;
830                }
831            }
832        }
833
834        // Standard UTF-8 character decoding
835        if let Ok((ch_bytes, consumed)) = first_char_of_utf8_string(remaining) {
836            if consumed > 0 {
837                if let Ok(s) = std::str::from_utf8(&ch_bytes) {
838                    for ch in s.chars() {
839                        result.push(u128::from(u32::from(ch)));
840                    }
841                }
842                if let Some(rem) = remaining.get(consumed..) {
843                    remaining = rem;
844                } else {
845                    remaining = &[];
846                }
847                continue;
848            }
849        }
850
851        // Advance by 1 byte if invalid UTF-8
852        if let Some(&b) = remaining.first() {
853            log.import_warning(0, &format!("Invalid UTF-8 byte 0x{b:02X}"));
854            if let Some(rem) = remaining.get(1..) {
855                remaining = rem;
856            } else {
857                remaining = &[];
858            }
859        } else {
860            break;
861        }
862    }
863
864    Ok(ConversionOutput::new(result, log))
865}
866
867/// Alias for `dclist_from_utf8`.
868pub fn utf8_to_dclist(
869    utf8_bytes: &[u8],
870    settings: &DcListUtf8Settings,
871) -> Result<ConversionOutput<DcList>> {
872    dclist_from_utf8(utf8_bytes, settings)
873}
874
875/// Converts UTF-8 text bytes to a `DcMstring`.
876pub fn utf8_to_dcmstring(
877    bytes: &[u8],
878) -> Result<(crate::DcMstring, FormatLog)> {
879    utf8_to_dcmstring_with_options(bytes, false)
880}
881
882/// Converts UTF-8 text bytes to a `DcMstring`, optionally in permissive mode.
883pub fn utf8_to_dcmstring_with_options(
884    bytes: &[u8],
885    permissive: bool,
886) -> Result<(crate::DcMstring, FormatLog)> {
887    if !permissive {
888        let text = std::str::from_utf8(bytes)
889            .map_err(|e| anyhow!("Input is not valid UTF-8 text: {e}"))?;
890        let dc_str =
891            crate::DcStr::from_bytes(text.as_bytes()).map_err(|e| {
892                anyhow!("UTF-8 text contains invalid Dc sequences: {e}")
893            })?;
894        let doc = crate::DcMstring::from_dc_str(dc_str)?;
895        return Ok((doc, FormatLog::default()));
896    }
897
898    let mut log = FormatLog::default();
899    let mut doc =
900        crate::DcMstring::with_capacity(bytes.len().saturating_add(21));
901    let mut offset = 0usize;
902    for chunk in bytes.utf8_chunks() {
903        let valid = chunk.valid();
904        if !valid.is_empty() {
905            doc.push_str(valid);
906            offset = offset.saturating_add(valid.len());
907        }
908        let invalid = chunk.invalid();
909        if !invalid.is_empty() {
910            log.import_warning(
911                u64::try_from(offset)?,
912                &format!(
913                    "Invalid UTF-8 sequence ({len} bytes) at offset {offset}; substituting U+FFFD",
914                    len = invalid.len()
915                ),
916            );
917            doc.push_char(crate::DcChar::from('\u{FFFD}'));
918            offset = offset.saturating_add(invalid.len());
919        }
920    }
921    Ok((doc, log))
922}
923
924/// Converts a `DcMstring` to UTF-8 bytes in strict mode (without canonicalization of equivalent Dcs).
925pub fn dcmstring_to_utf8(doc: &crate::DcMstr) -> Result<(Vec<u8>, FormatLog)> {
926    dcmstring_to_utf8_with_options(doc, false)
927}
928
929/// Converts a `DcMstring` to UTF-8 bytes with permissive or strict options.
930///
931/// In permissive mode (`permissive == true`), characters that cannot be
932/// represented as-is in UTF-8 are normalized (`DcNormalizationMode::RequiredByTarget`)
933/// with warnings, and malformed encodings recover with replacement characters and warnings.
934///
935/// In strict mode (`permissive == false`), characters are not normalized
936/// (`DcNormalizationMode::None`), unrepresentable characters log export errors,
937/// and malformed encodings return an error.
938pub fn dcmstring_to_utf8_with_options(
939    doc: &crate::DcMstr,
940    permissive: bool,
941) -> Result<(Vec<u8>, FormatLog)> {
942    let normalization = if permissive {
943        DcNormalizationMode::RequiredByTarget
944    } else {
945        DcNormalizationMode::None
946    };
947    dcmstring_to_utf8_with_normalization(doc, permissive, normalization)
948}
949
950/// Converts a `DcMstring` to UTF-8 bytes with explicit strictness and normalization policy.
951pub fn dcmstring_to_utf8_with_normalization(
952    doc: &crate::DcMstr,
953    permissive: bool,
954    normalization: DcNormalizationMode,
955) -> Result<(Vec<u8>, FormatLog)> {
956    dcmstr_to_utf8_with_options(
957        doc,
958        &DcListUtf8Settings {
959            canonicalize_equivalent_dcs: normalization
960                != DcNormalizationMode::None,
961            normalization,
962            permissive,
963            ..Default::default()
964        },
965    )
966}
967
968/// Projects a Dc document to UTF-8 using the requested equivalence and
969/// unmappable-character policies.
970///
971/// # Errors
972/// Returns an error for malformed encapsulated text or document data.
973pub fn dcmstr_to_utf8_with_options(
974    doc: &crate::DcMstr,
975    settings: &DcListUtf8Settings,
976) -> Result<(Vec<u8>, FormatLog)> {
977    let dc_string = super::document_dc_string(doc)?;
978    let dclist = dc_string.to_dclist();
979    let conv = dclist_to_utf8(&dclist, settings)?;
980    Ok((conv.result, conv.log))
981}
982
983/// Converts DcTF bytes to a `DcMstring`.
984pub fn dctf_to_dcmstring(
985    bytes: &[u8],
986) -> Result<(crate::DcMstring, FormatLog)> {
987    dctf_to_dcmstring_with_options(bytes, false)
988}
989
990/// Converts DcTF bytes to a `DcMstring`, optionally in permissive mode.
991pub fn dctf_to_dcmstring_with_options(
992    bytes: &[u8],
993    permissive: bool,
994) -> Result<(crate::DcMstring, FormatLog)> {
995    if !permissive {
996        let dc_str = crate::DcStr::from_bytes(bytes).map_err(|e| {
997            anyhow!("Input bytes do not conform to valid DcTF format: {e}")
998        })?;
999        let doc = crate::DcMstring::from_dc_str(dc_str)?;
1000        return Ok((doc, FormatLog::default()));
1001    }
1002
1003    let mut log = FormatLog::default();
1004    let mut doc =
1005        crate::DcMstring::with_capacity(bytes.len().saturating_add(21));
1006    let mut offset = 0usize;
1007    while offset < bytes.len() {
1008        let Some(slice) = bytes.get(offset..) else {
1009            break;
1010        };
1011        if let Some((val, char_len)) = ctb_formats_dctf::decode_dctf_buf(slice)
1012        {
1013            doc.push_char(crate::DcChar(val));
1014            offset = offset.saturating_add(char_len);
1015        } else {
1016            // Reason for fallback: when error_len is None (incomplete sequence at end of slice), consume the remaining bytes of the incomplete sequence.
1017            let step = ctb_formats_dctf::determine_dctf_error_len(slice)
1018                .unwrap_or(slice.len())
1019                .max(1)
1020                .min(slice.len());
1021            log.import_warning(
1022                u64::try_from(offset)?,
1023                &format!(
1024                    "Invalid DcTF sequence ({step} bytes) at offset {offset}; substituting U+FFFD"
1025                ),
1026            );
1027            doc.push_char(crate::DcChar::from('\u{FFFD}'));
1028            offset = offset.saturating_add(step);
1029        }
1030    }
1031    Ok((doc, log))
1032}
1033
1034/// Converts a `DcMstring` to DcTF bytes.
1035pub fn dcmstring_to_dctf(
1036    doc: &crate::DcMstring,
1037) -> Result<(Vec<u8>, FormatLog)> {
1038    let dc_string = super::document_dc_string(doc)?;
1039    Ok((dc_string.into_bytes(), FormatLog::default()))
1040}
1041
1042/// Converts legacy DcUtf bytes to a `DcMstring`.
1043pub fn dcutf_to_dcmstring(
1044    bytes: &[u8],
1045) -> Result<(crate::DcMstring, FormatLog)> {
1046    dcutf_to_dcmstring_with_options(bytes, false)
1047}
1048
1049/// Converts legacy DcUtf bytes to a `DcMstring`, optionally in permissive mode.
1050pub fn dcutf_to_dcmstring_with_options(
1051    bytes: &[u8],
1052    permissive: bool,
1053) -> Result<(crate::DcMstring, FormatLog)> {
1054    if !permissive {
1055        crate::validate_dcutf(bytes).map_err(|e| {
1056            anyhow!("Input bytes do not conform to valid DcUtf format: {e}")
1057        })?;
1058        let dc_string =
1059            crate::DcString::from_dcutf(bytes.to_vec()).map_err(|e| {
1060                anyhow!("Input bytes do not conform to valid DcUtf format: {e}")
1061            })?;
1062        let doc = crate::DcMstring::from_dc_string(&dc_string)?;
1063        return Ok((doc, FormatLog::default()));
1064    }
1065
1066    let mut log = FormatLog::default();
1067    let mut doc =
1068        crate::DcMstring::with_capacity(bytes.len().saturating_add(21));
1069    let mut offset = 0usize;
1070    while offset < bytes.len() {
1071        let Some(slice) = bytes.get(offset..) else {
1072            break;
1073        };
1074        if let Some((val, char_len)) =
1075            ctb_formats_dctf::decode_utf_8e_128_buf(slice)
1076        {
1077            doc.push_char(crate::DcChar(val));
1078            offset = offset.saturating_add(char_len);
1079        } else {
1080            // Reason for fallback: when error_len is None (incomplete sequence at end of slice), consume the remaining bytes of the incomplete sequence.
1081            let step = ctb_formats_dctf::determine_utf_8e_128_error_len(slice)
1082                .unwrap_or(slice.len())
1083                .max(1)
1084                .min(slice.len());
1085            log.import_warning(
1086                u64::try_from(offset)?,
1087                &format!(
1088                    "Invalid DcUtf sequence ({step} bytes) at offset {offset}; substituting U+FFFD"
1089                ),
1090            );
1091            doc.push_char(crate::DcChar::from('\u{FFFD}'));
1092            offset = offset.saturating_add(step);
1093        }
1094    }
1095    Ok((doc, log))
1096}
1097
1098/// Converts a `DcMstring` to legacy DcUtf bytes.
1099pub fn dcmstring_to_dcutf(
1100    doc: &crate::DcMstring,
1101) -> Result<(Vec<u8>, FormatLog)> {
1102    let dc_string = super::document_dc_string(doc)?;
1103    let bytes = super::dctext::dclist_to_dcutf(&dc_string.to_dclist());
1104    Ok((bytes, FormatLog::default()))
1105}
1106
1107#[cfg(test)]
1108#[allow(
1109    clippy::panic,
1110    clippy::expect_used,
1111    clippy::unwrap_used,
1112    clippy::unwrap_in_result,
1113    clippy::panic_in_result_fn,
1114    clippy::indexing_slicing,
1115    clippy::arithmetic_side_effects,
1116    reason = "Standard repository test boilerplate"
1117)]
1118mod tests {
1119    use super::*;
1120
1121    #[crate::ctb_test]
1122    fn test_dclist_utf8_basic_unicode() {
1123        let input: DcList = vec![72, 101, 108, 108, 111, 32, 128514]; // "Hello 😂"
1124        let settings = DcListUtf8Settings::default();
1125        let conv = dclist_to_utf8(&input, &settings).unwrap();
1126        assert_eq!(String::from_utf8(conv.result.clone()).unwrap(), "Hello 😂");
1127
1128        let back = dclist_from_utf8(&conv.result, &settings).unwrap();
1129        assert_eq!(back.result, input);
1130    }
1131
1132    #[crate::ctb_test]
1133    fn test_dclist_utf8_basenb_armored_roundtrip() {
1134        let unmappable_dc = SHORT_DC_REGION_START + 999_999;
1135        let input: DcList = vec![72, 105, unmappable_dc, 33];
1136        let mut settings = DcListUtf8Settings::default();
1137        settings.dcl_basenb_enabled = true;
1138
1139        let conv = dclist_to_utf8(&input, &settings).unwrap();
1140        let back = dclist_from_utf8(&conv.result, &settings).unwrap();
1141        assert_eq!(back.result, input);
1142    }
1143
1144    #[crate::ctb_test]
1145    fn test_dclist_utf8_basenb_fragment_roundtrip() {
1146        let unmappable_dc = SHORT_DC_REGION_START + 888_888;
1147        let input: DcList = vec![65, unmappable_dc, 66];
1148        let mut settings = DcListUtf8Settings::default();
1149        settings.dcl_basenb_enabled = true;
1150        settings.dcl_basenb_fragment_enabled = true;
1151
1152        let conv = dclist_to_utf8(&input, &settings).unwrap();
1153        let back = dclist_from_utf8(&conv.result, &settings).unwrap();
1154        assert_eq!(back.result, input);
1155    }
1156
1157    #[crate::ctb_test]
1158    fn test_dclist_utf8_replacement_and_skip() {
1159        let unmappable_dc = SHORT_DC_REGION_START + 777_777;
1160        let input: DcList = vec![65, unmappable_dc, 66];
1161
1162        // Replacement mode
1163        let settings_replace = DcListUtf8Settings::default();
1164        let conv_replace = dclist_to_utf8(&input, &settings_replace).unwrap();
1165        assert_eq!(
1166            String::from_utf8(conv_replace.result).unwrap(),
1167            "A\u{FFFD}B"
1168        );
1169
1170        // Skip mode
1171        let mut settings_skip = DcListUtf8Settings::default();
1172        settings_skip.skip_unmappable = true;
1173        let conv_skip = dclist_to_utf8(&input, &settings_skip).unwrap();
1174        assert_eq!(String::from_utf8(conv_skip.result).unwrap(), "AB");
1175    }
1176
1177    #[crate::ctb_test]
1178    fn test_utf8_projection_rejects_malformed_encapsulation() {
1179        let settings = DcListUtf8Settings {
1180            canonicalize_equivalent_dcs: true,
1181            ..Default::default()
1182        };
1183        for short_dcs in [
1184            vec![191, 190, 175, 195, 195, 192],
1185            vec![191, 127, 192],
1186            vec![191, 50, 192],
1187            vec![191, 143, 143, 195, 195],
1188        ] {
1189            let mut doc = crate::DcMstring::new();
1190            for short_dc in short_dcs {
1191                doc.push_char(crate::DcChar::from_short(short_dc));
1192            }
1193            assert!(dcmstr_to_utf8_with_options(&doc, &settings).is_err());
1194        }
1195        let mut doc = crate::DcMstring::new();
1196        doc.push_char(crate::DcChar::from_short(191));
1197        doc.push_char(crate::DcChar::from_short(192));
1198        assert_eq!(
1199            dcmstr_to_utf8_with_options(&doc, &settings).unwrap().0,
1200            b""
1201        );
1202    }
1203
1204    #[crate::ctb_test]
1205    fn test_utf8_conversion_permissive_encapsulation() {
1206        let settings = DcListUtf8Settings {
1207            canonicalize_equivalent_dcs: true,
1208            permissive: true,
1209            ..Default::default()
1210        };
1211        for (payload, expected) in [
1212            (vec![191, 151, 158, 188, 161, 192], "La\u{FFFD}bR"),
1213            (vec![191, 127, 192], "L\u{FFFD}R"),
1214            (vec![191, 50, 192], "L\u{FFFD}R"),
1215            (vec![191, 143, 143, 195, 195], "L\u{FFFD}R"),
1216        ] {
1217            let mut doc = crate::DcMstring::from("L");
1218            for short_dc in payload {
1219                doc.push_char(crate::DcChar::from_short(short_dc));
1220            }
1221            doc.push_str("R");
1222            let (bytes, log) =
1223                dcmstr_to_utf8_with_options(&doc, &settings).unwrap();
1224            assert_eq!(bytes, expected.as_bytes());
1225            assert!(log.has_warnings() && !log.has_errors());
1226            let (repaired, log) =
1227                repair_utf8_encapsulations(&doc, true).unwrap();
1228            assert!(log.has_warnings() && !log.has_errors());
1229            assert_eq!(
1230                dcmstr_to_utf8_with_options(&repaired, &settings).unwrap().0,
1231                bytes
1232            );
1233            assert!(repair_utf8_encapsulations(&doc, false).is_err());
1234            let strict = DcListUtf8Settings {
1235                permissive: false,
1236                ..settings.clone()
1237            };
1238            assert!(dcmstr_to_utf8_with_options(&doc, &strict).is_err());
1239        }
1240        let mut valid = crate::DcMstring::new();
1241        for short in [191, 143, 143, 195, 195, 192] {
1242            valid.push_char(crate::DcChar::from_short(short));
1243        }
1244        valid.push_binary(b"\xff\x00");
1245        let (repaired, log) = repair_utf8_encapsulations(&valid, true).unwrap();
1246        assert_eq!(repaired, valid);
1247        assert!(!log.has_warnings() && !log.has_errors());
1248    }
1249
1250    #[crate::ctb_test]
1251    fn test_utf8_encapsulation_transport_controls() {
1252        let mut doc = crate::DcMstring::from("L");
1253        doc.push_char(crate::dc::DC_START_ENCAPSULATION_UTF8);
1254        for digit in [143, 143, 195, 195] {
1255            for control in [13, 14, 16, 196, 197, 198, 199] {
1256                doc.push_char(crate::DcChar::from_short(control));
1257            }
1258            doc.push_char(crate::DcChar::from_short(digit));
1259        }
1260        doc.push_char(crate::dc::DC_END_ENCAPSULATION_UTF8);
1261        doc.push_str("R");
1262        let (text, log) = dcmstr_to_utf8_with_options(
1263            &doc,
1264            &DcListUtf8Settings {
1265                canonicalize_equivalent_dcs: true,
1266                ..Default::default()
1267            },
1268        )
1269        .unwrap();
1270        assert_eq!(text, b"LAR");
1271        assert!(!log.has_warnings() && !log.has_errors());
1272        let (preserved, log) = repair_utf8_encapsulations(&doc, false).unwrap();
1273        assert_eq!(preserved, doc);
1274        assert!(!log.has_warnings());
1275        crate::DcDocumentNavigator::parse_document_arena(
1276            doc.as_bytes(),
1277            &mut crate::DcSyntaxArena::new(),
1278            &crate::DcProjectionPolicy::strict(),
1279        )
1280        .unwrap();
1281    }
1282
1283    #[crate::ctb_test]
1284    fn test_utf8_strict_vs_permissive_equivalent_dcs() {
1285        let mut doc = crate::DcMstring::new();
1286        // Short Dc 65 ('P')
1287        doc.push_char(crate::DcChar::from_short(65));
1288
1289        // Strict mode (default): does NOT canonicalize equivalent Dcs and logs an error
1290        let (strict_bytes, strict_log) =
1291            dcmstring_to_utf8_with_options(&doc, false).unwrap();
1292        assert_eq!(strict_bytes, "\u{FFFD}".as_bytes());
1293        assert!(strict_log.has_errors());
1294        assert!(!strict_log.has_warnings());
1295
1296        // Default dcmstring_to_utf8 is strict
1297        let (def_bytes, def_log) = dcmstring_to_utf8(&doc).unwrap();
1298        assert_eq!(def_bytes, "\u{FFFD}".as_bytes());
1299        assert!(def_log.has_errors());
1300        assert!(!def_log.has_warnings());
1301
1302        // Permissive mode with DcNormalizationMode::None ("no normalization"):
1303        // replaces unrepresentable characters with U+FFFD and logs a warning
1304        let (no_norm_bytes, no_norm_log) = dcmstring_to_utf8_with_normalization(
1305            &doc,
1306            true,
1307            DcNormalizationMode::None,
1308        )
1309        .unwrap();
1310        assert_eq!(no_norm_bytes, "\u{FFFD}".as_bytes());
1311        assert!(no_norm_log.has_warnings());
1312        assert!(!no_norm_log.has_errors());
1313
1314        // Permissive mode (default DcNormalizationMode::RequiredByTarget):
1315        // canonicalizes equivalent Dcs with warnings
1316        let (perm_bytes, perm_log) =
1317            dcmstring_to_utf8_with_options(&doc, true).unwrap();
1318        assert_eq!(perm_bytes, b"P");
1319        assert!(perm_log.has_warnings());
1320        assert!(!perm_log.has_errors());
1321
1322        // Compare RequiredByTarget vs All on decomposed Unicode ("cafe\u{0301}") + short Dc 65 ('P')
1323        let mut mixed_doc = crate::DcMstring::from("cafe\u{0301}");
1324        mixed_doc.push_char(crate::DcChar::from_short(65));
1325
1326        let (req_bytes, req_log) = dcmstring_to_utf8_with_normalization(
1327            &mixed_doc,
1328            true,
1329            DcNormalizationMode::RequiredByTarget,
1330        )
1331        .unwrap();
1332        // RequiredByTarget preserves "cafe\u{0301}" as-is and only normalizes short Dc 65 -> 'P'
1333        assert_eq!(req_bytes, "cafe\u{0301}P".as_bytes());
1334        assert!(req_log.has_warnings());
1335
1336        let (all_bytes, all_log) = dcmstring_to_utf8_with_normalization(
1337            &mixed_doc,
1338            true,
1339            DcNormalizationMode::All,
1340        )
1341        .unwrap();
1342        // All normalizes both "cafe\u{0301}" -> "caf\u{00E9}" (NFC) and short Dc 65 -> 'P'
1343        assert_eq!(all_bytes, "caf\u{00E9}P".as_bytes());
1344        assert!(all_log.has_warnings());
1345    }
1346
1347    #[crate::ctb_test]
1348    fn test_dclist_utf8_canonicalize_equivalent_dcs() {
1349        let decimal = dclist_to_utf8(
1350            &[crate::DcChar::from_short(12).to_long()],
1351            &DcListUtf8Settings {
1352                canonicalize_equivalent_dcs: true,
1353                ..Default::default()
1354            },
1355        )
1356        .unwrap();
1357        assert_eq!(decimal.result, b".");
1358        assert!(!decimal.log.has_warnings() && !decimal.log.has_errors());
1359        // Short Dc 65 maps to 'P'
1360        let short_p = SHORT_DC_REGION_START + 65;
1361        let input: DcList = vec![short_p];
1362
1363        // Without canonicalization: treated as unmappable (replaced with \u{FFFD} by default)
1364        let settings_no_canon = DcListUtf8Settings::default();
1365        let conv_no_canon = dclist_to_utf8(&input, &settings_no_canon).unwrap();
1366        assert_eq!(
1367            String::from_utf8(conv_no_canon.result).unwrap(),
1368            "\u{FFFD}"
1369        );
1370
1371        // With canonicalization: maps short Dc 65 to 'P'
1372        let mut settings_canon = DcListUtf8Settings::default();
1373        settings_canon.canonicalize_equivalent_dcs = true;
1374        let conv_canon = dclist_to_utf8(&input, &settings_canon).unwrap();
1375        assert_eq!(String::from_utf8(conv_canon.result).unwrap(), "P");
1376    }
1377}