ctb_formats_base16b/
base16b.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later AND MIT
2// SPDX-License-Identifier for parts derived from Base16b: MIT
3/*
4This file is part of Collective Toolbox, a database and document workspace and utilities.
5Copyright (C) 2026 Collective Toolbox Developers
6Contact: info@collectivetoolbox.com
7
8This program is free software: you can redistribute it and/or modify it under
9the terms of the GNU Affero General Public License as published by the Free
10Software Foundation, either version 3 of the License, or (at your option) any
11later version.
12
13This program is distributed in the hope that it will be useful, but WITHOUT ANY
14WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
16
17You should have received a copy of the GNU Affero General Public License along
18with this program.  If not, see <https://www.gnu.org/licenses/>.
19*/
20
21/* Copyright © 2009 Base16b.org */
22
23/* Based on https://web.archive.org/web/20090902074623/http://www.base16b.org/doc/specification/version/0.1/base16b.pdf */
24
25// This code for the Base16b object is included under the following license:
26/*
27 * Base16b family encode / decode
28 * http://base16b.org/lib/version/0.1/js/base16b.js
29 * or http://base16b.org/lib/js/base16b.js
30 */
31/*
32    Copyright (c) 2009 Base16b.org
33    Permission is hereby granted, free of charge, to any person
34    obtaining a copy of this software and associated documentation
35    files (the "Software"), to deal in the Software without
36    restriction, including without limitation the rights to use,
37    copy, modify, merge, publish, distribute, sublicense, and/or sell
38    copies of the Software, and to permit persons to whom the
39    Software is furnished to do so, subject to the following
40    conditions:
41    The above copyright notice and this permission notice shall be
42    included in all copies or substantial portions of the Software.
43    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
44    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
45    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
46    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
47    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
48    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
49    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
50    OTHER DEALINGS IN THE SOFTWARE.
51*/
52
53//! Implements the Base16b format.
54//!
55//! Based on
56//! <https://web.archive.org/web/20090902074623/http://www.base16b.org/doc/specification/version/0.1/base16b.pdf>
57//! Note that the Base16b and Basenb formats provided here are different from
58//! the Base16b formats in the specification, due to what appears to be a bug in
59//! the specification (requiring the remainder length to be stored to decode the
60//! remainder correctly when it starts with a 0 bit and is not 16 bits long).
61
62#[allow(
63    unused_imports,
64    clippy::wildcard_imports,
65    reason = "Standard workspace crate prelude"
66)]
67pub(crate) use ctb_utilities::*;
68
69use anyhow::{Result, bail};
70
71use crate::bail_if_none;
72use ctb_utilities::circular_dep_unicode::{
73    js_like_slice_utf16, string_to_scalars, ucs2encode,
74};
75
76#[derive(Debug, Clone, Copy)]
77struct CpValue {
78    value: u32,
79    cp: u32,
80}
81
82// Private constants
83// +UF0000 is the first code point in the Asyntactic script
84const AS_START: CpValue = CpValue {
85    value: 0x0000,
86    cp: 0xF0000,
87};
88
89// Private non-contiguous code points
90fn noncont() -> [CpValue; 4] {
91    [
92        CpValue {
93            value: 0xFFFE,
94            cp: 0xF80A,
95        },
96        CpValue {
97            value: 0xFFFF,
98            cp: 0xF80B,
99        },
100        CpValue {
101            value: 0x1FFFE,
102            cp: 0xF80C,
103        },
104        CpValue {
105            value: 0x1FFFF,
106            cp: 0xF80D,
107        },
108    ]
109}
110
111// Private: bytes needed for a character (usually 2)
112fn char_bytes(segm_cp: &[u16]) -> usize {
113    if fixed_char_code_at(segm_cp, 0).is_ok()
114        && fixed_char_code_at(segm_cp, 1).is_ok()
115    {
116        2
117    } else {
118        1
119    }
120}
121
122// Private: bytes needed for a character (fixed surrogate logic)
123fn char_bytes_fixed(segm_cp: &[u16]) -> u8 {
124    // Reason for fallback: when slice is empty, first code point is None (code = 0), which is not a UTF-16 surrogate (0xD800..=0xDFFF), returning 1 byte.
125    let code = segm_cp.first().copied().unwrap_or(0);
126    if (0xD800..=0xDBFF).contains(&code) || (0xDC00..=0xDFFF).contains(&code) {
127        2
128    } else {
129        1
130    }
131}
132
133// Private: Two's complement for the value for this base
134fn invert_val(segm_val: u32, base: u32) -> u32 {
135    2u32.pow(base).saturating_sub(segm_val.saturating_add(1))
136}
137
138// Private: from code point to value
139fn from_code_point(segm_cp: &[u16], bytes: u8) -> Result<u32> {
140    // Map Code Point to a segment value as specified by the mapping table for this base in the Asyntactic script
141    let code = fixed_char_code_at(segm_cp, 0)?;
142    if bytes == 2 {
143        return Ok(code.saturating_sub(AS_START.cp));
144    }
145    for nc in &noncont() {
146        // handle non-contiguous code points for last two CPs in bases 16
147        // and 17
148        if nc.cp == code {
149            return Ok(nc.value);
150        }
151    }
152    bail!(format!("from_code_point: unknown code point {segm_cp:?}"))
153}
154
155// Private: value to code point
156fn to_code_point(segm_val: u32, base: u32) -> u32 {
157    // Map a segment value to the Code Point specified by the mapping table for this base in the Asyntactic script
158    if base < 16 {
159        AS_START.cp.saturating_add(segm_val)
160    } else {
161        for nc in &noncont() {
162            // handle non-contiguous code points for bases 16 and 17
163            if nc.value == segm_val {
164                return nc.cp;
165            }
166        }
167        AS_START.cp.saturating_add(segm_val)
168    }
169}
170
171// Private: code point to String (fixed surrogate logic)
172fn fixed_from_char_code(code_pt: u32) -> String {
173    // Reason for fallback: when code point is not a valid Unicode scalar value, format standard replacement character '\u{FFFD}'.
174    std::char::from_u32(code_pt)
175        .map_or_else(|| String::from("\u{FFFD}"), |c| c.to_string())
176}
177
178// Private: get the code point at a string index (surrogate aware)
179fn fixed_char_code_at(str_: &[u16], idx: usize) -> Result<u32> {
180    // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/charCodeAt
181    if idx >= str_.len() {
182        return Err(anyhow::anyhow!("index out of bounds"));
183    }
184    let code = u32::from(*str_.get(idx).context("index out of bounds")?);
185    if (0xD800..=0xDBFF).contains(&code) {
186        // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters)
187        let next_idx = idx.saturating_add(1);
188        if next_idx < str_.len() {
189            let hi = code;
190            let low =
191                u32::from(*str_.get(next_idx).context("index out of bounds")?);
192            let val = hi
193                .saturating_sub(0xD800)
194                .saturating_mul(0x400)
195                .saturating_add(low.saturating_sub(0xDC00))
196                .saturating_add(0x10000);
197            return Ok(val);
198        }
199    }
200    if (0xDC00..=0xDFFF).contains(&code) {
201        // Low surrogate
202        if idx >= 1 {
203            let prev_idx = idx.saturating_sub(1);
204            let hi =
205                u32::from(*str_.get(prev_idx).context("index out of bounds")?);
206            let low = code;
207            let val = hi
208                .saturating_sub(0xD800)
209                .saturating_mul(0x400)
210                .saturating_add(low.saturating_sub(0xDC00))
211                .saturating_add(0x10000);
212            return Ok(val);
213        }
214    }
215    Ok(code)
216}
217
218/// Encode an array of pseudo-booleans (0 or 1) to a string using the
219/// Asyntactic script.
220pub fn encode(input_arr: &[u8], base: u32) -> Result<String> {
221    /*
222    Encode an array of pseudo-booleans (0 or 1)
223    The specification of the encoding is documented elsewhere on this site. (Search Asyntactic script and Base16b.)
224
225    See `byte_array_to_int_bit_array` and other functions in bitwise.rs for
226    converting to and from these arrays of bits.
227    */
228    if !(7..=17).contains(&base) {
229        bail!("invalid base".to_string());
230    }
231    let base_usize = usize::try_from(base)?;
232    let mut result_arr: Vec<String> = Vec::new();
233    #[expect(
234        clippy::expect_used,
235        reason = "base_usize is in 7..=17, so division by zero is impossible"
236    )]
237    let full_segments = input_arr
238        .len()
239        .checked_div(base_usize)
240        .expect("base_usize is non-zero (7..=17)");
241    let remain_bits = input_arr
242        .len()
243        .saturating_sub(full_segments.saturating_mul(base_usize));
244    for segment in 0..full_segments {
245        let segmstart = base_usize.saturating_mul(segment);
246        let segmend = segmstart.saturating_add(base_usize);
247        let currsegm = input_arr
248            .get(segmstart..segmend)
249            .context("Invalid segment range")?;
250        let mut segm_val = 0u32;
251        for (bit_idx, &b) in currsegm.iter().enumerate() {
252            let shift = u32::try_from(
253                base_usize.saturating_sub(1).saturating_sub(bit_idx),
254            )?;
255            #[expect(
256                clippy::expect_used,
257                reason = "shift is < 17, so 32-bit shift cannot overflow"
258            )]
259            let bit_val = u32::from(b)
260                .checked_shl(shift)
261                .expect("shift is < 17, which fits in u32");
262            segm_val = segm_val.saturating_add(bit_val);
263        }
264        let cp = to_code_point(segm_val, base);
265        result_arr.push(fixed_from_char_code(cp));
266    }
267    // encode termination character
268    let segmstart = base_usize.saturating_mul(full_segments);
269    let currsegm = input_arr
270        .get(segmstart..)
271        .context("Invalid remainder range")?;
272    // most significant bit at the start (left) / least significant bit at
273    // the end (right).
274    let mut segm_val = 0u32;
275    if remain_bits > 0 {
276        for (bit_idx, &b) in currsegm.iter().enumerate() {
277            let shift = u32::try_from(
278                remain_bits.saturating_sub(1).saturating_sub(bit_idx),
279            )?;
280            #[expect(
281                clippy::expect_used,
282                reason = "shift is < remain_bits <= 17, so 32-bit shift cannot overflow"
283            )]
284            let bit_val = u32::from(b)
285                .checked_shl(shift)
286                .expect("shift is < 17, which fits in u32");
287            segm_val = segm_val.saturating_add(bit_val);
288        }
289    }
290    let term_cp = to_code_point(invert_val(segm_val, base), base);
291    result_arr.push(fixed_from_char_code(term_cp));
292    Ok(result_arr.concat())
293}
294
295/// Decode a string encoded in the Asyntactic script. Return an array of
296/// pseudo-booleans (0 or 1).
297///
298/// remainderLength is not in the original version of this code. It should
299/// be provided to get round-trip output. It is the input length in bits,
300/// mod the number of bits per character (the second argument to the encode
301/// function). Other fixes to decoding are also made if remainderLength is
302/// provided. If it is not provided, the output should be the same as with
303/// original API (if not, that's a bug) - WITH THE EXCEPTION that in some
304/// cases the original version sometimes returned NaN for some bits. See the
305/// tests for an example. I haven't looked into why that is.
306///
307/// Pass None as the `remainder_length` to use per the original API.
308pub fn decode(
309    input_str: &str,
310    remainder_length: Option<u32>,
311) -> Result<Vec<u8>> {
312    let input_str = ucs2encode(&string_to_scalars(input_str))?;
313    let original_api = remainder_length.is_none();
314    let mut result_arr: Vec<u8> = Vec::new();
315    let term_char_bytes_slice = input_str
316        .get(input_str.len().saturating_sub(1)..)
317        .context("Empty input string")?;
318    let term_char_bytes = char_bytes_fixed(term_char_bytes_slice);
319    let term_char_bytes_usize: usize = term_char_bytes.into();
320    let term_char_cp_slice = input_str
321        .get(input_str.len().saturating_sub(term_char_bytes_usize)..)
322        .context("Invalid termination character range")?;
323    let term_char_val = from_code_point(term_char_cp_slice, term_char_bytes)?;
324    let mut bit: u32 = 17;
325    // decode the base from the termination character
326    while bit >= 7 {
327        let bit_minus_1 = bit.saturating_sub(1);
328        let divisor = 2u32.pow(bit_minus_1);
329        #[expect(
330            clippy::expect_used,
331            reason = "divisor is 2^(bit-1) >= 64, which is non-zero"
332        )]
333        let div_result = term_char_val
334            .checked_div(divisor)
335            .expect("divisor is non-zero power of 2");
336        if div_result != 0 {
337            break;
338        }
339        bit = bit.saturating_sub(1);
340    }
341    let base: u32 = if (7..=17).contains(&bit) {
342        bit
343    } else {
344        bail!("invalid base decoded");
345    };
346    let mut bytes_used: usize = 0;
347    let full_bytes = input_str.len().saturating_sub(term_char_bytes_usize);
348    while bytes_used < full_bytes {
349        // decode the code point segments in sequence
350        let slice_for_bytes = input_str
351            .get(bytes_used..=bytes_used)
352            .context("Invalid bytes used range")?;
353        let curr_char_bytes = char_bytes_fixed(slice_for_bytes); // taste before taking a byte
354        let curr_char_bytes_usize: usize = curr_char_bytes.into();
355        let segment_bit_length: u32 = if original_api {
356            u32::from(curr_char_bytes).saturating_mul(8)
357        } else {
358            base
359        };
360        let seg_end = bytes_used.saturating_add(curr_char_bytes_usize);
361        let segment = input_str
362            .get(bytes_used..seg_end)
363            .context("Invalid segment index")?;
364        let segm_val = from_code_point(segment, curr_char_bytes)?;
365        // most significant bit at the start (left) / least significant bit at the end (right).
366        let sbl_usize = usize::try_from(segment_bit_length)?;
367        for bit_pos_usize in (0..sbl_usize).rev() {
368            let bit_pos = u32::try_from(bit_pos_usize)?;
369            let divisor = 2u64.pow(bit_pos);
370            #[expect(
371                clippy::expect_used,
372                reason = "divisor is 2^bit_pos >= 1, which is non-zero"
373            )]
374            let div_val = u64::from(segm_val)
375                .checked_div(divisor)
376                .expect("divisor is non-zero power of 2");
377            let raw: u32 = u32::try_from(div_val.rem_euclid(2))?;
378            let decoded_bit = u8::try_from(raw)?;
379            if !original_api && decoded_bit > 1 {
380                bail!("Found incorrect bit while decoding");
381            }
382            result_arr.push(decoded_bit);
383        }
384        bytes_used = bytes_used.saturating_add(curr_char_bytes_usize);
385    }
386    // remainder
387    let remain_val = invert_val(term_char_val, base); // decode the remainder from the termination character
388    let mut bit: i16 =
389        i16::from(term_char_bytes.saturating_mul(8)).saturating_sub(1);
390    if (bit > 0) && !original_api {
391        let rem_len = bail_if_none!(remainder_length);
392        bit = i16::try_from(rem_len)?.saturating_sub(1);
393    }
394    if bit >= 0 {
395        while bit >= 0 {
396            let bit_u32: u32 = bit.try_into()?;
397            let divisor = 2u32.pow(bit_u32);
398            #[expect(
399                clippy::expect_used,
400                reason = "divisor is 2^bit_u32 >= 1, which is non-zero"
401            )]
402            let div_val = remain_val
403                .checked_div(divisor)
404                .expect("divisor is non-zero power of 2");
405            let bit_val = u8::try_from(div_val.rem_euclid(2))?;
406            result_arr.push(bit_val);
407            bit = bit.saturating_sub(1);
408        }
409    }
410    Ok(result_arr)
411}
412
413/// Public: count Unicode characters in the way Base16b does
414pub fn true_length(input_str: &str) -> Result<usize> {
415    /*
416    Count the number of characters in a string.
417    This function can handle stings of mixed BMP plane and higher Unicode planes.
418    Fixes a problem with Javascript which incorrectly that assumes each character is only one byte.
419    */
420    let str_bytes = ucs2encode(&string_to_scalars(input_str))?.len();
421    let mut str_length: usize = 0;
422    let mut tally_bytes: usize = 0;
423    while tally_bytes < str_bytes {
424        let slice_end = if tally_bytes.saturating_add(2) > input_str.len() {
425            input_str.len()
426        } else {
427            tally_bytes.saturating_add(2)
428        };
429        // select utf-16 slices. This will sometimes index into the middle
430        // of surrogate pairs.
431        let slice = js_like_slice_utf16(input_str, tally_bytes, slice_end);
432        let char_bytes = char_bytes(&slice);
433        tally_bytes = tally_bytes.saturating_add(char_bytes);
434        str_length = str_length.saturating_add(1);
435    }
436    Ok(str_length)
437}
438
439#[cfg(test)]
440#[allow(
441    clippy::panic,
442    clippy::expect_used,
443    clippy::unwrap_used,
444    clippy::unwrap_in_result,
445    clippy::panic_in_result_fn,
446    clippy::indexing_slicing,
447    clippy::arithmetic_side_effects,
448    reason = "Standard repository test boilerplate"
449)]
450mod tests {
451    use super::*;
452
453    use crate::utilities::assert_vec_u8_ok_eq;
454    use ctb_formats_utilities::assert_string_ok_eq;
455
456    #[crate::ctb_test]
457    fn test_char_bytes() {
458        assert_eq!(char_bytes(&"a".encode_utf16().collect::<Vec<u16>>()), 1);
459        assert_eq!(char_bytes(&"𠜎".encode_utf16().collect::<Vec<u16>>()), 2);
460        assert_eq!(char_bytes(&"🥴".encode_utf16().collect::<Vec<u16>>()), 2);
461    }
462
463    #[crate::ctb_test]
464    fn test_true_length() {
465        assert_eq!(true_length("aa").unwrap(), 1);
466        assert_eq!(true_length("a𠜎").unwrap(), 2);
467        assert_eq!(true_length("a🥴").unwrap(), 2);
468    }
469
470    #[crate::ctb_test]
471
472    fn test_encode_decode() {
473        // This is UUID e82eef60-19bc-4a00-a44a-763a3445c16f as bits
474        // To convert:
475        // ctoolbox base2base 2 2 -q --limit 1 --pad --separator ', ' "$(ctoolbox base2base 16 2 -q --limit 255 --pad --separator ', ' 'e82eef60-19bc-4a00-a44a-763a3445c16f')"
476        let input = vec![
477            1, 1, 1, 0, 1, 0, 0, 0, //
478            0, 0, 1, 0, 1, 1, 1, 0, //
479            1, 1, 1, 0, 1, 1, 1, 1, //
480            0, 1, 1, 0, 0, 0, 0, 0, //
481            0, 0, 0, 1, 1, 0, 0, 1, //
482            1, 0, 1, 1, 1, 1, 0, 0, //
483            0, 1, 0, 0, 1, 0, 1, 0, //
484            0, 0, 0, 0, 0, 0, 0, 0, //
485            1, 0, 1, 0, 0, 1, 0, 0, //
486            0, 1, 0, 0, 1, 0, 1, 0, //
487            0, 1, 1, 1, 0, 1, 1, 0, //
488            0, 0, 1, 1, 1, 0, 1, 0, //
489            0, 0, 1, 1, 0, 1, 0, 0, //
490            0, 1, 0, 0, 0, 1, 0, 1, //
491            1, 1, 0, 0, 0, 0, 0, 1, //
492            0, 1, 1, 0, 1, 1, 1, 1,
493        ];
494        let expected7 = "\u{f0074}\u{f000b}\u{f005d}\u{f0076}\u{f0000}\u{f0066}\u{f0078}\u{f004a}\u{f0000}\u{f0029}\u{f0009}\u{f0027}\u{f0031}\u{f0068}\u{f0068}\u{f0045}\u{f0060}\u{f005b}\u{f007c}";
495        let expected8 = "\u{f00e8}\u{f002e}\u{f00ef}\u{f0060}\u{f0019}\u{f00bc}\u{f004a}\u{f0000}\u{f00a4}\u{f004a}\u{f0076}\u{f003a}\u{f0034}\u{f0045}\u{f00c1}\u{f006f}\u{f00ff}";
496        let expected9 = "\u{f01d0}\u{f00bb}\u{f017b}\u{f0001}\u{f0137}\u{f0112}\u{f0100}\u{f00a4}\u{f0094}\u{f01d8}\u{f01d1}\u{f0144}\u{f00b8}\u{f005b}\u{f01fc}";
497        let expected10 = "\u{f03a0}\u{f02ee}\u{f03d8}\u{f0019}\u{f02f1}\u{f00a0}\u{f0029}\u{f004a}\u{f01d8}\u{f03a3}\u{f0111}\u{f01c1}\u{f0390}";
498        let expected11 = "\u{f0741}\u{f03bb}\u{f06c0}\u{f019b}\u{f0625}\u{f0002}\u{f0489}\u{f0276}\u{f01d1}\u{f0511}\u{f0382}\u{f0790}";
499        let expected12 = "\u{f0e82}\u{f0eef}\u{f0601}\u{f09bc}\u{f04a0}\u{f00a4}\u{f04a7}\u{f063a}\u{f0344}\u{f05c1}\u{f0f90}";
500        let expected13 = "\u{f1d05}\u{f1bbd}\u{f100c}\u{f1bc4}\u{f1401}\u{f0912}\u{f13b1}\u{f1a34}\u{f08b8}\u{f1e90}";
501        let expected14 = "\u{f3a0b}\u{f2ef6}\u{f0066}\u{f3c4a}\u{f0029}\u{f04a7}\u{f18e8}\u{f3445}\u{f305b}\u{f3ffc}";
502        let expected15 = "\u{f7417}\u{f3bd8}\u{f0337}\u{f44a0}\u{f0522}\u{f29d8}\u{f7468}\u{f45c1}\u{f7f90}";
503        let expected16 = "\u{fe82e}\u{fef60}\u{f19bc}\u{f4a00}\u{fa44a}\u{f763a}\u{f3445}\u{fc16f}\u{f80b}";
504        let expected17 = "\u{10d05d}\u{10bd80}\u{fcde2}\u{fa00a}\u{f894e}\u{108e8d}\u{f22e0}\u{10fe90}";
505
506        encode(&input, 6).unwrap_err();
507        encode(&input, 18).unwrap_err();
508        let result7 = assert_string_ok_eq(expected7, encode(&input, 7));
509        let result8 = assert_string_ok_eq(expected8, encode(&input, 8));
510        let result9 = assert_string_ok_eq(expected9, encode(&input, 9));
511        let result10 = assert_string_ok_eq(expected10, encode(&input, 10));
512        let result11 = assert_string_ok_eq(expected11, encode(&input, 11));
513        let result12 = assert_string_ok_eq(expected12, encode(&input, 12));
514        let result13 = assert_string_ok_eq(expected13, encode(&input, 13));
515        let result14 = assert_string_ok_eq(expected14, encode(&input, 14));
516        let result15 = assert_string_ok_eq(expected15, encode(&input, 15));
517        let result16 = assert_string_ok_eq(expected16, encode(&input, 16));
518        let result17 = assert_string_ok_eq(expected17, encode(&input, 17));
519
520        decode("abcd", None).unwrap_err();
521
522        let input_len = u32::try_from(input.len()).unwrap();
523        assert_vec_u8_ok_eq(&input, decode(&result7, Some(input_len % 7)));
524        assert_vec_u8_ok_eq(&input, decode(&result8, Some(input_len % 8)));
525        assert_vec_u8_ok_eq(&input, decode(&result9, Some(input_len % 9)));
526        assert_vec_u8_ok_eq(&input, decode(&result10, Some(input_len % 10)));
527        assert_vec_u8_ok_eq(&input, decode(&result11, Some(input_len % 11)));
528        assert_vec_u8_ok_eq(&input, decode(&result12, Some(input_len % 12)));
529        assert_vec_u8_ok_eq(&input, decode(&result13, Some(input_len % 13)));
530        assert_vec_u8_ok_eq(&input, decode(&result14, Some(input_len % 14)));
531        assert_vec_u8_ok_eq(&input, decode(&result15, Some(input_len % 15)));
532        assert_vec_u8_ok_eq(&input, decode(&result16, Some(input_len % 16)));
533        assert_vec_u8_ok_eq(&input, decode(&result17, Some(input_len % 17)));
534
535        #[rustfmt::skip]
536        let no_remainder_res7 = &[0,0,0,0,0,0,0,0,0,1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,0,0,1,0,1,1,1,0,1,0,0,0,0,0,0,0,0,0,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1];
537        #[rustfmt::skip]
538        let no_remainder_res8 = &[0,0,0,0,0,0,0,0,1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,1,0,1,1,1,1,0,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0,0,1,0,1,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,1];
547        #[rustfmt::skip]
548        let no_remainder_res13 = &[0,0,0,1,1,1,0,1,0,0,0,0,0,1,0,1,0,0,0,1,1,0,1,1,1,0,1,1,1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,1,1,0,1,1,1,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,0,0,1,0,0,1,1,1,0,1,1,0,0,0,1,0,0,0,1,1,0,1,0,0,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,1,0,1,1,1,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,1,1,1];
549        #[rustfmt::skip]
550        let no_remainder_res14 = &[0,0,1,1,1,0,1,0,0,0,0,0,1,0,1,1,0,0,1,0,1,1,1,0,1,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0,1,1,1,1,0,0,0,1,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,1,0,0,0,0,0,1,0,0,1,0,1,0,0,1,1,1,0,0,0,1,1,0,0,0,1,1,1,0,1,0,0,0,0,0,1,1,0,1,0,0,0,1,0,0,0,1,0,1,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1];
551        #[rustfmt::skip]
552        let no_remainder_res15 = &[0,1,1,1,0,1,0,0,0,0,0,1,0,1,1,1,0,0,1,1,1,0,1,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,1,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,1,0,0,0,1,0,0,0,1,0,1,0,0,1,1,1,0,1,1,0,0,0,0,1,1,1,0,1,0,0,0,1,1,0,1,0,0,0,0,1,0,0,0,1,0,1,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,1];
553        // NOTE: The original returns NaN for some bits:
554        // I haven't looked into why.
555        // let no_remainder_res16 = &[1,1,1,0,1,0,0,0,0,0,1,0,1,1,1,0,1,1,1,0,1,1,1,1,0,1,1,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,1,1,1,1,0,0,0,1,0,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,0,1,0,0,0,1,1,0,1,0,0,0,1,0,0,0,1,0,1,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,0,0,0,0,0,0,0,0];
556        #[rustfmt::skip]
557        let no_remainder_res16 = &[1,1,1,0,1,0,0,0,0,0,1,0,1,1,1,0,1,1,1,0,1,1,1,1,0,1,1,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,1,1,1,1,0,0,0,1,0,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,0,1,0,0,0,1,1,0,1,0,0,0,1,0,0,0,1,0,1,1,1,0,0,0,0,0,1,0,1,1,0,1,1,1,1,0,0,0,0,0,0,0,0];
558        #[rustfmt::skip]
559        let no_remainder_res17 = &[1,1,0,1,0,0,0,0,0,1,0,1,1,1,0,1,1,0,1,1,1,1,0,1,1,0,0,0,0,0,0,0,1,1,0,0,1,1,0,1,1,1,1,0,0,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,1,0,1,0,0,0,1,1,1,0,1,0,0,0,1,1,0,1,0,0,1,0,0,0,1,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,1,1,1];
560        assert_vec_u8_ok_eq(no_remainder_res7, decode(&result7, None));
561        assert_vec_u8_ok_eq(no_remainder_res8, decode(&result8, None));
562        assert_vec_u8_ok_eq(no_remainder_res9, decode(&result9, None));
563        assert_vec_u8_ok_eq(no_remainder_res10, decode(&result10, None));
564        assert_vec_u8_ok_eq(no_remainder_res11, decode(&result11, None));
565        assert_vec_u8_ok_eq(no_remainder_res12, decode(&result12, None));
566        assert_vec_u8_ok_eq(no_remainder_res13, decode(&result13, None));
567        assert_vec_u8_ok_eq(no_remainder_res14, decode(&result14, None));
568        assert_vec_u8_ok_eq(no_remainder_res15, decode(&result15, None));
569        assert_vec_u8_ok_eq(no_remainder_res16, decode(&result16, None));
570        assert_vec_u8_ok_eq(no_remainder_res17, decode(&result17, None));
571
572        // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
573        let input: Vec<u8> = vec![
574            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, //
575            0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, //
576            0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, //
577            0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, //
578            0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, //
579            0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, //
580            0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, //
581            0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, //
582            0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, //
583            0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, //
584            0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, //
585            0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, //
586            0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, //
587            0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, //
588            0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, //
589            0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1,
590        ];
591        let encoded = "\u{f0002}\u{f080c}\u{f2028}\u{f6070}\u{100121}\u{f82c3}\u{f0687}\u{f0f10}\u{f2224}\u{f4c50}\u{fa8b0}\u{107181}\u{102343}\u{fc707}\u{f8f0f}\u{f80c}";
592        let res = assert_string_ok_eq(encoded, encode(&input, 17));
593        crate::log!(res);
594        assert_vec_u8_ok_eq(
595            &input,
596            decode(&res, Some(u32::try_from(input.len() % 17).unwrap())),
597        );
598    }
599}