ctb_formats_eite/encoding/
base.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//! Base conversion
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use anyhow::{Result, anyhow, bail};
30
31use crate::encoding::ascii::{byte_from_stagel_char, stagel_char_from_byte};
32pub use ctb_formats_math::base::{
33    Base, BaseAlphabet, BaseConversionPaddingMode, BaseStringFormatSettings,
34    NumeralSystem, base_to_base_string, casefold_base_chars_in_string,
35    dec_to_hex_single, dec_to_hex_string, format_base_string,
36    get_digits_needed, hex_to_dec_single, hex_to_dec_string,
37    int_from_base_str_big, int_from_base_str_big_alphabet,
38    int_from_base_str_u32, int_from_base_str_u128, int_to_base_str,
39    int_to_base_str_big_alphabet, is_base_digit, is_base_digit_alphabet,
40    is_base_str, is_base_str_alphabet,
41    is_supported_base_with_default_alphabet as is_supported_base,
42};
43
44/// Convert two hex digits to a single byte -> char (StageL: charFromHexByte).
45/// StageL operated on bytes, not Unicode scalar validation beyond 0xFF.
46pub fn char_from_hex_byte(hex: &str) -> Result<char> {
47    if hex.len() != 2 {
48        return Err(anyhow!("Expected 2 hex digits, got {}", hex.len()));
49    }
50    let v = int_from_base_str_u32(hex, 16)?;
51    if v > 0xFF {
52        return Err(anyhow!("Hex byte out of range"));
53    }
54    char::from_u32(v)
55        .ok_or_else(|| anyhow!("Invalid Unicode scalar value: {v}"))
56}
57
58/// Returns the nth digit in base 36 or less (using capitalized digits).
59/// The original JS version had a bug where it would accept 36 as a base, when 0
60/// to 35 is expected (36 digits).
61///
62/// You probably want `BaseAlphabet::Standard.char_for_digit(n)` instead. This is conceptually similar, but returns an uppercase digit.
63pub fn int_to_base36_char(n: u8) -> Result<String> {
64    if !(0..=35).contains(&n) {
65        bail!("{n} is not within range 0..=35");
66    }
67    if n <= 9 {
68        stagel_char_from_byte(n.saturating_add(48))
69    } else {
70        stagel_char_from_byte(n.saturating_add(55))
71    }
72}
73
74/// Returns an int given the nth digit in base 36 or less (using capitalized digits).
75///
76/// You probably want `BaseAlphabet::Standard.digit_for_char(c)` instead. This is conceptually simlar, but does not accept lowercase digits.
77pub fn int_from_base36_char(ch: &str) -> Result<u8> {
78    // Validate input: must be a single character StageL string
79    if ch.len() != 1 {
80        bail!("'{ch}' is not a single StageL character");
81    }
82
83    // Convert to uppercase
84    let ch_uc = ch.to_ascii_uppercase();
85    let b = byte_from_stagel_char(&ch_uc)?;
86
87    let int_res = if b >= 65 {
88        if b > 90 {
89            bail!(
90                "'{ch_uc}' is not within the supported range of digits between 0 and Z (35)."
91            );
92        }
93        b.saturating_sub(55)
94    } else {
95        if !(48..=57).contains(&b) {
96            bail!(
97                "'{ch}' is not within the supported range of digits between 0 and Z (35)."
98            );
99        }
100        b.saturating_sub(48)
101    };
102
103    if !(0..=35).contains(&int_res) {
104        bail!("Internal error in int_from_base36_char called with n='{ch}'.");
105    }
106
107    Ok(int_res)
108}
109
110/*
111Maybe useful:
112
113fn u32_slice_as_bytes_le(values: &[u32]) -> Vec<u8> {
114    let mut out = Vec::with_capacity(values.len() * 4);
115    for &v in values {
116        out.extend_from_slice(&v.to_le_bytes());
117    }
118    out
119}
120
121fn u32_slice_as_bytes_be(values: &[u32]) -> Vec<u8> {
122    let mut out = Vec::with_capacity(values.len() * 4);
123    for &v in values {
124        out.extend_from_slice(&v.to_be_bytes());
125    }
126    out
127}
128 */
129
130#[cfg(test)]
131#[allow(
132    clippy::panic,
133    clippy::expect_used,
134    clippy::unwrap_used,
135    clippy::unwrap_in_result,
136    clippy::panic_in_result_fn,
137    clippy::indexing_slicing,
138    clippy::arithmetic_side_effects,
139    reason = "Standard repository test boilerplate"
140)]
141mod tests {
142    use ctb_formats_utilities::{
143        assert_string_ok_eq_no_errors, assert_string_ok_eq_no_warnings,
144    };
145
146    use super::*;
147
148    #[crate::ctb_test]
149    fn test_base36_digit_roundtrip() {
150        for n in 0..=35 {
151            let ch = int_to_base36_char(n).unwrap();
152            let v = int_from_base36_char(&ch).unwrap();
153            assert_eq!(n, v);
154        }
155        assert!(int_to_base36_char(36).is_err());
156    }
157
158    #[crate::ctb_test]
159    fn test_hex_conversion_examples() {
160        // Mirrors runTestsMath base conversion portion
161        let hex = dec_to_hex_single(9917).unwrap();
162        assert_eq!(hex, "26BD");
163        let dec = hex_to_dec_single("26BD").unwrap();
164        assert_eq!(dec, 9917);
165    }
166
167    #[crate::ctb_test]
168    fn test_char_from_hex_byte() {
169        assert_eq!(char_from_hex_byte("41").unwrap(), 'A');
170        assert_eq!(char_from_hex_byte("7f").unwrap(), '\u{007F}');
171        assert!(char_from_hex_byte("XYZ").is_err());
172    }
173
174    #[crate::ctb_test]
175    fn test_base_to_base_string() {
176        let format_settings = BaseStringFormatSettings::default();
177        assert_string_ok_eq_no_warnings(
178            "26",
179            base_to_base_string("1A", 16, 10, &format_settings),
180        );
181
182        let _result = assert_string_ok_eq_no_warnings(
183            "26 16 4",
184            base_to_base_string("0x1A, 0x10, 0x04", 16, 10, &format_settings),
185        );
186
187        let (_result, log) = assert_string_ok_eq_no_errors(
188            // This result doesn't make mathematical sense, as the outputs are
189            // base 10.
190            "0x26, 0x16, 0x4",
191            base_to_base_string(
192                "0x1A, 0x10, 0x04",
193                16,
194                10,
195                &BaseStringFormatSettings {
196                    separator: "".to_string(),
197                    filter_chars: false,
198                    parse_prefixes: false,
199                    ..Default::default()
200                },
201            ),
202        );
203        assert!(log.has_warnings());
204
205        assert_string_ok_eq_no_warnings(
206            "12",
207            base_to_base_string("10", 10, 8, &format_settings),
208        );
209
210        let (_result, log) = assert_string_ok_eq_no_errors(
211            "26,uuuu 4F,é 16, 4",
212            base_to_base_string(
213                "26,uuuu 4F,é 16, 0x04",
214                16,
215                16,
216                &BaseStringFormatSettings {
217                    separator: "".to_string(),
218                    filter_chars: false,
219                    ..Default::default()
220                },
221            ),
222        );
223        assert!(log.has_warnings());
224
225        assert_string_ok_eq_no_warnings(
226            "0x026!0x04f!0x016!0x004",
227            base_to_base_string(
228                "26, 4F, 16, 0x04",
229                16,
230                16,
231                &BaseStringFormatSettings {
232                    prefix: "0x".to_string(),
233                    separator: "!".to_string(),
234                    lowercase: true,
235                    pad: BaseConversionPaddingMode {
236                        pad_l: 3,
237                        pad_fit: false,
238                    },
239                    ..Default::default()
240                },
241            ),
242        );
243
244        assert_string_ok_eq_no_warnings(
245            "0x26!0x4F!0x16!0x04",
246            base_to_base_string(
247                "26, 4F, 16, 0x04",
248                16,
249                16,
250                &BaseStringFormatSettings {
251                    prefix: "0x".to_string(),
252                    separator: "!".to_string(),
253                    lowercase: false,
254                    limit: u64::from(u8::MAX),
255                    pad: BaseConversionPaddingMode {
256                        pad_l: 0,
257                        pad_fit: true,
258                    },
259                    ..Default::default()
260                },
261            ),
262        );
263
264        let (_result, log) = assert_string_ok_eq_no_errors(
265            "26 4 16",
266            format_base_string(
267                "26, 4F, 16",
268                10,
269                &BaseStringFormatSettings::default(),
270            ),
271        );
272        assert!(log.has_warnings());
273
274        assert_string_ok_eq_no_warnings(
275            "26, 4F, 16, F, 0",
276            format_base_string(
277                "0x26, 4f, 16f, 0",
278                16,
279                &BaseStringFormatSettings {
280                    separator: ", ".to_string(),
281                    limit: 255,
282                    ..Default::default()
283                },
284            ),
285        );
286
287        assert_string_ok_eq_no_warnings(
288            "2 6 4 F 1 6",
289            format_base_string(
290                "0x26, 4f, 16",
291                16,
292                &BaseStringFormatSettings {
293                    limit: 1,
294                    ..Default::default()
295                },
296            ),
297        );
298    }
299
300    #[crate::ctb_test]
301    fn test_format_base_string() {
302        let (_result, log) = assert_string_ok_eq_no_errors(
303            "26 0 4F 0 16F",
304            format_base_string(
305                "26, 0n4F, 0x16fZz",
306                16,
307                &BaseStringFormatSettings {
308                    parse_prefixes: false,
309                    ..Default::default()
310                },
311            ),
312        );
313        assert!(log.has_warnings());
314
315        let (_result, log) = assert_string_ok_eq_no_errors(
316            "0x26!, 0x0!n0x4f!, 0x0!x0x16f!Zz",
317            format_base_string(
318                "26, 0n4F, 0x16fZz",
319                16,
320                &BaseStringFormatSettings {
321                    prefix: "0x".to_string(),
322                    separator: "!".to_string(),
323                    lowercase: true,
324                    parse_prefixes: false,
325                    filter_chars: false,
326                    ..Default::default()
327                },
328            ),
329        );
330        assert!(log.has_warnings());
331    }
332
333    #[crate::ctb_test]
334    fn test_collapse_filtered() {
335        let settings = BaseStringFormatSettings {
336            collapse_filtered: true,
337            ..Default::default()
338        };
339        // "10_000" should collapse '_' and parse as "10000"
340        let res = base_to_base_string("10_0!00", 10, 10, &settings);
341        let (res, log) = res.expect("Error");
342        assert_eq!("10000", res);
343        assert!(log.has_warnings());
344    }
345
346    #[crate::ctb_test]
347    fn test_collapse_only() {
348        let settings = BaseStringFormatSettings {
349            collapse_only: vec!["_".to_string()],
350            filter_chars: true,
351            ..Default::default()
352        };
353        // "10_000" should collapse '_' and parse as "10000", leaving other filtered chars as spaces
354        assert_string_ok_eq_no_warnings(
355            "10000",
356            base_to_base_string("10_000", 10, 10, &settings),
357        );
358        let conv = base_to_base_string("10_000!", 10, 10, &settings);
359        assert!(conv.is_ok());
360        let (conv, log) = conv.expect("checked");
361        assert_eq!("10000", conv);
362        assert!(log.has_warnings());
363    }
364
365    #[crate::ctb_test]
366    fn test_base64_alphabet_digits() {
367        let alpha = BaseAlphabet::Base64Standard;
368        assert_eq!(alpha.char_for_digit(0).unwrap(), 'A');
369        assert_eq!(alpha.char_for_digit(25).unwrap(), 'Z');
370        assert_eq!(alpha.char_for_digit(26).unwrap(), 'a');
371        assert_eq!(alpha.char_for_digit(51).unwrap(), 'z');
372        assert_eq!(alpha.char_for_digit(52).unwrap(), '0');
373        assert_eq!(alpha.char_for_digit(61).unwrap(), '9');
374        assert_eq!(alpha.char_for_digit(62).unwrap(), '+');
375        assert_eq!(alpha.char_for_digit(63).unwrap(), '/');
376        assert!(alpha.char_for_digit(64).is_err());
377
378        for d in 0..=63 {
379            let ch = alpha.char_for_digit(d).unwrap();
380            let parsed = alpha.digit_for_char(ch).unwrap();
381            assert_eq!(d, parsed);
382        }
383    }
384
385    #[crate::ctb_test]
386    fn test_base64_standard_conversion() {
387        // Base 10 (Standard) -> Base 64 (Base64Standard)
388        let dec_to_b64 = BaseStringFormatSettings {
389            input_alphabet: BaseAlphabet::Standard,
390            output_alphabet: BaseAlphabet::Base64Standard,
391            ..Default::default()
392        };
393        assert_string_ok_eq_no_warnings(
394            "A B / BA D/",
395            base_to_base_string("0 1 63 64 255", 10, 64, &dec_to_b64),
396        );
397
398        // Base 64 (Base64Standard) -> Base 10 (Standard)
399        let b64_to_dec = BaseStringFormatSettings {
400            input_alphabet: BaseAlphabet::Base64Standard,
401            output_alphabet: BaseAlphabet::Standard,
402            ..Default::default()
403        };
404        assert_string_ok_eq_no_warnings(
405            "0 1 63 64 255",
406            base_to_base_string("A B / BA D/", 64, 10, &b64_to_dec),
407        );
408
409        // Base 16 (Standard) -> Base 64 (Base64Standard)
410        let hex_to_b64 = BaseStringFormatSettings {
411            input_alphabet: BaseAlphabet::Standard,
412            output_alphabet: BaseAlphabet::Base64Standard,
413            ..Default::default()
414        };
415        assert_string_ok_eq_no_warnings(
416            "D/ EA",
417            base_to_base_string("ff 100", 16, 64, &hex_to_b64),
418        );
419
420        // Case sensitivity: 'a' is 26, 'A' is 0, '0' is 52
421        assert_string_ok_eq_no_warnings(
422            "26 0 52",
423            base_to_base_string("a A 0", 64, 10, &b64_to_dec),
424        );
425
426        // Zero-padding with 'A'
427        let pad_settings = BaseStringFormatSettings {
428            output_alphabet: BaseAlphabet::Base64Standard,
429            pad: BaseConversionPaddingMode {
430                pad_l: 4,
431                pad_fit: false,
432            },
433            ..Default::default()
434        };
435        assert_string_ok_eq_no_warnings(
436            "AAAF",
437            base_to_base_string("5", 10, 64, &pad_settings),
438        );
439
440        // Base 10 (Standard) -> Base 30 (Base64Standard)
441        let dec_to_b30_b64 = BaseStringFormatSettings {
442            input_alphabet: BaseAlphabet::Standard,
443            output_alphabet: BaseAlphabet::Base64Standard,
444            ..Default::default()
445        };
446        assert_string_ok_eq_no_warnings(
447            "BBPBDU",
448            base_to_base_string("25516010", 10, 30, &dec_to_b30_b64),
449        );
450
451        // Base 30 (Base64Standard) -> Base 10 (Standard)
452        let b30_b64_to_dec = BaseStringFormatSettings {
453            input_alphabet: BaseAlphabet::Base64Standard,
454            output_alphabet: BaseAlphabet::Standard,
455            ..Default::default()
456        };
457        assert_string_ok_eq_no_warnings(
458            "25516010",
459            base_to_base_string("BBPBDU", 30, 10, &b30_b64_to_dec),
460        );
461
462        // Base > 36 fails if Standard alphabet is configured
463        let standard_settings = BaseStringFormatSettings::default();
464        assert!(
465            base_to_base_string("255", 10, 64, &standard_settings).is_err()
466        );
467
468        // Base 1 (unary) tests with Standard alphabet
469        assert_string_ok_eq_no_warnings(
470            "00000",
471            base_to_base_string(
472                "5",
473                10,
474                1,
475                &BaseStringFormatSettings::default(),
476            ),
477        );
478        assert_string_ok_eq_no_warnings(
479            "5",
480            base_to_base_string(
481                "00000",
482                1,
483                10,
484                &BaseStringFormatSettings::default(),
485            ),
486        );
487
488        // Base 1 (unary) tests with Base64Standard alphabet
489        let dec_to_un_b64 = BaseStringFormatSettings {
490            input_alphabet: BaseAlphabet::Standard,
491            output_alphabet: BaseAlphabet::Base64Standard,
492            ..Default::default()
493        };
494        assert_string_ok_eq_no_warnings(
495            "AAAAA",
496            base_to_base_string("5", 10, 1, &dec_to_un_b64),
497        );
498        let un_b64_to_dec = BaseStringFormatSettings {
499            input_alphabet: BaseAlphabet::Base64Standard,
500            output_alphabet: BaseAlphabet::Standard,
501            ..Default::default()
502        };
503        assert_string_ok_eq_no_warnings(
504            "5",
505            base_to_base_string("AAAAA", 1, 10, &un_b64_to_dec),
506        );
507    }
508}