ctb_formats_eite/formats/
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//! This implements conversion to and from UTF-8, as well as to and from the
21//! dcBasenb format (which is implemented as a private-use extension of UTF-8).
22
23// - The original JS used a state machine (intDcBasenbUuidMonitorState +
24//   intDcBasenbUuidMonitorReprocessNeededCount) to detect the 8‑codepoint
25//   embedded start / end UUID sentinels while allowing possible overlaps.
26//   That logic is reproduced closely so behavior (including the original
27//   FIXME edge cases) is preserved.
28// - dcBasenb (base17b) encoding of unmappables: each unmappable Dc is pack32’d
29//   (UTF‑8 bytes for a single codepoint), then those bytes are encoded as one
30//   independent base17b unit (terminated by a distinct remainder char, which is
31//   not originally part of base17b). Each such encoded unit is concatenated
32//   inside an “armored” region (surrounded by start / end UUIDs unless the
33//   fragment variant is enabled).
34// - Error handling uses anyhow::Result. Warnings replicate original semantic
35//   intent (they are emitted, but decoding continues).
36
37#[allow(
38    unused_imports,
39    clippy::wildcard_imports,
40    reason = "Standard workspace module prelude"
41)]
42use crate::utilities::*;
43
44use anyhow::{Result, anyhow, bail};
45use const_default::ConstDefault;
46
47use crate::dc::{
48    DC_END_ENCAPSULATION_UTF8, DC_ESCAPE, DC_START_ENCAPSULATION_UTF8, DcChar,
49    bytes_as_dc_encapsulated_utf8, dc_encapsulated_raw_to_bytes,
50    is_dc_base64_encapsulation_char,
51};
52use crate::eite_state::EiteState;
53use crate::encoding::basenb::{
54    byte_array_from_basenb_17_utf8, byte_array_to_basenb_17_utf8,
55    is_basenb_char,
56};
57use crate::encoding::pack32::{pack32, unpack32};
58use crate::exceptions::excep_arr;
59use crate::formats::dcbasenb::{
60    DC_BASENB_EMBEDDED_END, DC_BASENB_EMBEDDED_END_UUID_BYTES,
61    DC_BASENB_EMBEDDED_START, DC_BASENB_EMBEDDED_START_BYTES,
62};
63use crate::formats::{dc_from_format, dc_to_format};
64use crate::settings::get_enabled_variants_for_format;
65use crate::{bail_if_none, log};
66use ctb_formats_utf8::{
67    UTF8_REPLACEMENT_CHARACTER, first_char_of_utf8_string,
68    first_char_of_utf8_string_lossless,
69};
70use ctb_formats_utilities::{CharUtfBytesExt, FormatLog};
71
72#[derive(Debug, Clone)]
73pub struct UTF8FormatSettings {
74    // Variants
75    pub dc_basenb_enabled: bool,
76    pub dc_basenb_fragment_enabled: bool,
77    /// Make fragment decode failures an error instead of warning.
78    pub dc_basenb_fragment_strict: bool,
79    /// Instead of embedding un-mappable or invalid UTF-8 to be
80    /// round-trippable, use replacement characters.
81    pub utf8_base64_embed_enabled: bool,
82    /// Skip unmappable characters entirely when outputting to UTF-8.
83    pub skip_unmappable: bool,
84    pub debug: bool,
85}
86
87impl Default for UTF8FormatSettings {
88    fn default() -> Self {
89        UTF8FormatSettings::DEFAULT
90    }
91}
92
93impl ConstDefault for UTF8FormatSettings {
94    const DEFAULT: Self = Self {
95        dc_basenb_enabled: false,
96        dc_basenb_fragment_enabled: false,
97        dc_basenb_fragment_strict: true,
98        utf8_base64_embed_enabled: true,
99        skip_unmappable: false,
100        debug: false,
101    };
102}
103
104/// Retrieve enabled UTF-8 variant settings for a direction ("in" / "out")
105pub fn utf8_variant_settings(
106    state: &EiteState,
107    direction: &str,
108) -> Result<Vec<String>> {
109    get_enabled_variants_for_format(state, "utf8", direction)
110}
111
112/// Convert an internal Dc array to UTF-8 bytes, optionally embedding
113/// unmappable Dcs inside dcBasenb armored regions.
114///
115/// Original: `dcaToUtf8`.
116pub fn dca_to_utf8(
117    dc_array: &[u32],
118    settings: &UTF8FormatSettings,
119) -> Result<(Vec<u8>, FormatLog)> {
120    let mut log = FormatLog::default();
121
122    // Variant settings
123    let dc_basenb_enabled = settings.dc_basenb_enabled;
124    let dc_basenb_fragment_enabled = settings.dc_basenb_fragment_enabled;
125    let utf8_base64_embed_enabled = settings.utf8_base64_embed_enabled;
126    let debug = settings.debug;
127
128    let mut out: Vec<u8> = Vec::new();
129
130    // Accumulate unmappables if dcBasenb variant is enabled.
131    let mut unmappables: Vec<u32> = Vec::new();
132    let mut found_any_unmappables = false;
133
134    // Escape handling
135    let mut escape_next = false;
136    let mut escape_this = false;
137
138    if debug {
139        log.debug(&format!("dca_to_utf8: input length {}", dc_array.len()));
140    }
141
142    let len = dc_array.len();
143    let mut i: usize = 0;
144
145    while i < len {
146        let raw_dc = dc_array
147            .get(i)
148            .copied()
149            .ok_or_else(|| anyhow!("Index out of bounds"))?;
150        let dc = DcChar::from_short(raw_dc);
151
152        // Manage escape flags
153        if escape_next {
154            escape_next = false;
155            escape_this = true;
156        }
157        if dc == DC_ESCAPE {
158            escape_next = true;
159        }
160
161        // Encapsulated UTF-8 handling (new structured block).
162        // A valid encapsulated sequence is:
163        //   DC_START_ENCAPSULATION_UTF8 (191),
164        //   0..N of is_dc_base64_encapsulation_character == true,
165        //   DC_END_ENCAPSULATION_UTF8 (192).
166        // If truncated (missing end marker) or invalid char encountered, we fallback by
167        // reprocessing that subsequence with utf8_base64_embed_enabled turned off.
168        if utf8_base64_embed_enabled
169            && !escape_this
170            && dc == DC_START_ENCAPSULATION_UTF8
171        {
172            #[cfg(debug_assertions)]
173            {
174                log.debug(&format!(
175                    "Found start of encapsulated UTF-8 sequence at index {i}"
176                ));
177            }
178            let start_index = i;
179            let mut j = i.saturating_add(1);
180            let mut truncated = true;
181
182            // Scan forward for a valid end marker, ensuring all characters in between are valid.
183            while j < len {
184                let cur_raw = dc_array
185                    .get(j)
186                    .copied()
187                    .ok_or_else(|| anyhow!("Index out of bounds"))?;
188                let cur = DcChar::from_short(cur_raw);
189                if cur == DC_END_ENCAPSULATION_UTF8 {
190                    truncated = false;
191                    break;
192                }
193                if !is_dc_base64_encapsulation_char(cur) {
194                    // Invalid character => treat as truncated (do not consume invalid char).
195                    truncated = true;
196                    break;
197                }
198                j = j.saturating_add(1);
199            }
200
201            if truncated {
202                // Determine slice to reprocess (excluding the invalid char, if any).
203                let end_exclusive = j.min(len);
204                #[expect(
205                    clippy::expect_used,
206                    reason = "start_index <= j and end_exclusive <= len is in bounds"
207                )]
208                let subseq = dc_array.get(start_index..end_exclusive).expect(
209                    "start_index <= j and end_exclusive <= len is in bounds",
210                );
211                if j >= len {
212                    log.warn(&format!(
213                        "Truncated encapsulated UTF-8 sequence at index {start_index} (missing end marker)"
214                    ));
215                } else {
216                    #[expect(
217                        clippy::expect_used,
218                        reason = "j < len checked by else branch"
219                    )]
220                    let char_dc = *dc_array
221                        .get(j)
222                        .expect("j < len checked by else branch");
223                    log.warn(&format!(
224                        "Invalid character {char_dc} inside encapsulated UTF-8 sequence starting at index {start_index} (treating as truncated)"
225                    ));
226                }
227
228                // Reprocess with embedding disabled so each Dc is handled normally (likely becomes replacement chars).
229                let mut retry_settings = settings.clone();
230                retry_settings.utf8_base64_embed_enabled = false;
231                let (retry_bytes, retry_log) =
232                    dca_to_utf8(subseq, &retry_settings)?;
233                log.merge(&retry_log);
234
235                // Flush pending basenb unmappables before emitting fallback bytes.
236                flush_unmappables(
237                    &mut out,
238                    &mut unmappables,
239                    &mut found_any_unmappables,
240                    true,
241                    dc_basenb_enabled,
242                    dc_basenb_fragment_enabled,
243                )?;
244
245                out.extend_from_slice(&retry_bytes);
246
247                // Advance to (but not past) the invalid char if there was one.
248                i = j;
249                continue;
250            } else {
251                // Valid sequence: dc_array[i] == start, dc_array[j] == end.
252                // Inner slice excludes start and end markers.
253                let inner = if j > i.saturating_add(1) {
254                    #[expect(
255                        clippy::expect_used,
256                        reason = "i < j < len established by marker search loop"
257                    )]
258                    dc_array
259                        .get(i.saturating_add(1)..j)
260                        .expect("i + 1 < j < len is in bounds")
261                } else {
262                    &[]
263                };
264
265                // Attempt decode.
266                match dc_encapsulated_raw_to_bytes(inner) {
267                    Ok(bytes) => {
268                        if debug {
269                            log.debug(&format!(
270                                "Decoded encapsulated UTF-8 sequence at {}..{} ({} inner dcs, {} bytes)",
271                                i,
272                                j,
273                                inner.len(),
274                                bytes.len()
275                            ));
276                        }
277
278                        // Flush pending unmappables before appending decoded payload.
279                        flush_unmappables(
280                            &mut out,
281                            &mut unmappables,
282                            &mut found_any_unmappables,
283                            true,
284                            dc_basenb_enabled,
285                            dc_basenb_fragment_enabled,
286                        )?;
287
288                        out.extend_from_slice(&bytes);
289                    }
290                    Err(e) => {
291                        // Fallback: reprocess entire sequence (including markers) with embedding disabled.
292                        #[expect(
293                            clippy::expect_used,
294                            reason = "markers i and j established in range (i <= j < len) by marker search loop"
295                        )]
296                        let subseq = dc_array
297                            .get(i..=j)
298                            .expect("markers i and j established in range");
299                        log.warn(&format!(
300                            "Failed to decode encapsulated UTF-8 sequence {subseq:?} at {i}..{j}: {e} (fallback to plain processing)"
301                        ));
302                        let mut retry_settings = settings.clone();
303                        retry_settings.utf8_base64_embed_enabled = false;
304                        let (retry_bytes, retry_log) =
305                            dca_to_utf8(subseq, &retry_settings)?;
306                        log.merge(&retry_log);
307
308                        flush_unmappables(
309                            &mut out,
310                            &mut unmappables,
311                            &mut found_any_unmappables,
312                            true,
313                            dc_basenb_enabled,
314                            dc_basenb_fragment_enabled,
315                        )?;
316                        out.extend_from_slice(&retry_bytes);
317                    }
318                }
319
320                // Advance past end marker.
321                i = j.saturating_add(1);
322                escape_this = false;
323                continue;
324            }
325        }
326
327        // Standard Dc mapping path (original logic preserved / reorganized).
328        let mut mapped: Vec<u8> = Vec::new();
329        let (dc_mapped, dc_log) = dc_to_format("utf8", raw_dc)?;
330        mapped.extend(dc_mapped);
331        log.merge(&dc_log);
332
333        if debug {
334            log.debug(&format!(
335                "dca_to_utf8: idx {i}, current_dc {raw_dc}, mapped {mapped:?}"
336            ));
337        }
338
339        // Unmappable? (empty mapped vector)
340        if mapped.is_empty() {
341            if dc_basenb_enabled {
342                unmappables.push(raw_dc);
343            } else {
344                // Reason for fallback: loop index i is u32-bounded in standard files, but fallback to 0 safely avoids panic if file index exceeds u32::MAX when logging warning.
345                log.export_warning(
346                    i.try_into().unwrap_or(0),
347                    &format!("Dc {raw_dc} has no UTF-8 mapping"),
348                );
349                if !settings.skip_unmappable {
350                    mapped.extend_from_slice(UTF8_REPLACEMENT_CHARACTER);
351                }
352            }
353        }
354
355        // If basenb enabled and boundary or got a mappable Dc, flush accumulated unmappables.
356        if dc_basenb_enabled && !mapped.is_empty() && !unmappables.is_empty() {
357            flush_unmappables(
358                &mut out,
359                &mut unmappables,
360                &mut found_any_unmappables,
361                false,
362                dc_basenb_enabled,
363                dc_basenb_fragment_enabled,
364            )?;
365        }
366
367        // Append mapped Dc (if any) to output after handling unmappables.
368        if !mapped.is_empty() {
369            out.extend(mapped);
370        }
371
372        if escape_this {
373            escape_this = false;
374        }
375
376        i = i.saturating_add(1);
377    }
378
379    // End-of-stream flush for unmappables.
380    flush_unmappables(
381        &mut out,
382        &mut unmappables,
383        &mut found_any_unmappables,
384        true,
385        dc_basenb_enabled,
386        dc_basenb_fragment_enabled,
387    )?;
388
389    // Close armored region if needed.
390    if dc_basenb_enabled && found_any_unmappables && !dc_basenb_fragment_enabled
391    {
392        out.extend(DC_BASENB_EMBEDDED_END_UUID_BYTES);
393    }
394
395    Ok((out, log))
396}
397
398/// Decode UTF-8 bytes to an internal Dc array, honoring dcBasenb embedding.
399/// Translation of original `dcaFromUtf8`.
400/// Should return an `Ok()` result for all inputs; `Err()` should only occur for internal errors (= bugs).
401pub fn dca_from_utf8(
402    utf8_bytes: &[u8],
403    settings: &UTF8FormatSettings,
404) -> Result<(Vec<u32>, FormatLog)> {
405    let mut log = FormatLog::default();
406    let dc_basenb_enabled = settings.dc_basenb_enabled;
407    let debug = settings.debug;
408
409    // Accumulate runs of un-mappable or invalid UTF-8, if set to preserve it
410    let mut unmappables: Vec<u8> = Vec::new();
411
412    // Buffer for result Dcs.
413    let mut result: Vec<u32> = Vec::new();
414
415    // Remaining unprocessed bytes (sliding window).
416    let mut remaining: &[u8] = utf8_bytes;
417
418    if debug {
419        log.debug(&format!(
420            "dca_from_utf8: input bytes {:?}, input length {}, dc_basenb_enabled={}",
421            utf8_bytes,
422            utf8_bytes.len(),
423            dc_basenb_enabled
424        ));
425    }
426
427    while !remaining.is_empty() {
428        if debug {
429            log.debug(&format!(
430                "dca_from_utf8: remaining bytes {:?}, input length {}, result {:?}, dc_basenb_enabled={}",
431                remaining,
432                remaining.len(),
433                result,
434                dc_basenb_enabled
435            ));
436        }
437
438        // If enabled, maintain state machine for entering/leaving DcBasenb region.
439        if dc_basenb_enabled {
440            // Dcbasenb is enabled, so process characters accordingly.
441            // Not currently inside a DcBasenb section -> look for START UUID.
442            let possible_basenb = if settings.dc_basenb_fragment_enabled {
443                let (first_char, possible_consumed) =
444                    first_char_of_utf8_string(remaining)?;
445                possible_consumed > 0 && is_basenb_char(&first_char)
446            } else {
447                remaining.starts_with(DC_BASENB_EMBEDDED_START.as_bytes())
448            };
449
450            if possible_basenb {
451                log.debug("Found possible DcBasenb section");
452
453                // Inside DcBasenb section -> look for end UUID: DC_BASENB_EMBEDDED_END
454                // Unless fragment decoding is enabled, in which case look for end of string or first non-dcbnb character
455                let end_marker = DC_BASENB_EMBEDDED_END.as_bytes();
456                let section_vec: Vec<u8>;
457                crate::log!(
458                    "Looking for end marker in remaining, {:?}",
459                    remaining
460                );
461
462                // Position of the end marker (non-fragment) or end of basenb run (fragment)
463                let mut end_pos: Option<usize> = None;
464
465                if settings.dc_basenb_fragment_enabled {
466                    let mut fragment_consumed = 0;
467                    let mut found = false;
468                    log!(
469                        "Fragment enabled, looking for end of range in {:?}",
470                        remaining
471                    );
472                    while fragment_consumed < remaining.len() {
473                        #[expect(
474                            clippy::expect_used,
475                            reason = "fragment_consumed < remaining.len() guaranteed by while loop"
476                        )]
477                        let rem_slice =
478                            remaining.get(fragment_consumed..).expect(
479                                "fragment_consumed < remaining.len() in loop",
480                            );
481                        log!("Consumed, remaining {:?}", rem_slice);
482                        let first_char = first_char_of_utf8_string(rem_slice);
483                        if first_char.is_err() {
484                            log!("Char errored, {:?}", first_char);
485                            break;
486                        }
487                        let (first_char, char_consumed) = first_char?;
488                        if !is_basenb_char(&first_char) {
489                            log!("Char is not basenb, {:?}", first_char);
490                            break;
491                        }
492                        fragment_consumed =
493                            fragment_consumed.saturating_add(char_consumed);
494                        found = true;
495                    }
496                    end_pos =
497                        if found { Some(fragment_consumed) } else { None };
498                } else {
499                    end_pos = remaining
500                        .windows(end_marker.len())
501                        .position(|window| window == end_marker);
502                }
503
504                if let Some(end_pos) = end_pos {
505                    // `end_pos` is the index where the end marker starts
506                    let section = if settings.dc_basenb_fragment_enabled {
507                        #[expect(
508                            clippy::expect_used,
509                            reason = "end_pos <= remaining.len() guaranteed by fragment scan"
510                        )]
511                        remaining.get(..end_pos).expect(
512                            "end_pos <= remaining.len() in fragment scan",
513                        )
514                    } else {
515                        // bytes after the start marker and before the end marker
516                        // Reason for fallback: 32..end_pos slices payload between 32-byte header and end_pos; fallback to empty slice safely handles truncated sections under 32 bytes without panic.
517                        remaining.get(32..end_pos).unwrap_or(&[])
518                    };
519                    #[cfg(debug_assertions)]
520                    log.debug(
521                        format!(
522                            "Found valid DcBasenb section: {:?} Fragment? {:?}",
523                            section, settings.dc_basenb_fragment_enabled
524                        )
525                        .as_str(),
526                    );
527                    section_vec = section.to_vec(); // copy into new Vec<u8>
528                } else {
529                    if !settings.dc_basenb_fragment_enabled {
530                        // End marker not found -- handle error or partial buffer
531                        log.warn(
532                            "An invalid base17b UTF8 input was encountered. Probably it was incorrectly truncated.",
533                        );
534                    }
535
536                    let section = if settings.dc_basenb_fragment_enabled {
537                        remaining
538                    } else {
539                        // Reason for fallback: 33.. slices payload after 33-byte prefix when end marker missing; fallback to empty slice safely handles truncated streams under 33 bytes without panic.
540                        remaining.get(33..).unwrap_or(&[]) // or just "remaining" as above?
541                    };
542                    section_vec = section.to_vec();
543                }
544
545                // Decode and append collected DcBasenb chars.
546                if !section_vec.is_empty() {
547                    decode_and_append_basenb_run(
548                        &section_vec,
549                        &mut result,
550                        &mut log,
551                        utf8_bytes.len().saturating_sub(remaining.len()),
552                        settings,
553                    )?;
554                }
555                #[cfg(debug_assertions)]
556                log.debug(
557                    format!("Finished decoding DcBasenb run: {result:?}")
558                        .as_str(),
559                );
560
561                if let Some(end_pos) = end_pos
562                    && !settings.dc_basenb_fragment_enabled
563                {
564                    // Now update `remaining` to point after the end marker
565                    // Reason for fallback: advancing past end marker may reach or exceed stream length; fallback to empty slice safely terminates sliding window loop.
566                    remaining = remaining
567                        .get(end_pos.saturating_add(end_marker.len())..)
568                        .unwrap_or(&[]);
569                    continue;
570                }
571                remaining = &[];
572            }
573        }
574
575        if remaining.is_empty() {
576            log.debug("No more input found.");
577            break;
578        }
579
580        // Extract next UTF-8 character
581        let (ch_bytes, (consumed, valid)) =
582            first_char_of_utf8_string_lossless(remaining)?;
583        let dc = dc_from_format(
584            "unicode",
585            if valid {
586                &ch_bytes
587            } else {
588                // This is only be used when base64 embedding is turned off
589                UTF8_REPLACEMENT_CHARACTER
590            },
591        );
592
593        if debug {
594            log.debug(&format!("dca_from_utf8: converting bytes {ch_bytes:?}"));
595        }
596
597        if dc.is_err() {
598            if debug {
599                // borrow the Ok(Vec) so we don't move it out of `dc`
600                log.debug(&format!("debug {ch_bytes:?} to err"));
601            }
602            // Reason for fallback: dc.is_err() check guarantees dc is Err variant; map_or_else formats error chain with fallback string if err ref is empty.
603            let err_msg = dc.as_ref().err().map_or_else(
604                || "Unknown error".to_string(),
605                |e| {
606                    e.chain()
607                        .map(std::string::ToString::to_string)
608                        .collect::<Vec<_>>()
609                        .join(": ")
610                },
611            );
612            log.error(&format!(
613                "Failed to import UTF-8 character at offset {consumed}: {err_msg}"
614            ));
615            bail!("Internal error trying to import UTF-8 character {log:?}");
616        } else {
617            let (dc, dc_log) = dc?;
618            let dc_first = bail_if_none!(dc.first().copied());
619            if dc.len() > 1 {
620                // It would be conceivable to if the UTF-8 input were being
621                // encapsulated per-character, but since this is in a function
622                // with access to the whole string, it likely produces a
623                // shorter output to accumulate as long a run of un-mappable
624                // UTF-8 as possible and encode it as a group. (An alternative
625                // would be to encapsulate each failed character or byte
626                // individually, which may produce a file that was larger but
627                // more resilient to corruption.)
628                log.error(&format!(
629                    "Multiple Dcs returned for UTF-8 character at offset {consumed}: {ch_bytes:?} -> {dc:?}"
630                ));
631                bail!("Unexpectedly received multiple Dcs for one UTF-8 input");
632            }
633            if dc_first == 207 {
634                log.warn(&format!(
635                    "Unmapped UTF-8 character at offset {consumed}: {ch_bytes:?}"
636                ));
637            }
638            if !valid {
639                log.warn(&format!(
640                    "Invalid UTF-8 at offset {consumed}: {ch_bytes:?}"
641                ));
642            }
643
644            // If embedding is enabled, we delay output of unmappables by accumulating them
645            let mut skip_pushing_this = false;
646            if settings.utf8_base64_embed_enabled {
647                if dc_first == 207 || !valid {
648                    // append ch_bytes to unmappables
649                    unmappables.extend_from_slice(&ch_bytes);
650                    skip_pushing_this = true;
651                } else if !unmappables.is_empty() {
652                    result.extend_from_slice(&bytes_as_dc_encapsulated_utf8(
653                        unmappables.as_slice(),
654                    )?);
655                    unmappables.clear();
656                }
657            }
658
659            if debug {
660                // borrow the Ok(Vec) so we don't move it out of `dc`
661                log.debug(&format!(
662                    "dca_from_utf8: converted bytes {ch_bytes:?} to dc {dc:?}"
663                ));
664            }
665
666            if !skip_pushing_this {
667                result.push(dc_first);
668            }
669            log.merge(&dc_log);
670        }
671
672        // Advance remaining window by consumed bytes
673        #[expect(
674            clippy::expect_used,
675            reason = "consumed <= remaining.len() guaranteed by UTF-8 char decode"
676        )]
677        let next_remaining = remaining.get(consumed..).expect(
678            "consumed <= remaining.len() guaranteed by UTF-8 char decode",
679        );
680        remaining = next_remaining;
681    }
682
683    if settings.utf8_base64_embed_enabled && !unmappables.is_empty() {
684        result.extend_from_slice(&bytes_as_dc_encapsulated_utf8(
685            unmappables.as_slice(),
686        )?);
687        unmappables.clear();
688    }
689
690    Ok((result, log))
691}
692
693/// Helper: decode a collected base17b run into pack32 UTF-8 bytes,
694/// then iterate through those bytes one UTF-8 codepoint at a time,
695/// unpacking each to an internal Dc and appending to result.
696fn decode_and_append_basenb_run(
697    collected: &[u8],
698    out: &mut Vec<u32>,
699    log: &mut FormatLog,
700    offset: usize,
701    settings: &UTF8FormatSettings,
702) -> Result<()> {
703    let mut all_consumed = 0;
704    let mut basenb_run: Vec<u8> = Vec::new();
705
706    while all_consumed < collected.len() {
707        crate::debug!(&format!(
708            "Decoding basenb run: collected {collected:?}, all_consumed {all_consumed}, basenb_run {basenb_run:?}"
709        ));
710
711        let (ch, consumed) = first_char_of_utf8_string(bail_if_none!(
712            collected.get(all_consumed..)
713        ))?;
714
715        if is_basenb_char(&ch) {
716            basenb_run.extend_from_slice(&ch);
717        } else {
718            // UTF-8 character embedded in a basenb run
719            if !basenb_run.is_empty() {
720                let decoded = byte_array_from_basenb_17_utf8(&basenb_run)?;
721                if excep_arr(&decoded)? {
722                    log.import_warning(
723                        u64::try_from(offset)?,
724                        "Found exceptions in decoded basenb 17 run around this offset",
725                    );
726                }
727                let pack32ed_string = String::from_utf8(decoded)?;
728                for ch in pack32ed_string.chars() {
729                    out.push(unpack32(&ch.as_utf8_bytes())?);
730                }
731                basenb_run.clear();
732            }
733
734            // Handle the non-basenb UTF-8 char by delegating to dca_from_utf8
735            let (from_utf8, char_log) = dca_from_utf8(&ch, settings)?;
736            log.merge(&char_log);
737            out.extend_from_slice(&from_utf8);
738        }
739
740        all_consumed = all_consumed.saturating_add(consumed);
741    }
742
743    if !basenb_run.is_empty() {
744        let decoded = byte_array_from_basenb_17_utf8(&basenb_run)?;
745        if excep_arr(&decoded)? {
746            log.import_warning(
747                u64::try_from(offset)?,
748                "Found exceptions in decoded basenb 17 run around this offset",
749            );
750        }
751        #[cfg(debug_assertions)]
752        crate::debug!("Decoded basenb run to {:?}", &decoded);
753
754        // Preserve original semantics: lossy string with warning/error if not valid UTF-8.
755        let pack32ed_string_not_lossy = String::from_utf8(decoded.clone());
756        let pack32ed_string = String::from_utf8_lossy(&decoded);
757        if let Err(err) = pack32ed_string_not_lossy {
758            let offset = u64::try_from(offset)?;
759            let message = &format!(
760                "Failed to decode basenb 17 run to UTF-8 string: {err}"
761            );
762            if settings.dc_basenb_fragment_strict {
763                log.import_error(offset, message);
764            } else {
765                log.import_warning(offset, message);
766            }
767        }
768        for ch in pack32ed_string.chars() {
769            out.push(unpack32(&ch.as_utf8_bytes())?);
770        }
771        basenb_run.clear();
772    }
773
774    Ok(())
775}
776
777/// Flush accumulated unmappables (armoring logic).
778/// Preserves original logic, including redundant checks and start/end marker emission semantics.
779fn flush_unmappables(
780    out: &mut Vec<u8>,
781    unmappables: &mut Vec<u32>,
782    found_any_unmappables: &mut bool,
783    force: bool,
784    dc_basenb_enabled: bool,
785    dc_basenb_fragment_enabled: bool,
786) -> Result<()> {
787    if dc_basenb_enabled
788        && (force || !unmappables.is_empty())
789        && !unmappables.is_empty()
790    {
791        if !*found_any_unmappables && !dc_basenb_fragment_enabled {
792            out.extend(DC_BASENB_EMBEDDED_START_BYTES);
793        }
794        *found_any_unmappables = true;
795
796        // Encode each unmappable Dc individually
797        for &dc in unmappables.iter() {
798            let packed = pack32(dc)?;
799            let encoded = byte_array_to_basenb_17_utf8(&packed)?;
800            out.extend(encoded);
801        }
802        unmappables.clear();
803    }
804    Ok(())
805}
806
807#[cfg(test)]
808#[allow(
809    clippy::panic,
810    clippy::expect_used,
811    clippy::unwrap_used,
812    clippy::unwrap_in_result,
813    clippy::panic_in_result_fn,
814    clippy::indexing_slicing,
815    clippy::arithmetic_side_effects,
816    reason = "Standard repository test boilerplate"
817)]
818mod tests {
819    use crate::utilities::assert_vec_u32_eq;
820    use ctb_formats_utilities::{
821        assert_vec_u8_ok_eq_no_errors, assert_vec_u8_ok_eq_no_warnings,
822        assert_vec_u32_ok_eq_no_errors, assert_vec_u32_ok_eq_no_warnings,
823    };
824
825    use super::*;
826
827    const SETTINGS: UTF8FormatSettings =
828        <UTF8FormatSettings as ConstDefault>::DEFAULT;
829
830    #[crate::ctb_test]
831    fn test_decode_and_append_basenb_run() {
832        let expected_uuid = DC_BASENB_EMBEDDED_START_BYTES.to_vec();
833        let remainder = "\u{F800}".as_bytes().to_vec();
834        let input = [expected_uuid, remainder].concat();
835        let mut out = Vec::new();
836        let mut log = FormatLog::default();
837        let offset = 0;
838        let settings = &SETTINGS;
839
840        decode_and_append_basenb_run(
841            &input, &mut out, &mut log, offset, settings,
842        )
843        .expect("Failed to decode and append basenb run");
844
845        // this is just noise because it was a UUID
846        assert_vec_u32_eq(
847            &[
848                65533, 46, 65533, 96, 25, 65533, 74, 0, 65533, 74, 118, 58, 52,
849                69, 65533, 111,
850            ],
851            &out,
852        );
853    }
854
855    #[crate::ctb_test]
856    fn dca_roundtrip_simple_utf8_without_basenb() {
857        let dcs = assert_vec_u32_ok_eq_no_warnings(
858            &[],
859            dca_from_utf8(&[], &SETTINGS),
860        );
861
862        assert_vec_u8_ok_eq_no_warnings(&[], dca_to_utf8(&dcs, &SETTINGS));
863
864        // UTF-8 base-64 embedding enabled
865        // 'A', U+0082 (empty mapping), 'É' (no mapping), (invalid byte), U+2029 (Dc 295)
866        let input = [0x41, 0xC2, 0x82, 0xC3, 0x89, 0xFF, 0xE2, 0x80, 0xA9];
867        // Unmappable run will be c2 82 c3 89 ff, base64 woLDif8=
868        // 48 40 11 3 34 31 60 =
869        let (dcs, log) = assert_vec_u32_ok_eq_no_errors(
870            &[50, 191, 175, 167, 138, 130, 161, 158, 187, 195, 192, 295],
871            dca_from_utf8(&input, &SETTINGS),
872        );
873        assert!(log.has_warnings());
874
875        assert_vec_u8_ok_eq_no_warnings(&input, dca_to_utf8(&dcs, &SETTINGS));
876
877        // Truncated base-64 embedding
878        let (_utf8, log) = assert_vec_u8_ok_eq_no_errors(
879            &[
880                0x41, 0xEF, 0xBF, 0xBD, 0xEF, 0xBF, 0xBD, 0xEF, 0xBF, 0xBD,
881                0xEF, 0xBF, 0xBD,
882            ],
883            dca_to_utf8(&[50, 191, 175, 167, 138], &SETTINGS),
884        );
885        assert!(log.has_warnings());
886
887        // UTF-8 base-64 embedding disabled. Should not crash on unmappable.
888        let (_utf8, log) = assert_vec_u8_ok_eq_no_errors(
889            &[0xEF, 0xBF, 0xBD],
890            dca_to_utf8(
891                &[289],
892                &UTF8FormatSettings {
893                    utf8_base64_embed_enabled: false,
894                    ..Default::default()
895                },
896            ),
897        );
898        assert!(log.has_warnings());
899
900        // UTF-8 base-64 embedding disabled
901        // 'A', U+0082 (empty mapping), 'É' (no mapping), (invalid byte), U+2029 (Dc 295)
902        let input = [0x41, 0xC2, 0x82, 0xC3, 0x89, 0xFF, 0xE2, 0x80, 0xA9];
903        let (_dcs, log) = assert_vec_u32_ok_eq_no_errors(
904            &[50, 207, 207, 206, 295],
905            dca_from_utf8(
906                &input,
907                &UTF8FormatSettings {
908                    utf8_base64_embed_enabled: false,
909                    ..Default::default()
910                },
911            ),
912        );
913        assert!(log.has_warnings());
914
915        // With Dc and Unicode replacement characters:
916        // 'A', U+FFFD, U+FFFD, U+FFFD, U+2029 (Dc 295)
917        let expected = [
918            0x41, 0xEF, 0xBF, 0xBD, 0xEF, 0xBF, 0xBD, 0xEF, 0xBF, 0xBD, 0xE2,
919            0x80, 0xA9,
920        ];
921        assert_vec_u8_ok_eq_no_warnings(
922            &expected,
923            dca_to_utf8(&[50, 207, 207, 206, 295], &SETTINGS),
924        );
925    }
926}