ctb_formats_eite/encoding/
basenb.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//! Basenb encoding/decoding: pack binary data into Unicode PUA.
21//!
22//! Basenb is a way of encoding arbitrary binary data into a compact string
23//! representation that can be embedded in Unicode text, as runs of Unicode
24//! private-use characters.
25//!
26//! It's a modified version of Base16b that additionally encodes a "remainder"
27//! length in a trailing character, which seems to be needed to reliably
28//! round-trip values.
29//!
30//! Actually using it requires some sort of protocol for when to switch between
31//! basenb and regular PUA characters. dcBasenb addresses that by encoding UUIDs
32//! and using them as in-band start/end markers. (Round-tripping a UTF-8 file
33//! that included dcBasenb UUIDs, for instance in reference to them, would
34//! probably only be possible by encoding the UUIDs as UTF-8 encapsulated within
35//! the Dcs, and being careful with the encode/decode settings.)
36//!
37//! dcBasenb is a way of encoding arbitrary Dcs into runs of Unicode private-use
38//! characters; see dcbasenb.rs
39
40#[allow(
41    unused_imports,
42    clippy::wildcard_imports,
43    reason = "Standard workspace module prelude"
44)]
45use crate::utilities::*;
46
47use anyhow::{Result, anyhow, bail};
48
49use crate::encoding::pack32::{is_pack32_char, pack32, unpack32};
50use crate::util::array::subset;
51use crate::util::bitwise::{
52    byte_array_from_int_bit_array, byte_array_to_int_bit_array,
53};
54use crate::util::math::int_is_between_u32;
55use crate::{bail_if_none, log};
56use ctb_formats_base16b as base16b;
57
58/// FIXME UNIMPLEMENTED
59pub const ARMORED_BASE17B_UTF8_START_UUID_BYTES: [u8; 32] = [
60    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
61    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
62    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
63];
64
65/// FIXME UNIMPLEMENTED
66pub const ARMORED_BASE17B_UTF8_END_UUID_BYTES: [u8; 32] = [
67    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
68    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
69    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
70];
71
72/// internalIntBitArrayToBasenbString(intBase, bytes)
73/// Returns UTF-8 bytes of the encoded string (mirroring JS returning a byte array).
74pub fn int_bit_array_to_basenb_no_remainder_marker(
75    base: u32,
76    input: &[u8],
77) -> Result<Vec<u8>> {
78    let encoded = base16b::encode(input, base)?;
79
80    Ok(encoded.into_bytes())
81}
82
83/// internalIntBitArrayFromBasenbString(byteArrayInput, intRemainder)
84/// JS passes a `Uint8Array` of UTF-8 bytes and an int remainder
85pub fn int_bit_array_from_basenb_string(
86    input_bytes: &[u8],
87    remainder_len: Option<u32>,
88) -> Result<Vec<u8>> {
89    let s = std::str::from_utf8(input_bytes).map_err(|e| {
90        anyhow!(
91            "utf8 error on input {:?}, from_lossy {:?}: {e}",
92            input_bytes,
93            String::from_utf8_lossy(input_bytes)
94        )
95    })?;
96    log!(
97        "Decoding with input str {:?}, remainder {:?}",
98        s,
99        remainder_len
100    );
101    base16b::decode(s, remainder_len)
102}
103
104/// Is the provided base valid for Basenb? (Original: 7 through 17 inclusive.)
105pub fn is_basenb_base(base: u32) -> bool {
106    (7..=17).contains(&base)
107}
108
109/// True if the pack32 character represents a Basenb character codepoint.
110///
111/// The Basenb character ranges):
112///   - 983040 ..= 1048573: U+F0000 to U+FFFFD
113///   - 1048576 ..= 1114109: U+100000 to U+10FFFD
114///   - 63481  ..= 63501   (special / remainder markers): U+F7F9 to U+F80D
115///
116/// Distinct remainder markers subset: 63481 ..= 63497: U+F7F9 to U+F809
117pub fn is_basenb_char(packed_char: &[u8]) -> bool {
118    if !is_pack32_char(packed_char) {
119        return false;
120    }
121    if let Ok(cp) = unpack32(packed_char) {
122        // U+F0000 to U+FFFFD
123        if int_is_between_u32(cp, 983_040, 1_048_573) {
124            return true;
125        }
126        // U+100000 to U+10FFFD
127        if int_is_between_u32(cp, 1_048_576, 1_114_109) {
128            return true;
129        }
130        // U+F7F9 to U+F80D. Remainders are U+F7F9 to U+F809; U+F80A to U+F80D
131        // are used for Base16b and Base17b.
132        if int_is_between_u32(cp, 63_481, 63_501) {
133            return true;
134        }
135    }
136    false
137}
138
139/// True if the pack32 character is one of the distinct remainder markers
140/// (63481..=63497).
141pub fn is_basenb_distinct_remainder_char(packed_char: &[u8]) -> bool {
142    if !is_pack32_char(packed_char) {
143        return false;
144    }
145    if let Ok(cp) = unpack32(packed_char) {
146        // U+F7F9 to U+F809
147        return int_is_between_u32(cp, 63_481, 63_497);
148    }
149    false
150}
151
152pub fn byte_array_to_basenb_no_remainder_marker(
153    base: u32,
154    input: &[u8],
155) -> Result<Vec<u8>> {
156    if !is_basenb_base(base) {
157        return Err(anyhow!(
158            "byte_array_to_basenb_no_remainder_marker: invalid base {base}, expected 7..=17"
159        ));
160    }
161    let bit_array = byte_array_to_int_bit_array(input);
162    let encoded =
163        int_bit_array_to_basenb_no_remainder_marker(base, &bit_array)?;
164    Ok(encoded)
165}
166
167/// Encode a raw byte array into Basenb (UTF-8 sequence of pack32 codepoints).
168///
169/// Steps:
170/// 1. Convert bytes to bit array.
171/// 2. Encode bit array via `int_bit_array_to_basenb_string`.
172/// 3. Append remainder length marker: pack32(63497 - (`bit_len` % 17)).
173///    (Matches the original implementation’s workaround re: remainder storage.)
174///
175/// Returns the full UTF-8 (actually just raw bytes containing appended pack32
176/// code units) representing the Basenb encoding.
177pub fn byte_array_to_basenb_utf8(base: u32, input: &[u8]) -> Result<Vec<u8>> {
178    let mut encoded = byte_array_to_basenb_no_remainder_marker(base, input)?;
179    /* Remainder marker. The remainder length also needs to be stored, to be able to decode successfully. We'll calculate, encode, and append it. It's always 4 bytes, 1 UTF-8 character, and 2 UTF-16 characters long, after encoding (it has 2 added to it to make it always be the same byte length and UTF-16 length; this must be subtracted before passing it to the Base16b.decode function). */
180    let total_bits = input.len().checked_mul(8).ok_or_else(|| {
181        anyhow!("Input length is too large to represent bits")
182    })?;
183    let base_usize = usize::try_from(base)?;
184    let remainder = total_bits
185        .checked_rem(base_usize)
186        .ok_or_else(|| anyhow!("Base cannot be zero"))?;
187    // Start with U+F809, and subtract the remainder to find the codepoint.
188    let remainder_u32 = u32::try_from(remainder)?;
189    let codepoint = 63_497_u32.checked_sub(remainder_u32).ok_or_else(|| {
190        anyhow!("Remainder too large for codepoint calculation")
191    })?;
192    encoded.extend(pack32(codepoint)?);
193    Ok(encoded)
194}
195
196/// Sentinel UUID returned by the legacy JS implementation to indicate an invalid
197/// basenb UTF-8 decode input (only remainder char present or incomplete data).
198/// UUID: 3362daa3-1705-40ec-9a97-59d052fd4037
199pub const BYTE_ARRAY_FROM_BASENB_UTF8_INVALID_INPUT_EXCEPTION_BYTES: [u8; 16] = [
200    51, 98, 218, 163, 23, 5, 64, 236, 154, 151, 89, 208, 82, 253, 64, 55,
201];
202
203/// Decode a Basenb UTF-8 byte sequence into the original byte array.
204///
205/// This replicates the JS `byteArrayFromBasenbUtf8(intArrayIn)` logic:
206/// - Determines the encoded remainder-length indicator (either a distinct
207///   3‑byte remainder char or a generic 4‑byte packed char).
208/// - For a distinct remainder char (3 bytes): remainder = 63497 - unpack32
209///   (last3)
210/// - For a generic (4 bytes) remainder char: decode that char as an 8‑bit
211///   value, then `remainder = decoded_byte - 2`
212/// - If the full input length is exactly (or smaller than) the remainder char
213///   length, returns the sentinel UUID bytes to indicate invalid input (legacy
214///   behavior).
215///
216/// Remainder length (in bits) is passed to `int_bit_array_from_basenb_string`
217/// which reconstructs the concatenated bit array; that is then converted back
218/// to bytes.
219///
220/// Returns:
221/// - `Ok(Vec<u8>)` with decoded bytes (or sentinel bytes if invalid input).
222pub fn byte_array_from_basenb_utf8(input: &[u8]) -> Result<Vec<u8>> {
223    /* Extract remainder length */
224    let remainder: u32;
225    /* last 3 bytes (1 character), which represent the remainder */
226    let mut remainder_arr: Vec<u8>;
227    remainder_arr = bail_if_none!(subset(input, -3, -1)?);
228    if is_basenb_distinct_remainder_char(&remainder_arr) {
229        let raw_remainder = unpack32(&remainder_arr)?;
230        remainder = 63497_u32.checked_sub(raw_remainder).ok_or_else(|| {
231            anyhow!("Underflow in basenb remainder calculation")
232        })?;
233    } else {
234        /* last 4 bytes (1 character), which represent the remainder */
235        remainder_arr = bail_if_none!(subset(input, -4, -1)?);
236        let remainder_decoded: Vec<u8> = byte_array_from_int_bit_array(
237            &int_bit_array_from_basenb_string(&remainder_arr, Some(8))?,
238        )?;
239        let temp: &u8 = bail_if_none!(remainder_decoded.first());
240        let temp: i16 = bail_if_none!(i16::from(*temp).checked_add(-2));
241        remainder = u32::try_from(temp)?;
242    }
243    if input.len() <= remainder_arr.len() {
244        // Mirrors legacy path: only a (missing) remainder => sentinel.
245        return Ok(
246            BYTE_ARRAY_FROM_BASENB_UTF8_INVALID_INPUT_EXCEPTION_BYTES.to_vec()
247        );
248    }
249    let len_i64 = i64::try_from(remainder_arr.len())?;
250    let subset_end = len_i64
251        .checked_neg()
252        .and_then(|val| val.checked_sub(1))
253        .ok_or_else(|| {
254        anyhow!("Subset end calculation overflow/underflow")
255    })?;
256
257    let subset = bail_if_none!(subset(input, 0, subset_end)?);
258
259    log!("Getting bits from subset: {:?}, {:?}", &subset, remainder);
260
261    let bits = &int_bit_array_from_basenb_string(&subset, Some(remainder))?;
262    log!("Bits from decoder: {:?}", &bits);
263    byte_array_from_int_bit_array(bits)
264}
265
266/// Convenience wrapper (encode bytes to Basenb 17 UTF-8 representation).
267///
268/// JS original: `byteArrayToBase17bUtf8(intArrayIn)` calling `byteArrayToBasenbUtf8(17, ...)`.
269/// Renamed to try to make it clearer that this isn't the original base17b
270/// format.
271pub fn byte_array_to_basenb_17_utf8(input: &[u8]) -> Result<Vec<u8>> {
272    byte_array_to_basenb_utf8(17, input)
273}
274
275/// Convenience wrapper (decode Basenb  17 UTF-8 representation).
276///
277/// JS original simply forwarded to `byteArrayFromBasenbUtf8`.
278pub fn byte_array_from_basenb_17_utf8(input: &[u8]) -> Result<Vec<u8>> {
279    byte_array_from_basenb_utf8(input)
280}
281
282// “Armored” Base17b UTF-8 helpers.
283
284/// Produce an “armored” Base17b UTF-8 run, encoding arbitrary binary data:
285///   armored = `start_uuid` || `base17b_encode(bytes)` || `end_uuid`
286///
287/// This mirrors the original JS `byteArrayToArmoredBase17bUtf8`.
288/// FIXME Unimplemented/untested!
289pub fn byte_array_to_armored_base17b_utf8(input: &[u8]) -> Result<Vec<u8>> {
290    // Encode payload to Base17b UTF-8 (already provided in earlier translation).
291    let encoded = byte_array_to_basenb_17_utf8(input)?;
292    let mut out = ARMORED_BASE17B_UTF8_START_UUID_BYTES.to_vec();
293    out.extend(encoded);
294    out.extend(ARMORED_BASE17B_UTF8_END_UUID_BYTES);
295    Ok(out)
296}
297
298/// Decode an armored Base17b UTF-8 run to a byte array. FIXME untested!
299pub fn byte_array_from_armored_base17b_utf8(input: &[u8]) -> Result<Vec<u8>> {
300    let start = ARMORED_BASE17B_UTF8_START_UUID_BYTES;
301    let end = ARMORED_BASE17B_UTF8_END_UUID_BYTES;
302
303    let min_len = start
304        .len()
305        .checked_add(end.len())
306        .ok_or_else(|| anyhow!("Overflow calculating min_len"))?;
307    if input.len() < min_len {
308        bail!(
309            "Armored Base17b input too short: {} < required framing {}",
310            input.len(),
311            min_len
312        );
313    }
314
315    if !input.starts_with(&start) {
316        bail!("Armored Base17b input missing or corrupt start UUID marker");
317    }
318    if !input.ends_with(&end) {
319        bail!("Armored Base17b input missing or corrupt end UUID marker");
320    }
321
322    let inner_len = input
323        .len()
324        .checked_sub(start.len())
325        .and_then(|val| val.checked_sub(end.len()))
326        .ok_or_else(|| {
327            anyhow!("Input length underflow relative to start/end delimiters")
328        })?;
329    let end_idx = start
330        .len()
331        .checked_add(inner_len)
332        .ok_or_else(|| anyhow!("End index overflow"))?;
333    let inner = input
334        .get(start.len()..end_idx)
335        .ok_or_else(|| anyhow!("Input slice out of bounds"))?;
336    // Decode the inner Base17b UTF-8 segment back to raw bytes.
337    let decoded = byte_array_from_basenb_17_utf8(inner)?;
338    Ok(decoded)
339}
340
341#[cfg(test)]
342#[allow(
343    clippy::panic,
344    clippy::expect_used,
345    clippy::unwrap_used,
346    clippy::unwrap_in_result,
347    clippy::panic_in_result_fn,
348    clippy::indexing_slicing,
349    clippy::arithmetic_side_effects,
350    reason = "Standard repository test boilerplate"
351)]
352mod tests {
353
354    use crate::formats::dcbasenb::DC_BASENB_EMBEDDED_START_BYTES;
355    use crate::utilities::{assert_vec_u8_eq, assert_vec_u8_ok_eq};
356    use crate::{
357        encoding::pack32::pack32, util::bitwise::byte_array_to_int_bit_array,
358    };
359
360    use super::*;
361
362    #[crate::ctb_test]
363    fn test_is_basenb_base() {
364        for b in 0..=30 {
365            let valid = is_basenb_base(b);
366            if (7..=17).contains(&b) {
367                assert!(valid);
368            } else {
369                assert!(!valid);
370            }
371        }
372    }
373
374    #[crate::ctb_test]
375    fn test_basenb_remainder_marker_range() {
376        // Distinct remainder chars subset 63481..=63497
377        for cp in 63_480..=63_500 {
378            let packed = pack32(cp).unwrap();
379            if (63_481..=63_497).contains(&cp) {
380                assert!(is_basenb_distinct_remainder_char(&packed));
381            } else {
382                assert!(!is_basenb_distinct_remainder_char(&packed));
383            }
384        }
385    }
386
387    #[crate::ctb_test]
388    fn test_basenb_char_ranges() {
389        // sample points
390        for cp in [
391            63_480, 63_481, 63_495, 63_501, 63_502, 983_040, 983_100,
392            1_048_573, 1_048_574,
393        ] {
394            let packed = pack32(cp).unwrap();
395            let is_char = is_basenb_char(&packed);
396            let expected = (63_481..=63_501).contains(&cp)
397                || (983_040..=1_048_573).contains(&cp)
398                || (1_048_576..=1_114_109).contains(&cp);
399            assert_eq!(
400                is_char, expected,
401                "cp={} expected {} got {}",
402                cp, expected, is_char
403            );
404        }
405    }
406
407    #[crate::ctb_test]
408    fn test_byte_array_to_basenb_utf8_remainder_marker() {
409        // The remainder length also needs to be stored, to be able to decode successfully. We'll calculate, encode, and append it. It's always 4 bytes, 1 UTF-8 character, and 2 UTF-16 characters long, after encoding (it has 2 added to it to make it always be the same byte length and UTF-16 length; this must be subtracted before passing it to the Base16b.decode function).
410        // Known: remainder marker = 63497 - (bit_len % 17)
411        let data = b"\xAB\xCD"; // 16 bits
412        let bits = byte_array_to_int_bit_array(data);
413        assert_eq!(bits.len(), 16);
414        let base = 10;
415        let encoded_with_remainder =
416            byte_array_to_basenb_utf8(base, data).unwrap();
417        let encoded_b10b =
418            byte_array_to_basenb_no_remainder_marker(base, data).unwrap();
419        assert!(
420            encoded_with_remainder.len() >= 4,
421            "Expected at least one codepoint + remainder marker"
422        );
423        let len_diff = encoded_with_remainder
424            .len()
425            .checked_sub(encoded_b10b.len())
426            .expect("encoded_with_remainder is shorter than encoded_b10b");
427        let start_idx = encoded_with_remainder
428            .len()
429            .checked_sub(len_diff)
430            .expect("len_diff is greater than encoded_with_remainder length");
431        let lastn = &encoded_with_remainder[start_idx..];
432        assert!(is_basenb_distinct_remainder_char(lastn));
433        let cp = unpack32(lastn).unwrap();
434        let bits_len_u32 =
435            u32::try_from(bits.len()).expect("Could not fit length in u32");
436        let expected_rem =
437            bits_len_u32.checked_rem(base).expect("base is zero");
438        let expected = 63_497_u32
439            .checked_sub(expected_rem)
440            .expect("Remainder too large for expected codepoint");
441        assert_eq!(cp, expected);
442        assert_vec_u8_ok_eq(
443            data,
444            byte_array_from_basenb_utf8(&encoded_with_remainder),
445        );
446    }
447
448    #[crate::ctb_test]
449    fn test_byte_array_to_basenb_utf8_invalid_base() {
450        let data = b"abc";
451        assert!(byte_array_to_basenb_utf8(6, data).is_err());
452        assert!(byte_array_to_basenb_utf8(18, data).is_err());
453    }
454
455    fn is_sentinel(bytes: &[u8]) -> bool {
456        bytes == BYTE_ARRAY_FROM_BASENB_UTF8_INVALID_INPUT_EXCEPTION_BYTES
457    }
458
459    #[crate::ctb_test]
460    fn test_decode_empty_input() {
461        let enc = assert_vec_u8_ok_eq(
462            "\u{f80d}\u{f809}".as_bytes(),
463            byte_array_to_basenb_utf8(17, &[]),
464        );
465        let dec = byte_array_from_basenb_utf8(&enc);
466        assert_vec_u8_ok_eq(&[], dec);
467    }
468
469    #[crate::ctb_test]
470    fn test_decode_invalid_only_remainder() {
471        let dec = byte_array_from_basenb_utf8("\u{f809}".as_bytes()).unwrap();
472        assert!(
473            is_sentinel(&dec),
474            "Expected sentinel for empty input decode; got {:?}",
475            dec
476        );
477    }
478
479    #[crate::ctb_test]
480    fn test_round_trip_base17_small_samples() {
481        let samples: Vec<Vec<u8>> = vec![
482            vec![0u8],
483            vec![1, 2, 3],
484            vec![255],
485            b"hello".to_vec(),
486            b"\x00\x01\x02\x03\xFE\xFF".to_vec(),
487            (0u8..32u8).collect(),
488        ];
489
490        for sample in samples {
491            let enc = byte_array_to_basenb_17_utf8(&sample).unwrap();
492            crate::log!(
493                "Sample {:?} encoded to Basenb 17 UTF-8 bytes: {:?}",
494                sample.clone(),
495                enc.clone()
496            );
497            let dec = byte_array_from_basenb_17_utf8(&enc).unwrap();
498            if is_sentinel(&dec) && !sample.is_empty() {
499                panic!(
500                    "Unexpected sentinel for non-empty sample {:?} (encoded {:?})",
501                    sample, enc
502                );
503            }
504            if !sample.is_empty() {
505                assert_vec_u8_eq(&sample, &dec);
506            }
507        }
508    }
509
510    #[crate::ctb_test]
511    fn test_basenb_encode_uuid() {
512        // e82eef60-19bc-4a00-a44a-763a3445c16f
513        let input: Vec<u8> = vec![
514            0xe8, 0x2e, 0xef, 0x60, //
515            0x19, 0xbc, 0x4a, 0x00, //
516            0xa4, 0x4a, 0x76, 0x3a, //
517            0x34, 0x45, 0xc1, 0x6f,
518        ];
519
520        // Working out the remainder byte by hand:
521        // 16 bytes * 8 bits = 128 bits
522        // 128 % 17 = 9
523        // The last remainder codepoint is U+F809, - 9 = U+F800.
524
525        let expected_uuid = DC_BASENB_EMBEDDED_START_BYTES.to_vec();
526        let remainder = "\u{F800}".as_bytes().to_vec();
527        let expected = [expected_uuid, remainder].concat();
528
529        let enc = assert_vec_u8_ok_eq(
530            &expected,
531            byte_array_to_basenb_17_utf8(&input),
532        );
533
534        let dec = byte_array_from_basenb_17_utf8(&enc).unwrap();
535        if is_sentinel(&dec) && !input.is_empty() {
536            panic!(
537                "Unexpected exception UUID for {:?} (encoded {:?})",
538                input, enc
539            );
540        }
541
542        assert_vec_u8_eq(&input, &dec);
543    }
544
545    #[crate::ctb_test]
546    fn test_armored_round_trip() {
547        let payload = b"Hello Base17b Armored!";
548        let armored = byte_array_to_armored_base17b_utf8(payload).unwrap();
549        // Basic framing checks
550        let start = ARMORED_BASE17B_UTF8_START_UUID_BYTES;
551        let end = ARMORED_BASE17B_UTF8_END_UUID_BYTES;
552        assert!(armored.starts_with(&start));
553        assert!(armored.ends_with(&end));
554
555        let decoded = byte_array_from_armored_base17b_utf8(&armored);
556        assert_vec_u8_ok_eq(payload, decoded);
557    }
558
559    #[crate::ctb_test]
560    fn test_armored_invalid_prefix() {
561        let payload = b"xyz";
562        let mut armored = byte_array_to_armored_base17b_utf8(payload).unwrap();
563        // Corrupt first byte
564        armored[0] ^= 0xFF;
565        let err = byte_array_from_armored_base17b_utf8(&armored).unwrap_err();
566        assert!(
567            err.to_string().contains("missing or corrupt start UUID"),
568            "Unexpected error: {err}"
569        );
570    }
571
572    #[crate::ctb_test]
573    fn test_armored_invalid_suffix() {
574        let payload = b"xyz";
575        let mut armored = byte_array_to_armored_base17b_utf8(payload).unwrap();
576        // Corrupt last byte
577        let last = armored
578            .len()
579            .checked_sub(1)
580            .expect("armored array is empty");
581        armored[last] ^= 0xAA;
582        let err = byte_array_from_armored_base17b_utf8(&armored).unwrap_err();
583        assert!(
584            err.to_string().contains("missing or corrupt end UUID"),
585            "Unexpected error: {err}"
586        );
587    }
588
589    #[crate::ctb_test]
590    fn test_armored_too_short() {
591        let data: Vec<u8> = vec![1, 2, 3, 4]; // shorter than any plausible framing
592        let err = byte_array_from_armored_base17b_utf8(&data).unwrap_err();
593        assert!(
594            err.to_string().contains("too short"),
595            "Unexpected error: {err}"
596        );
597    }
598}