ctb_formats_dctf/
dctf.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//! DcTF and legacy DcUtf / "UTF-8e-128" encoding and decoding (UTF-8 extended to 128-bit integers)
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29mod codec;
30pub use codec::{
31    MAX_DCTF_LEN, decode_dctf, decode_dctf_buf, decode_utf_8e_128,
32    decode_utf_8e_128_buf, determine_dctf_error_len,
33    determine_utf_8e_128_error_len, encode_dctf, encode_dctf_buf,
34    encode_utf_8e_128, encode_utf_8e_128_buf, len_dctf, len_utf_8e_128,
35};
36
37#[ipc_method]
38/// Encode a u128 codepoint using the `utf_8e_128` format.
39pub fn encode_dcutf(codepoint: u128) -> Vec<u8> {
40    encode_utf_8e_128(codepoint)
41}
42
43#[ipc_method]
44/// Lossily decode the first character from `bytes` using the legacy DcUtf (`utf_8e_128`) format.
45///
46/// Returns `(value, used_len)` (yielding `U+FFFD` and the maximal subpart length on
47/// malformed sequences), or `None` if `bytes` is empty.
48#[expect(
49    clippy::needless_pass_by_value,
50    reason = "IPC method signature requires Vec<u8>"
51)]
52pub fn decode_dcutf(bytes: Vec<u8>) -> Option<(u128, usize)> {
53    decode_utf_8e_128(&bytes)
54}
55
56#[ipc_method]
57/// Encode a u128 codepoint using the DcTF format.
58pub fn encode(codepoint: u128) -> Vec<u8> {
59    encode_dctf(codepoint)
60}
61
62#[ipc_method]
63/// Lossily decode the first character from `bytes` using the DcTF format.
64///
65/// Returns `(value, used_len)` (yielding `U+FFFD` and the maximal subpart length on
66/// malformed sequences), or `None` if `bytes` is empty.
67#[expect(
68    clippy::needless_pass_by_value,
69    reason = "IPC method signature requires Vec<u8>"
70)]
71pub fn decode(bytes: Vec<u8>) -> Option<(u128, usize)> {
72    decode_dctf(&bytes)
73}
74
75#[cfg(test)]
76#[allow(
77    clippy::panic,
78    clippy::expect_used,
79    clippy::unwrap_used,
80    clippy::unwrap_in_result,
81    clippy::panic_in_result_fn,
82    clippy::indexing_slicing,
83    clippy::arithmetic_side_effects,
84    reason = "Standard repository test boilerplate"
85)]
86mod tests {
87    use super::*;
88
89    #[crate::ctb_test]
90    fn test_standard_ascii() {
91        let mut buf = [0u8; 24];
92        for ch in [0x00u128, 0x41, 0x7F] {
93            let n = encode_utf_8e_128_buf(&mut buf, ch);
94            let (v, m) = decode_utf_8e_128_buf(&buf[..n]).unwrap();
95            assert_eq!(v, ch);
96            assert_eq!(n, m);
97        }
98    }
99
100    #[crate::ctb_test]
101    fn test_standard_multibyte() {
102        let samples = [
103            0x80u128, 0x7FF, 0x800, 0x1234, 0x20AC, 0xFFFF, 0x10000, 0x10FFFF,
104        ];
105        let mut buf = [0u8; 24];
106        for cp in samples {
107            let n = encode_utf_8e_128_buf(&mut buf, cp);
108            let (v, m) = decode_utf_8e_128_buf(&buf[..n]).unwrap();
109            assert_eq!(v, cp);
110            assert_eq!(n, m);
111        }
112    }
113
114    #[crate::ctb_test]
115    fn test_extended_simple() {
116        let mut buf = [0u8; 24];
117        let cp = 0x10FFFFu128 + 1;
118        let n = encode_utf_8e_128_buf(&mut buf, cp);
119        assert!(n >= 3);
120        assert_eq!(buf[0], 0xFF);
121        let (v, m) = decode_utf_8e_128_buf(&buf[..n]).unwrap();
122        assert_eq!(v, cp);
123        assert_eq!(n, m);
124    }
125
126    #[crate::ctb_test]
127    fn test_extended_large() {
128        let mut buf = [0u8; 24];
129        let cp = u128::MAX;
130        let n = encode_utf_8e_128_buf(&mut buf, cp);
131        assert_eq!(buf[0], 0xFF);
132        let (v, m) = decode_utf_8e_128_buf(&buf[..n]).unwrap();
133        assert_eq!(v, cp);
134        assert_eq!(n, m);
135    }
136
137    #[crate::ctb_test]
138    fn test_malformed() {
139        assert!(decode_utf_8e_128_buf(&[]).is_none());
140        assert!(decode_utf_8e_128_buf(&[0x80]).is_none()); // continuation as start
141        assert!(decode_utf_8e_128_buf(&[0xFF]).is_none()); // incomplete extended
142    }
143
144    #[crate::ctb_test]
145    fn test_overlaps_rejected() {
146        // If value <= U+10FFFF must be encoded in standard form; constructing extended form should be rejected.
147        // Manually craft extended for 0x41
148        let bytes = vec![0xFF, 0x81, 0xC1]; // length=1, payload=0x01 -> value=1 (<= U+10FFFF)
149        assert!(decode_utf_8e_128_buf(&bytes).is_none());
150
151        // Construct an extended encoding for a value in standard range (should decode to None)
152        // Manually: value = 0x10FFFF (should have used standard form)
153        let mut bytes = Vec::new();
154        bytes.push(0xFF);
155        // Determine minimal groups for 0x10FFFF
156        let val = 0x10FFFFu128;
157        let bits = 128usize.saturating_sub(
158            usize::try_from(val.leading_zeros())
159                .expect("Failed to create usize"),
160        );
161        let l = bits.div_ceil(6);
162        bytes.push(0x80 | u8::try_from(l).expect("Failed to create byte"));
163        let mut groups = [0u8; 22];
164        let mut tmp = val;
165        for i in 0..l {
166            groups[l.saturating_sub(1).saturating_sub(i)] =
167                u8::try_from(tmp & 0x3F).expect("Failed to create byte");
168            tmp >>= 6;
169        }
170        for i in 0..l {
171            bytes.push(0x80 | groups[i]);
172        }
173        assert!(decode_utf_8e_128_buf(&bytes).is_none());
174    }
175
176    #[crate::ctb_test]
177    fn test_encode_utf_8e_128_buf_basic() {
178        let mut buf = [0u8; 24];
179        // ASCII
180        let n = encode_utf_8e_128_buf(&mut buf, 0x41);
181        assert_eq!(&buf[..n], &[0x41]);
182        // 2-byte
183        let n = encode_utf_8e_128_buf(&mut buf, 0x80);
184        assert_eq!(&buf[..n], &[0xC2, 0x80]);
185        // 3-byte
186        let n = encode_utf_8e_128_buf(&mut buf, 0x800);
187        assert_eq!(&buf[..n], &[0xE0, 0xA0, 0x80]);
188        // 4-byte
189        let n = encode_utf_8e_128_buf(&mut buf, 0x10000);
190        assert_eq!(&buf[..n], &[0xF0, 0x90, 0x80, 0x80]);
191        // Extended
192        encode_utf_8e_128_buf(&mut buf, 0x1_0000_0000);
193        assert_eq!(buf[0], 0xFF);
194    }
195
196    #[crate::ctb_test]
197    fn test_decode_utf_8e_128_buf_basic() {
198        // ASCII
199        let res = decode_utf_8e_128_buf(&[0x41]);
200        assert_eq!(res, Some((0x41, 1)));
201        // 2-byte
202        let res = decode_utf_8e_128_buf(&[0xC2, 0x80]);
203        assert_eq!(res, Some((0x80, 2)));
204        // 3-byte
205        let res = decode_utf_8e_128_buf(&[0xE0, 0xA0, 0x80]);
206        assert_eq!(res, Some((0x800, 3)));
207        // 4-byte
208        let res = decode_utf_8e_128_buf(&[0xF0, 0x90, 0x80, 0x80]);
209        assert_eq!(res, Some((0x10000, 4)));
210    }
211
212    #[crate::ctb_test]
213    fn test_encode_decode_utf_8e_128() {
214        // Roundtrip
215        for &cp in &[
216            0x41u128,
217            0x80,
218            0x800,
219            0x10000,
220            0x10FFFF,
221            0x1_0000_0000,
222            u128::MAX,
223        ] {
224            let encoded = encode_utf_8e_128(cp);
225            let decoded = decode_utf_8e_128(&encoded).unwrap();
226            assert_eq!(decoded.0, cp);
227        }
228    }
229
230    #[crate::ctb_test]
231    fn test_decode_utf_8e_128_replacement() {
232        // Invalid input returns replacement character consuming exact maximal subpart
233        let res = decode_utf_8e_128(&[0xFF]);
234        assert_eq!(res, Some((0xFFFD, 1)));
235    }
236
237    #[crate::ctb_test]
238    fn test_dctf_standard_ascii() {
239        let mut buf = [0u8; 24];
240        for ch in [0x00u128, 0x41, 0x7F] {
241            let n = encode_dctf_buf(&mut buf, ch);
242            let (v, m) = decode_dctf_buf(&buf[..n]).unwrap();
243            assert_eq!(v, ch);
244            assert_eq!(n, m);
245        }
246    }
247
248    #[crate::ctb_test]
249    fn test_dctf_standard_multibyte() {
250        let samples = [
251            0x80u128, 0x7FF, 0x800, 0x1234, 0x20AC, 0xFFFF, 0x10000, 0x10FFFF,
252        ];
253        let mut buf = [0u8; 24];
254        for cp in samples {
255            let n = encode_dctf_buf(&mut buf, cp);
256            let (v, m) = decode_dctf_buf(&buf[..n]).unwrap();
257            assert_eq!(v, cp);
258            assert_eq!(n, m);
259        }
260    }
261
262    #[crate::ctb_test]
263    fn test_dctf_extended_simple() {
264        let mut buf = [0u8; 24];
265        let cp = 0x10FFFFu128 + 1;
266        let n = encode_dctf_buf(&mut buf, cp);
267        assert_eq!(n, 4);
268        assert_eq!(buf[0], 0xF4);
269        let (v, m) = decode_dctf_buf(&buf[..n]).unwrap();
270        assert_eq!(v, cp);
271        assert_eq!(n, m);
272    }
273
274    #[crate::ctb_test]
275    fn test_dctf_extended_large() {
276        let mut buf = [0u8; 24];
277        let cp = u128::MAX;
278        let n = encode_dctf_buf(&mut buf, cp);
279        assert_eq!(buf[0], 0xFF);
280        let (v, m) = decode_dctf_buf(&buf[..n]).unwrap();
281        assert_eq!(v, cp);
282        assert_eq!(n, m);
283    }
284
285    #[crate::ctb_test]
286    fn test_dctf_malformed() {
287        assert!(decode_dctf_buf(&[]).is_none());
288        assert!(decode_dctf_buf(&[0x80]).is_none()); // continuation as start
289        assert!(decode_dctf_buf(&[0xFF]).is_none()); // incomplete extended
290    }
291
292    #[crate::ctb_test]
293    fn test_dctf_overlaps_rejected() {
294        // If value <= U+10FFFF must be encoded in standard form; constructing extended form should be rejected.
295        // Manually craft extended for 0x41
296        let bytes = vec![0xFF, 0x81, 0xC1]; // length=1, payload=0x01 -> value=1 (<= U+10FFFF)
297        assert!(decode_dctf_buf(&bytes).is_none());
298
299        // Construct an extended encoding for a value in standard range (should decode to None)
300        // Manually: value = 0x10FFFF (should have used standard form)
301        let mut bytes = Vec::new();
302        bytes.push(0xFF);
303        // Determine minimal groups for 0x10FFFF
304        let val = 0x10FFFFu128;
305        let bits = 128usize.saturating_sub(
306            usize::try_from(val.leading_zeros())
307                .expect("Failed to create usize"),
308        );
309        let l = bits.div_ceil(6);
310        bytes.push(0x80 | u8::try_from(l).expect("Failed to create byte"));
311        let mut groups = [0u8; 22];
312        let mut tmp = val;
313        for i in 0..l {
314            groups[l.saturating_sub(1).saturating_sub(i)] =
315                u8::try_from(tmp & 0x3F).expect("Failed to create byte");
316            tmp >>= 6;
317        }
318        for i in 0..l {
319            bytes.push(0x80 | groups[i]);
320        }
321        assert!(decode_dctf_buf(&bytes).is_none());
322    }
323
324    #[crate::ctb_test]
325    fn test_dctf_encode_dctf_buf_basic() {
326        let mut buf = [0u8; 24];
327        // ASCII
328        let n = encode_dctf_buf(&mut buf, 0x41);
329        assert_eq!(&buf[..n], &[0x41]);
330        // 2-byte
331        let n = encode_dctf_buf(&mut buf, 0x80);
332        assert_eq!(&buf[..n], &[0xC2, 0x80]);
333        // 3-byte
334        let n = encode_dctf_buf(&mut buf, 0x800);
335        assert_eq!(&buf[..n], &[0xE0, 0xA0, 0x80]);
336        // 4-byte
337        let n = encode_dctf_buf(&mut buf, 0x10000);
338        assert_eq!(&buf[..n], &[0xF0, 0x90, 0x80, 0x80]);
339        // 7-byte (36-bit tier)
340        let n = encode_dctf_buf(&mut buf, 0x1_0000_0000);
341        assert_eq!(n, 7);
342        assert_eq!(buf[0], 0xFE);
343        // 8-byte (0xFF tier 0, >= 2^36)
344        let n = encode_dctf_buf(&mut buf, 0x10_0000_0000);
345        assert_eq!(n, 8);
346        assert_eq!(buf[0], 0xFF);
347    }
348
349    #[crate::ctb_test]
350    fn test_dctf_decode_dctf_buf_basic() {
351        // ASCII
352        let res = decode_dctf_buf(&[0x41]);
353        assert_eq!(res, Some((0x41, 1)));
354        // 2-byte
355        let res = decode_dctf_buf(&[0xC2, 0x80]);
356        assert_eq!(res, Some((0x80, 2)));
357        // 3-byte
358        let res = decode_dctf_buf(&[0xE0, 0xA0, 0x80]);
359        assert_eq!(res, Some((0x800, 3)));
360        // 4-byte
361        let res = decode_dctf_buf(&[0xF0, 0x90, 0x80, 0x80]);
362        assert_eq!(res, Some((0x10000, 4)));
363    }
364
365    #[crate::ctb_test]
366    fn test_dctf_encode_decode_dctf() {
367        // Roundtrip
368        for &cp in &[
369            0x41u128,
370            0x80,
371            0x800,
372            0x10000,
373            0x10FFFF,
374            0x1_0000_0000,
375            u128::MAX,
376        ] {
377            let encoded = encode_dctf(cp);
378            let decoded = decode_dctf(&encoded).unwrap();
379            assert_eq!(decoded.0, cp);
380        }
381    }
382
383    #[crate::ctb_test]
384    fn test_dctf_decode_dctf_replacement() {
385        // Invalid input returns replacement character consuming exact maximal subpart
386        let res = decode_dctf(&[0xFF]);
387        assert_eq!(res, Some((0xFFFD, 1)));
388    }
389
390    #[crate::ctb_test]
391    fn test_dctf_all_tier_boundaries_and_ordering() {
392        // Every tier boundary from 1B through 23B (k = 0..=15), plus surrogates
393        let mut boundaries: Vec<(u128, usize)> = vec![
394            (0x00, 1),
395            (0x7F, 1),
396            (0x80, 2),
397            (0x7FF, 2),
398            (0x800, 3),
399            (0xD7FF, 3),
400            (0xD800, 3),
401            (0xDFFF, 3),
402            (0xE000, 3),
403            (0xFFFF, 3),
404            (0x1_0000, 4),
405            (0x10_FFFF, 4),
406            (0x11_0000, 4),
407            (0x11_00CB, 4), // Dc 203
408            (0x1F_FFFF, 4),
409            (0x20_0000, 5),
410            (0x22_0000, 5), // Format Dc start
411            (0x3FF_FFFF, 5),
412            (0x400_0000, 6),
413            (0x7FFF_FFFF, 6),
414            (0x8000_0000, 7),
415            (0x2_0000_0000, 7), // System ID start
416            (0xF_FFFF_FFFF, 7),
417        ];
418        for k in 0..=15usize {
419            let min_val = if k == 0 {
420                1u128 << 36
421            } else {
422                1u128 << (32 + 6 * k)
423            };
424            let max_bits = 38 + 6 * k;
425            let max_val = if max_bits == 128 {
426                u128::MAX
427            } else {
428                (1u128 << max_bits) - 1
429            };
430            boundaries.push((min_val, 8 + k));
431            boundaries.push((max_val, 8 + k));
432        }
433
434        let mut prev_val: Option<u128> = None;
435        let mut prev_bytes: Option<Vec<u8>> = None;
436        for (val, expected_len) in boundaries {
437            assert_eq!(
438                len_dctf(val),
439                expected_len,
440                "len_dctf mismatch for {val:#x}"
441            );
442            let encoded = encode_dctf(val);
443            assert_eq!(
444                encoded.len(),
445                expected_len,
446                "encode_dctf length mismatch for {val:#x}"
447            );
448            let (decoded, consumed) =
449                decode_dctf_buf(&encoded).unwrap_or_else(|| {
450                    panic!("decode_dctf_buf failed for {val:#x}")
451                });
452            assert_eq!(decoded, val);
453            assert_eq!(consumed, expected_len);
454
455            // Unsigned byte-lexicographic order must strictly match numeric order
456            if let (Some(pv), Some(pb)) = (prev_val, &prev_bytes) {
457                if val > pv {
458                    assert!(
459                        pb.as_slice() < encoded.as_slice(),
460                        "Lexicographic order violated between {pv:#x} ({pb:02X?}) and {val:#x} ({encoded:02X?})"
461                    );
462                }
463            }
464            prev_val = Some(val);
465            prev_bytes = Some(encoded);
466        }
467    }
468
469    #[crate::ctb_test]
470    fn test_dctf_overlong_rejections() {
471        // 2B overlong: 0x00 and 0x7F
472        assert!(decode_dctf_buf(&[0xC0, 0x80]).is_none());
473        assert!(decode_dctf_buf(&[0xC1, 0xBF]).is_none());
474        // 3B overlong: 0x7FF
475        assert!(decode_dctf_buf(&[0xE0, 0x9F, 0xBF]).is_none());
476        // 4B overlong: 0xFFFF
477        assert!(decode_dctf_buf(&[0xF0, 0x8F, 0xBF, 0xBF]).is_none());
478        // 5B overlong: 0x1F_FFFF
479        assert!(decode_dctf_buf(&[0xF8, 0x87, 0xBF, 0xBF, 0xBF]).is_none());
480        // 6B overlong: 0x3FF_FFFF
481        assert!(
482            decode_dctf_buf(&[0xFC, 0x83, 0xBF, 0xBF, 0xBF, 0xBF]).is_none()
483        );
484        // 7B overlong: 0x7FFF_FFFF
485        assert!(
486            decode_dctf_buf(&[0xFE, 0x81, 0xBF, 0xBF, 0xBF, 0xBF, 0xBF])
487                .is_none()
488        );
489        // 8B (k=0) overlong: 2^36 - 1 (0xFF, 0x80, 0xBF x 6)
490        assert!(
491            decode_dctf_buf(&[0xFF, 0x80, 0xBF, 0xBF, 0xBF, 0xBF, 0xBF, 0xBF])
492                .is_none()
493        );
494        // 8B (k=0) min valid: 2^36 (0xFF, 0x81, 0x80 x 6)
495        assert_eq!(
496            decode_dctf_buf(&[0xFF, 0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80]),
497            Some((1u128 << 36, 8))
498        );
499        // k = 1..=15 overlong (2^(32+6k) - 1) vs min valid (2^(32+6k))
500        for k in 1..=15usize {
501            let total_len = 8 + k;
502            let k_u8 = u8::try_from(k).unwrap();
503            let mut overlong = vec![0xFF, 0x80 | (k_u8 << 2), 0x83];
504            overlong.resize(total_len, 0xBF);
505            assert!(
506                decode_dctf_buf(&overlong).is_none(),
507                "Expected overlong rejection at k={k}"
508            );
509
510            let mut min_valid = vec![0xFF, 0x80 | (k_u8 << 2), 0x84];
511            min_valid.resize(total_len, 0x80);
512            assert_eq!(
513                decode_dctf_buf(&min_valid),
514                Some((1u128 << (32 + 6 * k), total_len)),
515                "Expected min_valid acceptance at k={k}"
516            );
517        }
518    }
519
520    #[crate::ctb_test]
521    fn test_dctf_and_dcutf_maximal_subpart_recovery() {
522        // Helper that decodes an entire byte slice lossily into Vec<(u128, usize)>
523        fn lossy_dctf_stream(mut slice: &[u8]) -> Vec<(u128, usize)> {
524            let mut out = Vec::new();
525            while let Some((cp, len)) = decode_dctf(slice) {
526                out.push((cp, len));
527                slice = &slice[len..];
528            }
529            out
530        }
531
532        fn lossy_dcutf_stream(mut slice: &[u8]) -> Vec<(u128, usize)> {
533            let mut out = Vec::new();
534            while let Some((cp, len)) = decode_utf_8e_128(slice) {
535                out.push((cp, len));
536                slice = &slice[len..];
537            }
538            out
539        }
540
541        // 1. E1 80 41 -> (FFFD, 2), ('A', 1) (must not swallow ASCII 'A'!)
542        assert_eq!(determine_dctf_error_len(&[0xE1, 0x80, 0x41]), Some(2));
543        assert_eq!(
544            determine_utf_8e_128_error_len(&[0xE1, 0x80, 0x41]),
545            Some(2)
546        );
547        assert_eq!(
548            lossy_dctf_stream(&[0xE1, 0x80, 0x41]),
549            vec![(0xFFFD, 2), (0x41, 1)]
550        );
551        assert_eq!(
552            lossy_dcutf_stream(&[0xE1, 0x80, 0x41]),
553            vec![(0xFFFD, 2), (0x41, 1)]
554        );
555
556        // 2. C0 80 -> two 1-byte errors
557        assert_eq!(determine_dctf_error_len(&[0xC0, 0x80]), Some(1));
558        assert_eq!(
559            lossy_dctf_stream(&[0xC0, 0x80]),
560            vec![(0xFFFD, 1), (0xFFFD, 1)]
561        );
562        assert_eq!(
563            lossy_dcutf_stream(&[0xC0, 0x80]),
564            vec![(0xFFFD, 1), (0xFFFD, 1)]
565        );
566
567        // 3. E0 80 80 -> three 1-byte errors
568        assert_eq!(determine_dctf_error_len(&[0xE0, 0x80, 0x80]), Some(1));
569        assert_eq!(
570            lossy_dctf_stream(&[0xE0, 0x80, 0x80]),
571            vec![(0xFFFD, 1), (0xFFFD, 1), (0xFFFD, 1)]
572        );
573        assert_eq!(
574            lossy_dcutf_stream(&[0xE0, 0x80, 0x80]),
575            vec![(0xFFFD, 1), (0xFFFD, 1), (0xFFFD, 1)]
576        );
577
578        // 4. F0 80 80 80 -> four 1-byte errors
579        assert_eq!(
580            determine_dctf_error_len(&[0xF0, 0x80, 0x80, 0x80]),
581            Some(1)
582        );
583        assert_eq!(
584            lossy_dctf_stream(&[0xF0, 0x80, 0x80, 0x80]),
585            vec![(0xFFFD, 1); 4]
586        );
587
588        // 5. F8 80 80 80 80 -> five 1-byte errors in DcTF (and in DcUtf since F8 is invalid start)
589        assert_eq!(
590            determine_dctf_error_len(&[0xF8, 0x80, 0x80, 0x80, 0x80]),
591            Some(1)
592        );
593        assert_eq!(
594            lossy_dctf_stream(&[0xF8, 0x80, 0x80, 0x80, 0x80]),
595            vec![(0xFFFD, 1); 5]
596        );
597        assert_eq!(
598            lossy_dcutf_stream(&[0xF8, 0x80, 0x80, 0x80, 0x80]),
599            vec![(0xFFFD, 1); 5]
600        );
601
602        // 6. FC 80 80 80 80 80 -> six 1-byte errors
603        assert_eq!(
604            lossy_dctf_stream(&[0xFC, 0x80, 0x80, 0x80, 0x80, 0x80]),
605            vec![(0xFFFD, 1); 6]
606        );
607
608        // 7. FE 80 80 80 80 80 80 -> seven 1-byte errors
609        assert_eq!(
610            lossy_dctf_stream(&[0xFE, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80]),
611            vec![(0xFFFD, 1); 7]
612        );
613
614        // 8. FF 80 80 80 80 80 80 80 -> eight 1-byte errors in DcTF (0xFF 0x80 cannot reach 2^36)
615        assert_eq!(
616            lossy_dctf_stream(&[
617                0xFF, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80
618            ]),
619            vec![(0xFFFD, 1); 8]
620        );
621
622        // 9. FF 84 80 80 80 80 80 80 80 -> in DcTF (k=1, bb=00), [0xFF, 0x84] is a valid 2-byte
623        // prefix, but byte 2 (0x80 < 0x84) cannot continue it -> 1 two-byte error + 7 one-byte errors!
624        assert_eq!(
625            determine_dctf_error_len(&[
626                0xFF, 0x84, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80
627            ]),
628            Some(2)
629        );
630        assert_eq!(
631            lossy_dctf_stream(&[
632                0xFF, 0x84, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80
633            ]),
634            vec![
635                (0xFFFD, 2),
636                (0xFFFD, 1),
637                (0xFFFD, 1),
638                (0xFFFD, 1),
639                (0xFFFD, 1),
640                (0xFFFD, 1),
641                (0xFFFD, 1),
642                (0xFFFD, 1),
643            ]
644        );
645
646        // 10. Chunk-boundary vs actual-EOF truncation:
647        // [0xE2, 0x82] is an incomplete 2-byte prefix of U+20AC:
648        assert_eq!(determine_dctf_error_len(&[0xE2, 0x82]), None);
649        assert_eq!(determine_utf_8e_128_error_len(&[0xE2, 0x82]), None);
650        // At actual EOF (decode_dctf / decode_utf_8e_128), it consumes all 2 bytes as one U+FFFD:
651        assert_eq!(decode_dctf(&[0xE2, 0x82]), Some((0xFFFD, 2)));
652        assert_eq!(decode_utf_8e_128(&[0xE2, 0x82]), Some((0xFFFD, 2)));
653
654        // 11. Malformed extended (0xFF) sequences followed by ASCII 'A' (0x41):
655        // Must preserve 'A' and never consume it into the replacement span.
656        // DcTF: 0xFF 0x81 (k=0, expects 8 bytes) truncated after 3 bytes by 'A':
657        assert_eq!(
658            determine_dctf_error_len(&[
659                0xFF, 0x81, 0x80, 0x41, 0x80, 0x80, 0x80, 0x80
660            ]),
661            Some(3)
662        );
663        assert_eq!(
664            lossy_dctf_stream(&[0xFF, 0x81, 0x80, 0x41]),
665            vec![(0xFFFD, 3), (0x41, 1)]
666        );
667        // DcUtf: 0xFF 0x84 (L=4, expects 6 bytes) with canonical byte 2 (0x84) truncated by 'A':
668        assert_eq!(
669            determine_utf_8e_128_error_len(&[
670                0xFF, 0x84, 0x84, 0x41, 0x80, 0x80
671            ]),
672            Some(3)
673        );
674        assert_eq!(
675            lossy_dcutf_stream(&[0xFF, 0x84, 0x84, 0x41]),
676            vec![(0xFFFD, 3), (0x41, 1)]
677        );
678
679        // 12. Overlapping byte sequence FF 87 81 80 80 80 80 80 80:
680        // Valid in both DcUtf (2^36 = 68,719,476,736) and DcTF (13_262_859_010_048).
681        let overlap = [0xFF, 0x87, 0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80];
682        assert_eq!(decode_utf_8e_128_buf(&overlap), Some((1u128 << 36, 9)));
683        assert_eq!(
684            decode_dctf_buf(&overlap),
685            Some((13_262_859_010_048u128, 9))
686        );
687    }
688
689    #[crate::ctb_test]
690    fn test_ipc_encode_decode_wrappers() {
691        assert_eq!(decode(Vec::new()), None);
692        assert_eq!(decode_dcutf(Vec::new()), None);
693
694        let cp = 0x11_0000u128; // Short Dc 0
695        let encoded_dctf = encode(cp);
696        let encoded_dcutf = encode_dcutf(cp);
697        assert_eq!(encoded_dctf, encode_dctf(cp));
698        assert_eq!(encoded_dcutf, encode_utf_8e_128(cp));
699
700        let decoded_dctf = decode(encoded_dctf).unwrap();
701        assert_eq!(decoded_dctf.0, cp);
702
703        let decoded_dcutf = decode_dcutf(encoded_dcutf).unwrap();
704        assert_eq!(decoded_dcutf.0, cp);
705    }
706}