ctb_formats_dctf/
codec.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//! Pure `UTF-8e-128` buffer and slice encoding/decoding routines.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29// FIXME: Can this be simplified by leaning on Rust's native UTF-8 en/decoding?
30
31/// Encodes a Unicode scalar value or an extended (> U+10FFFF) 128‑bit integer
32/// using the UTF‑8e‑128 scheme.
33///
34/// For values <= `0x10_FFFF` this produces standard UTF‑8 (1–4 bytes).
35/// For larger values it emits:
36///   0:  0xFF
37///   1:  10LLLLLL   (1 <= L <= 22) number of payload continuation bytes
38///   2+: L payload continuation bytes 10bbbbbb ... (big‑endian 6‑bit groups)
39/// Returns the number of bytes written.
40///
41/// Panics if the provided buffer is too small (needs up to 24 bytes).
42#[expect(
43    clippy::expect_used,
44    reason = "Integer casts and array indexing are provably infallible due to preceding range checks and fixed array bounds"
45)]
46pub fn encode_utf_8e_128_buf(buf: &mut [u8], codepoint: u128) -> usize {
47    // Standard UTF-8 path for values within Unicode range
48
49    // (Optional) Reject surrogate range if you only want Unicode scalar values.
50    // if (0xD800..=0xDFFF).contains(&cp) {
51    //     // An alternative here might be to assign them higher Dcs, or
52    //     // since this encoding can hold 132 bits, to stuff them into that
53    //     // unused space
54    //     panic!("Cannot encode surrogate as scalar");
55    // }
56    if codepoint <= 0x10FFFF {
57        let cp = u32::try_from(codepoint)
58            .expect("codepoint <= 0x10FFFF fits in u32");
59        if cp <= 0x7F {
60            if let Some(b) = buf.get_mut(0) {
61                *b = u8::try_from(cp).expect("cp <= 0x7F fits in u8");
62            }
63            return 1;
64        } else if cp <= 0x7FF {
65            if buf.len() >= 2 {
66                if let Some(b) = buf.get_mut(0) {
67                    *b = 0xC0
68                        | u8::try_from(cp >> 6)
69                            .expect("cp >> 6 for cp <= 0x7FF is <= 31");
70                }
71                if let Some(b) = buf.get_mut(1) {
72                    *b = 0x80
73                        | u8::try_from(cp & 0x3F).expect("cp & 0x3F is <= 63");
74                }
75            }
76            return 2;
77        } else if cp <= 0xFFFF {
78            if buf.len() >= 3 {
79                if let Some(b) = buf.get_mut(0) {
80                    *b = 0xE0
81                        | u8::try_from(cp >> 12)
82                            .expect("cp >> 12 for cp <= 0xFFFF is <= 15");
83                }
84                if let Some(b) = buf.get_mut(1) {
85                    *b = 0x80
86                        | u8::try_from((cp >> 6) & 0x3F)
87                            .expect("shifted mask is <= 63");
88                }
89                if let Some(b) = buf.get_mut(2) {
90                    *b = 0x80
91                        | u8::try_from(cp & 0x3F).expect("cp & 0x3F is <= 63");
92                }
93            }
94            return 3;
95        }
96        if buf.len() >= 4 {
97            if let Some(b) = buf.get_mut(0) {
98                *b = 0xF0
99                    | u8::try_from(cp >> 18)
100                        .expect("cp >> 18 for cp <= 0x10FFFF is <= 4");
101            }
102            if let Some(b) = buf.get_mut(1) {
103                *b = 0x80
104                    | u8::try_from((cp >> 12) & 0x3F)
105                        .expect("shifted mask is <= 63");
106            }
107            if let Some(b) = buf.get_mut(2) {
108                *b = 0x80
109                    | u8::try_from((cp >> 6) & 0x3F)
110                        .expect("shifted mask is <= 63");
111            }
112            if let Some(b) = buf.get_mut(3) {
113                *b =
114                    0x80 | u8::try_from(cp & 0x3F).expect("cp & 0x3F is <= 63");
115            }
116        }
117        return 4;
118    }
119
120    // Extended form
121    // Determine bit length
122    let leading_zeros = usize::try_from(codepoint.leading_zeros())
123        .expect("u32 leading_zeros (0..=128) fits in usize");
124    let bits = 128usize.saturating_sub(leading_zeros);
125    let mut l = bits.div_ceil(6); // minimal number of 6-bit groups
126    if l == 0 {
127        l = 1;
128    }
129    assert!(l <= 22, "Value requires more than 132 bits?");
130
131    assert!(
132        buf.len() >= 2usize.saturating_add(l),
133        "Buffer too small for extended encoding"
134    );
135
136    // Extract groups big-endian: groups[0] is first (most significant) group
137    let mut groups = [0u8; 22];
138    {
139        let mut tmp = codepoint;
140        for i in 0..l {
141            let idx = l.saturating_sub(1).saturating_sub(i);
142            if let Some(g) = groups.get_mut(idx) {
143                *g = u8::try_from(tmp & 0x3F).expect("tmp & 0x3F is <= 63");
144            }
145            tmp >>= 6;
146        }
147        debug_assert!(tmp == 0);
148    }
149
150    // Canonical rule: first payload group must be non-zero (value > 0)
151    debug_assert!(
152        groups.first().copied().expect("groups array has length 22") != 0
153    );
154
155    if let Some(b) = buf.get_mut(0) {
156        *b = 0xFF;
157    }
158    if let Some(b) = buf.get_mut(1) {
159        *b = 0x80 | u8::try_from(l).expect("l <= 22 fits in u8");
160    }
161
162    for i in 0..l {
163        let dest_idx = 2usize.saturating_add(i);
164        if let (Some(b), Some(&g)) = (buf.get_mut(dest_idx), groups.get(i)) {
165            *b = 0x80 | g;
166        }
167    }
168
169    // Additional canonical check for 128-bit max if l == 22:
170    // top 4 bits of first payload group must be zero (they are the unused padding bits).
171    if l == 22 {
172        debug_assert!(
173            (groups.first().copied().expect("groups array has length 22")
174                & 0x3C)
175                == 0,
176            "Non-zero padding bits in 22-byte encoding"
177        );
178    }
179
180    2usize.saturating_add(l)
181}
182
183/// Decodes one UTF‑8 / UTF‑8e‑128 codepoint from the provided byte slice.
184/// On success returns Some((value, `length_consumed`)), else None.
185/// Enforces canonical (no overlong) encodings for both standard and extended forms.
186#[expect(
187    clippy::expect_used,
188    clippy::unwrap_in_result,
189    reason = "Fixed-size 22-element groups array guarantees first element presence and buf slice fits encoded length"
190)]
191pub fn decode_utf_8e_128_buf(bytes: &[u8]) -> Option<(u128, usize)> {
192    let first = *bytes.first()?;
193    if first == 0xFF {
194        // Extended form
195        let h = *bytes.get(1)?;
196        if (h & 0xC0) != 0x80 {
197            return None;
198        }
199        let l = usize::from(h & 0x3F);
200        if l == 0 || l > 22 {
201            return None;
202        }
203        if bytes.len() < l.saturating_add(2) {
204            return None;
205        }
206
207        // Gather groups
208        let mut groups = [0u8; 22];
209        for i in 0..l {
210            let b = *bytes.get(i.saturating_add(2))?;
211            if (b & 0xC0) != 0x80 {
212                return None;
213            }
214            if let Some(g) = groups.get_mut(i) {
215                *g = b & 0x3F;
216            }
217        }
218
219        // Canonical: first group not zero
220        if groups.first().copied().expect("groups array has length 22") == 0 {
221            return None;
222        }
223
224        // If l == 22, top 4 bits of first group (padding) must be zero.
225        if l == 22
226            && (groups.first().copied().expect("groups array has length 22")
227                & 0x3C)
228                != 0
229        {
230            return None;
231        }
232
233        // Reconstruct value pruning leading padding bits if total bits > 128
234        let total_bits = l.saturating_mul(6);
235        let extra = total_bits.saturating_sub(128); // 0..=4
236        if extra > 4 {
237            return None; // should not happen with l<=22 and u128 output
238        }
239
240        let g0 = groups.first().copied().expect("groups array has length 22");
241        // Ensure the extra (padding) high bits are zero
242        if extra > 0 && (g0 >> (6usize.saturating_sub(extra))) != 0 {
243            return None;
244        }
245
246        let mut value: u128 = 0;
247        if extra < 6 {
248            // Take lower (6 - extra) bits of first group
249            let first_payload_bits = g0
250                & ((1u8 << (6usize.saturating_sub(extra))).saturating_sub(1));
251            value = u128::from(first_payload_bits);
252        }
253        for i in 1..l {
254            if let Some(&g) = groups.get(i) {
255                value = (value << 6) | u128::from(g);
256            }
257        }
258
259        // Must not overlap with standard range
260        if value <= 0x10FFFF {
261            return None;
262        }
263
264        return Some((value, l.saturating_add(2)));
265    }
266
267    // Standard UTF-8 decoding
268    if first < 0x80 {
269        return Some((u128::from(first), 1));
270    }
271
272    // Determine expected length and initial mask / prefix
273    let (len, min_val, max_val_mask) = if (first & 0xE0) == 0xC0 {
274        // 110xxxxx
275        (2usize, 0x80u32, 0x1F)
276    } else if (first & 0xF0) == 0xE0 {
277        // 1110xxxx
278        (3usize, 0x800u32, 0x0F)
279    } else if (first & 0xF8) == 0xF0 {
280        // 11110xxx
281        (4usize, 0x10000u32, 0x07)
282    } else {
283        return None;
284    };
285
286    if bytes.len() < len {
287        return None;
288    }
289
290    let mut val: u32 = u32::from(first & max_val_mask);
291    for i in 1..len {
292        let b = *bytes.get(i)?;
293        if (b & 0xC0) != 0x80 {
294            return None;
295        }
296        val = (val << 6) | u32::from(b & 0x3F);
297    }
298
299    // Overlong check
300    if val < min_val {
301        return None;
302    }
303
304    // Unicode max (U+10FFFF)
305    if val > 0x10FFFF {
306        return None;
307    }
308
309    // Optional: reject surrogate range for scalar value canonicality.
310    // if (0xD800..=0xDFFF).contains(&val) {
311    //     return None;
312    // }
313
314    Some((u128::from(val), len))
315}
316
317/// Generalized UTF-8 encoding for u128.
318/// Returns a `Vec<u8>` containing the encoded bytes.
319#[expect(
320    clippy::expect_used,
321    reason = "encode_utf_8e_128_buf returns length <= 24 which fits in 24-byte buf"
322)]
323pub fn encode_utf_8e_128(codepoint: u128) -> Vec<u8> {
324    let mut buf = [0u8; 24];
325    let encoded_len = encode_utf_8e_128_buf(&mut buf, codepoint);
326    buf.get(..encoded_len)
327        .expect("encoded_len <= 24 fits in buf")
328        .to_vec()
329}
330
331/// Decodes one generalized UTF-8 codepoint from bytes.
332/// Returns Some((value, `length_consumed`)), or the replacement character on error.
333#[must_use]
334pub fn decode_utf_8e_128(bytes: &[u8]) -> Option<(u128, usize)> {
335    if bytes.is_empty() {
336        return None;
337    }
338
339    if let Some(x) = decode_utf_8e_128_buf(bytes) {
340        Some(x)
341    } else {
342        // Reason for fallback: truncated prefix at EOF consumes remaining bytes as one U+FFFD
343        // when determine_utf_8e_128_error_len returns None for lossy decoding.
344        let err_len =
345            determine_utf_8e_128_error_len(bytes).unwrap_or(bytes.len());
346        Some((0xFFFD, err_len))
347    }
348}
349
350/// Returns the encoded byte length of `codepoint` in legacy `UTF-8e-128` (`DcUtf`, `f89`).
351#[must_use]
352#[expect(
353    clippy::expect_used,
354    reason = "u32 leading_zeros (0..=128) always fits in usize"
355)]
356pub fn len_utf_8e_128(codepoint: u128) -> usize {
357    if codepoint <= 0x7F {
358        1
359    } else if codepoint <= 0x7FF {
360        2
361    } else if codepoint <= 0xFFFF {
362        3
363    } else if codepoint <= 0x10_FFFF {
364        4
365    } else {
366        let leading_zeros = usize::try_from(codepoint.leading_zeros())
367            .expect("u32 leading_zeros fits in usize");
368        let bits = 128usize.saturating_sub(leading_zeros);
369        let l = bits.div_ceil(6).max(1);
370        2usize.saturating_add(l)
371    }
372}
373
374/// Computes the maximal-subpart error length for an invalid or incomplete legacy
375/// `UTF-8e-128` (`DcUtf`, `f89`) byte slice.
376///
377/// Returns `Some(n)` (`n >= 1`) when `slice[..n]` is the longest initial subsequence
378/// that can prefix a canonical `DcUtf` sequence (or `Some(1)` if `slice[0]` cannot
379/// start any canonical sequence), or `None` when the entire `slice` is a valid
380/// incomplete prefix of a canonical `DcUtf` sequence (truncated at the end of `slice`).
381#[must_use]
382pub fn determine_utf_8e_128_error_len(slice: &[u8]) -> Option<usize> {
383    let first = *slice.first()?;
384    if first < 0x80 {
385        return Some(1);
386    }
387    if first < 0xC2 || (0xF5..=0xFE).contains(&first) {
388        return Some(1);
389    }
390    if first == 0xFF {
391        let Some(&b1) = slice.get(1) else {
392            return None;
393        };
394        if !(0x84..=0x96).contains(&b1) {
395            return Some(1);
396        }
397        let l = usize::from(b1 & 0x3F);
398        let expected_len = 2usize.saturating_add(l);
399        for i in 2..expected_len {
400            let Some(&b) = slice.get(i) else {
401                return None;
402            };
403            if (b & 0xC0) != 0x80 {
404                return Some(i);
405            }
406            if i == 2 {
407                if l == 4 && b < 0x84 {
408                    return Some(2);
409                }
410                if l == 22 && !(0x81..=0x83).contains(&b) {
411                    return Some(2);
412                }
413                if (5..=21).contains(&l) && b < 0x81 {
414                    return Some(2);
415                }
416            } else if i == 3
417                && l == 4
418                && slice.get(2).copied() == Some(0x84)
419                && b < 0x90
420            {
421                return Some(3);
422            }
423        }
424        return Some(expected_len);
425    }
426
427    let (expected_len, min_b1, max_b1) = if first <= 0xDF {
428        (2usize, 0x80u8, 0xBFu8)
429    } else if first == 0xE0 {
430        (3usize, 0xA0u8, 0xBFu8)
431    } else if first <= 0xEF {
432        (3usize, 0x80u8, 0xBFu8)
433    } else if first == 0xF0 {
434        (4usize, 0x90u8, 0xBFu8)
435    } else if first <= 0xF3 {
436        (4usize, 0x80u8, 0xBFu8)
437    } else {
438        // first == 0xF4
439        (4usize, 0x80u8, 0x8Fu8)
440    };
441
442    for i in 1..expected_len {
443        let Some(&b) = slice.get(i) else {
444            return None;
445        };
446        let (lo, hi) = if i == 1 {
447            (min_b1, max_b1)
448        } else {
449            (0x80u8, 0xBFu8)
450        };
451        if b < lo || b > hi {
452            return Some(i);
453        }
454    }
455    Some(expected_len)
456}
457
458/// Maximum byte length of a `DcTF` (`.dctf`, `f641`) character sequence (23 bytes for 128-bit values).
459pub const MAX_DCTF_LEN: usize = 23;
460
461/// Returns the encoded byte length of `codepoint` in `DcTF` (`.dctf`, `f641`).
462#[must_use]
463#[expect(
464    clippy::expect_used,
465    reason = "u32 leading_zeros (0..=128) always fits in usize"
466)]
467pub fn len_dctf(codepoint: u128) -> usize {
468    if codepoint <= 0x7F {
469        1
470    } else if codepoint <= 0x7FF {
471        2
472    } else if codepoint <= 0xFFFF {
473        3
474    } else if codepoint <= 0x1F_FFFF {
475        4
476    } else if codepoint <= 0x3FF_FFFF {
477        5
478    } else if codepoint <= 0x7FFF_FFFF {
479        6
480    } else if codepoint <= 0xF_FFFF_FFFF {
481        7
482    } else {
483        let leading_zeros = usize::try_from(codepoint.leading_zeros())
484            .expect("u32 leading_zeros fits in usize");
485        let bits = 128usize.saturating_sub(leading_zeros);
486        let k = bits.saturating_sub(38).div_ceil(6);
487        8usize.saturating_add(k)
488    }
489}
490
491/// Encodes a 128-bit Document Character / integer value using the `DcTF` (`.dctf`, `f641`) scheme.
492///
493/// Tier layout:
494/// - 1B (`0x00..=0x7F`): `0..=0x7F` (7 bits)
495/// - 2B (`0xC2..=0xDF` + 1 cont.): `0x80..=0x7FF` (11 bits)
496/// - 3B (`0xE0..=0xEF` + 2 cont.): `0x800..=0xFFFF` (16 bits, including surrogates `0xD800..=0xDFFF`)
497/// - 4B (`0xF0..=0xF7` + 3 cont.): `0x1_0000..=0x1F_FFFF` (21 bits)
498/// - 5B (`0xF8..=0xFB` + 4 cont.): `0x20_0000..=0x3FF_FFFF` (26 bits)
499/// - 6B (`0xFC..=0xFD` + 5 cont.): `0x400_0000..=0x7FFF_FFFF` (31 bits)
500/// - 7B (`0xFE` + 6 cont.): `0x8000_0000..=0xF_FFFF_FFFF` (36 bits)
501/// - `8 + k` B (`0 <= k <= 15`): `0xFF`, `10_kkkk_bb`, followed by `k + 6` continuation bytes (`38 + 6k` bits)
502///
503/// Returns the number of bytes written (1..=23).
504/// Panics if `buf` is smaller than the required encoded length.
505#[expect(
506    clippy::expect_used,
507    reason = "Bitmask and range-checked shifts guarantee infallible u8/usize conversions"
508)]
509pub fn encode_dctf_buf(buf: &mut [u8], codepoint: u128) -> usize {
510    if codepoint <= 0x7F {
511        assert!(!buf.is_empty(), "Buffer too small for 1-byte DcTF encoding");
512        if let Some(b) = buf.get_mut(0) {
513            *b = u8::try_from(codepoint).expect("<= 0x7F fits in u8");
514        }
515        return 1;
516    }
517
518    if codepoint <= 0xF_FFFF_FFFF {
519        let (len, lead_prefix): (usize, u8) = if codepoint <= 0x7FF {
520            (2, 0xC0)
521        } else if codepoint <= 0xFFFF {
522            (3, 0xE0)
523        } else if codepoint <= 0x1F_FFFF {
524            (4, 0xF0)
525        } else if codepoint <= 0x3FF_FFFF {
526            (5, 0xF8)
527        } else if codepoint <= 0x7FFF_FFFF {
528            (6, 0xFC)
529        } else {
530            (7, 0xFE)
531        };
532        assert!(
533            buf.len() >= len,
534            "Buffer too small for {len}-byte DcTF encoding"
535        );
536        let cont_count = len.saturating_sub(1);
537        let top_shift = cont_count.saturating_mul(6);
538        if let Some(b0) = buf.get_mut(0) {
539            *b0 = lead_prefix
540                | u8::try_from(codepoint >> top_shift)
541                    .expect("top bits fit in lead byte payload");
542        }
543        for i in 0..cont_count {
544            let shift = cont_count
545                .saturating_sub(1)
546                .saturating_sub(i)
547                .saturating_mul(6);
548            if let Some(b) = buf.get_mut(1usize.saturating_add(i)) {
549                *b = 0x80
550                    | u8::try_from((codepoint >> shift) & 0x3F)
551                        .expect("masked 6-bit group fits in u8");
552            }
553        }
554        return len;
555    }
556
557    // Extended 0xFF tiers (k = 0..=15, total length 8..=23)
558    let leading_zeros = usize::try_from(codepoint.leading_zeros())
559        .expect("u32 leading_zeros fits in usize");
560    let bits = 128usize.saturating_sub(leading_zeros);
561    let k = bits.saturating_sub(38).div_ceil(6);
562    debug_assert!(k <= 15);
563    let cont_count = k.saturating_add(6);
564    let total_len = k.saturating_add(8);
565    assert!(
566        buf.len() >= total_len,
567        "Buffer too small for {total_len}-byte extended DcTF encoding"
568    );
569
570    let top_shift = cont_count.saturating_mul(6);
571    let top_2 = if top_shift < 128 {
572        u8::try_from((codepoint >> top_shift) & 0x03)
573            .expect("2-bit value fits in u8")
574    } else {
575        0
576    };
577    let k_u8 = u8::try_from(k).expect("k <= 15 fits in u8");
578    if let Some(b0) = buf.get_mut(0) {
579        *b0 = 0xFF;
580    }
581    if let Some(b1) = buf.get_mut(1) {
582        *b1 = 0x80 | (k_u8 << 2) | top_2;
583    }
584    for i in 0..cont_count {
585        let shift = cont_count
586            .saturating_sub(1)
587            .saturating_sub(i)
588            .saturating_mul(6);
589        if let Some(b) = buf.get_mut(2usize.saturating_add(i)) {
590            *b = 0x80
591                | u8::try_from((codepoint >> shift) & 0x3F)
592                    .expect("masked 6-bit group fits in u8");
593        }
594    }
595    total_len
596}
597
598/// Decodes one `DcTF` (`.dctf`, `f641`) character from the provided byte slice.
599///
600/// Returns `Some((value, length_consumed))` if `bytes` begins with a valid,
601/// canonical `DcTF` sequence, or `None` if malformed, non-canonical, or truncated.
602#[must_use]
603pub fn decode_dctf_buf(bytes: &[u8]) -> Option<(u128, usize)> {
604    let first = *bytes.first()?;
605    if first < 0x80 {
606        return Some((u128::from(first), 1));
607    }
608    if first < 0xC2 {
609        return None;
610    }
611    if first == 0xFF {
612        let b1 = *bytes.get(1)?;
613        if (b1 & 0xC0) != 0x80 {
614            return None;
615        }
616        let k = usize::from((b1 >> 2) & 0x0F);
617        let total_len = 8usize.saturating_add(k);
618        if bytes.len() < total_len {
619            return None;
620        }
621        let mut value = u128::from(b1 & 0x03);
622        for i in 2..total_len {
623            let b = *bytes.get(i)?;
624            if (b & 0xC0) != 0x80 {
625                return None;
626            }
627            value = (value << 6) | u128::from(b & 0x3F);
628        }
629        let min_val = if k == 0 {
630            1u128 << 36
631        } else {
632            1u128 << (32usize.saturating_add(6usize.saturating_mul(k)))
633        };
634        if value < min_val {
635            return None;
636        }
637        return Some((value, total_len));
638    }
639
640    let (len, min_val, lead_mask): (usize, u128, u8) = if (first & 0xE0) == 0xC0
641    {
642        (2, 1u128 << 7, 0x1F)
643    } else if (first & 0xF0) == 0xE0 {
644        (3, 1u128 << 11, 0x0F)
645    } else if (first & 0xF8) == 0xF0 {
646        (4, 1u128 << 16, 0x07)
647    } else if (first & 0xFC) == 0xF8 {
648        (5, 1u128 << 21, 0x03)
649    } else if (first & 0xFE) == 0xFC {
650        (6, 1u128 << 26, 0x01)
651    } else {
652        // first == 0xFE
653        (7, 1u128 << 31, 0x00)
654    };
655
656    if bytes.len() < len {
657        return None;
658    }
659
660    let mut value = u128::from(first & lead_mask);
661    for i in 1..len {
662        let b = *bytes.get(i)?;
663        if (b & 0xC0) != 0x80 {
664            return None;
665        }
666        value = (value << 6) | u128::from(b & 0x3F);
667    }
668
669    if value < min_val {
670        return None;
671    }
672
673    Some((value, len))
674}
675
676/// Computes the maximal-subpart error length for an invalid or incomplete
677/// `DcTF` (`.dctf`, `f641`) byte slice.
678///
679/// Returns `Some(n)` (`n >= 1`) when `slice[..n]` is the longest initial subsequence
680/// that can prefix a canonical `DcTF` sequence (or `Some(1)` if `slice[0]` cannot
681/// start any canonical sequence), or `None` when the entire `slice` is a valid
682/// incomplete prefix of a canonical `DcTF` sequence (truncated at the end of `slice`).
683#[must_use]
684pub fn determine_dctf_error_len(slice: &[u8]) -> Option<usize> {
685    let first = *slice.first()?;
686    if first < 0xC2 {
687        return Some(1);
688    }
689    if first == 0xFF {
690        let Some(&b1) = slice.get(1) else {
691            return None;
692        };
693        if (b1 & 0xC0) != 0x80 || b1 == 0x80 {
694            return Some(1);
695        }
696        let k = usize::from((b1 >> 2) & 0x0F);
697        let expected_len = 8usize.saturating_add(k);
698        for i in 2..expected_len {
699            let Some(&b) = slice.get(i) else {
700                return None;
701            };
702            if (b & 0xC0) != 0x80 {
703                return Some(i);
704            }
705            if i == 2 && k >= 1 && (b1 & 0x03) == 0 && b < 0x84 {
706                return Some(2);
707            }
708        }
709        return Some(expected_len);
710    }
711
712    let (expected_len, min_b1): (usize, u8) = if first <= 0xDF {
713        (2, 0x80)
714    } else if first == 0xE0 {
715        (3, 0xA0)
716    } else if first <= 0xEF {
717        (3, 0x80)
718    } else if first == 0xF0 {
719        (4, 0x90)
720    } else if first <= 0xF7 {
721        (4, 0x80)
722    } else if first == 0xF8 {
723        (5, 0x88)
724    } else if first <= 0xFB {
725        (5, 0x80)
726    } else if first == 0xFC {
727        (6, 0x84)
728    } else if first == 0xFD {
729        (6, 0x80)
730    } else {
731        // first == 0xFE
732        (7, 0x82)
733    };
734
735    for i in 1..expected_len {
736        let Some(&b) = slice.get(i) else {
737            return None;
738        };
739        let lo = if i == 1 { min_b1 } else { 0x80 };
740        if b < lo || b > 0xBF {
741            return Some(i);
742        }
743    }
744    Some(expected_len)
745}
746
747/// Encodes `codepoint` in `DcTF` (`.dctf`, `f641`) and returns a `Vec<u8>`.
748#[must_use]
749#[expect(
750    clippy::expect_used,
751    reason = "encode_dctf_buf returns length <= MAX_DCTF_LEN (23) which fits in buf"
752)]
753pub fn encode_dctf(codepoint: u128) -> Vec<u8> {
754    let mut buf = [0u8; MAX_DCTF_LEN];
755    let encoded_len = encode_dctf_buf(&mut buf, codepoint);
756    buf.get(..encoded_len)
757        .expect("encoded_len <= 23 fits in buf")
758        .to_vec()
759}
760
761/// Decodes one `DcTF` (`.dctf`, `f641`) codepoint from `bytes`, or returns
762/// `(0xFFFD, error_len)` using maximal-subpart error recovery on ill-formed input.
763#[must_use]
764pub fn decode_dctf(bytes: &[u8]) -> Option<(u128, usize)> {
765    if bytes.is_empty() {
766        return None;
767    }
768
769    if let Some(x) = decode_dctf_buf(bytes) {
770        Some(x)
771    } else {
772        // Reason for fallback: truncated prefix at EOF consumes remaining bytes as one U+FFFD
773        // when determine_dctf_error_len returns None for lossy decoding.
774        let err_len = determine_dctf_error_len(bytes).unwrap_or(bytes.len());
775        Some((0xFFFD, err_len))
776    }
777}