ctb_formats_math/
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//! Mathematical base representation, positional numeral systems, and number
21//! string conversion utilities.
22//!
23//! This module addresses two distinct, interrelated domains:
24//!
25//! 1. **Mathematical Positional Radix Systems (Number-Oriented)**:
26//!    - Represents numeric quantities in positional notation across integer
27//!      radices from 1 (unary) to 64 ([`Base`], [`BaseAlphabet`],
28//!      [`NumeralSystem`]).
29//!    - Evaluates and formats scalar mathematical values ([`Natural`], integer
30//!      primitives).
31//!    - In positional number systems, leading zeros are semantically inert in
32//!      value (e.g. `0042` and `42` denote the identical scalar integer).
33//!
34//! 2. **Delimited Text Stream Parsing & Formatting (String-Oriented)**:
35//!    - Parses, converts, and formats strings containing one or more numbers
36//!      separated by delimiters (commas, spaces) or prefixes (`0x`, `0b`, `0o`)
37//!      via [`format_base_string`] and [`base_to_base_string`].
38//!    - Configured via [`BaseStringFormatSettings`], supporting custom padding,
39//!      delimiters, character filtering, and radix prefixes.
40//!    - Supports fixed-width digit chunking via the `limit` configuration
41//!      parameter (e.g. `limit = 255` allows chunking numbers into byte-sized
42//!      units).
43//!
44//! ### Distinction from Byte-Stream Data Armoring
45//!
46//! This module is intended for **mathematical numerals**, not for arbitrary
47//! binary byte data armoring:
48//! - In **data armoring** (e.g. continuous hex streams, hexdumps, Base16b, or
49//!   RFC 4648 Base64 byte armoring), exact byte framing is critical: leading
50//!   `0x00` bytes are real data elements whose removal alters data length and
51//!   corrupts serialization.
52//! - In **positional numerals** (this module), values are abstract scalars.
53//!   While [`BaseAlphabet::Base64Standard`] is provided, it represents a
54//!   mathematical base-64 positional radix ($b = 64$) over [`Natural`]
55//!   numbers, rather than an octet-stream block armor codec.
56//! - For raw byte sequence armoring and hexdumps, refer to `ctb_formats_armor`,
57//!   `ctb_formats_hexdump`, and `ctb_formats_base64`.
58
59#[allow(
60    unused_imports,
61    clippy::wildcard_imports,
62    reason = "Standard workspace module prelude"
63)]
64use crate::utilities::*;
65
66use anyhow::{Result, anyhow, bail, ensure};
67use ctb_formats_utilities::FormatLog;
68use malachite::Natural;
69use malachite::base::num::basic::traits::Zero;
70
71// ============================================================================
72// SECTION 1: Positional Radix & Numeral Systems (Mathematical Numbers)
73// ============================================================================
74
75/// Represents a mathematical integer base / radix (e.g. 1, 2, 8, 10, 16, 64).
76#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
77pub struct Base(u8);
78
79/// Alphabet used by a numeral system.
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
81pub enum BaseAlphabet {
82    /// Standard alphanumeric alphabet (`0-9`, `A-Z`), case-insensitive for
83    /// input.
84    #[default]
85    Standard,
86    /// Positional Base64 alphabet (`A-Z`, `a-z`, `0-9`, `+`, `/`),
87    /// case-sensitive.
88    ///
89    /// Note: In this module, this alphabet is used for mathematical base-64
90    /// positional numerals over numbers, not as an octet-stream data armor
91    /// codec.
92    Base64Standard,
93}
94
95impl BaseAlphabet {
96    /// Returns the maximum radix supported by this alphabet.
97    #[must_use]
98    pub const fn max_base(self) -> u8 {
99        match self {
100            Self::Standard => 36,
101            Self::Base64Standard => 64,
102        }
103    }
104
105    /// Returns true if the given base radix is valid for this alphabet.
106    #[must_use]
107    pub fn is_supported_base(self, radix: u8) -> bool {
108        (1..=self.max_base()).contains(&radix)
109    }
110
111    /// Returns true if the given `Base` is valid for this alphabet.
112    #[must_use]
113    pub fn is_supported_base_type(self, base: Base) -> bool {
114        self.is_supported_base(base.radix())
115    }
116
117    /// Returns the zero digit character for this alphabet.
118    #[must_use]
119    pub const fn zero_char(self) -> char {
120        match self {
121            Self::Standard => '0',
122            Self::Base64Standard => 'A',
123        }
124    }
125
126    /// Returns whether this alphabet is case-sensitive.
127    #[must_use]
128    pub const fn is_case_sensitive(self) -> bool {
129        match self {
130            Self::Standard => false,
131            Self::Base64Standard => true,
132        }
133    }
134
135    /// Returns the digit value for a character in this alphabet.
136    pub fn digit_for_char(self, c: char) -> Result<u8> {
137        match self {
138            Self::Standard => {
139                let uc = c.to_ascii_uppercase();
140                match uc {
141                    '0'..='9' => {
142                        let offset = u8::try_from(
143                            u32::from(uc).saturating_sub(u32::from(b'0')),
144                        )?;
145                        Ok(offset)
146                    }
147                    'A'..='Z' => {
148                        let offset = u8::try_from(
149                            u32::from(uc).saturating_sub(u32::from(b'A')),
150                        )?;
151                        Ok(10u8.saturating_add(offset))
152                    }
153                    _ => bail!(
154                        "Character '{c}' is not a valid digit in standard alphabet"
155                    ),
156                }
157            }
158            Self::Base64Standard => match c {
159                'A'..='Z' => {
160                    let offset = u8::try_from(
161                        u32::from(c).saturating_sub(u32::from(b'A')),
162                    )?;
163                    Ok(offset)
164                }
165                'a'..='z' => {
166                    let offset = u8::try_from(
167                        u32::from(c).saturating_sub(u32::from(b'a')),
168                    )?;
169                    Ok(26u8.saturating_add(offset))
170                }
171                '0'..='9' => {
172                    let offset = u8::try_from(
173                        u32::from(c).saturating_sub(u32::from(b'0')),
174                    )?;
175                    Ok(52u8.saturating_add(offset))
176                }
177                '+' => Ok(62),
178                '/' => Ok(63),
179                _ => bail!(
180                    "Character '{c}' is not a valid digit in Base64Standard alphabet"
181                ),
182            },
183        }
184    }
185
186    /// Returns the character for a digit value in this alphabet.
187    pub fn char_for_digit(self, digit: u8) -> Result<char> {
188        match self {
189            Self::Standard => {
190                if digit <= 9 {
191                    let code = b'0'.saturating_add(digit);
192                    Ok(char::from(code))
193                } else if digit <= 35 {
194                    let code = b'A'.saturating_add(digit.saturating_sub(10));
195                    Ok(char::from(code))
196                } else {
197                    bail!(
198                        "Digit {digit} out of range for standard alphabet (0..=35)"
199                    )
200                }
201            }
202            Self::Base64Standard => {
203                if digit <= 25 {
204                    let code = b'A'.saturating_add(digit);
205                    Ok(char::from(code))
206                } else if digit <= 51 {
207                    let code = b'a'.saturating_add(digit.saturating_sub(26));
208                    Ok(char::from(code))
209                } else if digit <= 61 {
210                    let code = b'0'.saturating_add(digit.saturating_sub(52));
211                    Ok(char::from(code))
212                } else if digit == 62 {
213                    Ok('+')
214                } else if digit == 63 {
215                    Ok('/')
216                } else {
217                    bail!(
218                        "Digit {digit} out of range for base64 alphabet (0..=63)"
219                    )
220                }
221            }
222        }
223    }
224
225    /// Returns true if character is a valid digit for the given numeric base.
226    #[must_use]
227    pub fn is_digit(self, c: char, base: u8) -> bool {
228        if !self.is_supported_base(base) {
229            return false;
230        }
231        match self.digit_for_char(c) {
232            Ok(d) => d < base,
233            Err(_) => false,
234        }
235    }
236}
237
238/// Represents a numeral system defined by a mathematical radix and a digit alphabet.
239#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
240pub struct NumeralSystem {
241    pub radix: Base,
242    pub alphabet: BaseAlphabet,
243}
244
245impl NumeralSystem {
246    pub const UNARY: Self = Self {
247        radix: Base::Unary,
248        alphabet: BaseAlphabet::Standard,
249    };
250    pub const BINARY: Self = Self {
251        radix: Base::Binary,
252        alphabet: BaseAlphabet::Standard,
253    };
254    pub const OCTAL: Self = Self {
255        radix: Base::Octal,
256        alphabet: BaseAlphabet::Standard,
257    };
258    pub const DECIMAL: Self = Self {
259        radix: Base::Decimal,
260        alphabet: BaseAlphabet::Standard,
261    };
262    pub const HEX: Self = Self {
263        radix: Base::Hex,
264        alphabet: BaseAlphabet::Standard,
265    };
266
267    /// Creates a new `NumeralSystem` with validation that the radix is supported by the alphabet.
268    pub fn new(radix: Base, alphabet: BaseAlphabet) -> Result<Self> {
269        ensure!(
270            alphabet.is_supported_base_type(radix),
271            "Radix {radix:?} (value {}) is not supported by alphabet {alphabet:?}",
272            radix.radix()
273        );
274        Ok(Self { radix, alphabet })
275    }
276
277    /// Creates a `NumeralSystem` using the standard alphabet.
278    pub fn standard(radix: Base) -> Result<Self> {
279        Self::new(radix, BaseAlphabet::Standard)
280    }
281
282    /// Creates a `NumeralSystem` using the Base64 alphabet.
283    pub fn base64(radix: Base) -> Result<Self> {
284        Self::new(radix, BaseAlphabet::Base64Standard)
285    }
286
287    /// Resolves a `NumeralSystem` from a numeric radix.
288    pub fn from_radix(radix: u8) -> Result<Self> {
289        let base = Base::from_radix(radix)?;
290        Ok(base.into())
291    }
292
293    /// Returns the character for a digit value in this numeral system.
294    pub fn char_for_digit(self, digit: u8) -> Result<char> {
295        if digit >= self.radix.radix() {
296            bail!(
297                "Digit {digit} is out of range for base {}",
298                self.radix.radix()
299            );
300        }
301        self.alphabet.char_for_digit(digit)
302    }
303
304    /// Parses a single character into a digit value in this numeral system.
305    pub fn digit_for_char(self, c: char) -> Result<u8> {
306        let digit = self.alphabet.digit_for_char(c)?;
307        if digit >= self.radix.radix() {
308            bail!(
309                "Digit '{c}' ({digit}) is out of range for base {}",
310                self.radix.radix()
311            );
312        }
313        Ok(digit)
314    }
315
316    /// Returns true if character is a valid digit in this numeral system.
317    #[must_use]
318    pub fn is_digit(self, c: char) -> bool {
319        self.digit_for_char(c).is_ok()
320    }
321
322    /// Returns the zero digit character for this numeral system.
323    #[must_use]
324    pub const fn zero_char(self) -> char {
325        self.alphabet.zero_char()
326    }
327}
328
329impl From<Base> for NumeralSystem {
330    fn from(base: Base) -> Self {
331        let alphabet = if base.radix() > 36 {
332            BaseAlphabet::Base64Standard
333        } else {
334            BaseAlphabet::Standard
335        };
336        Self {
337            radix: base,
338            alphabet,
339        }
340    }
341}
342
343impl Base {
344    #[expect(non_upper_case_globals, reason = "Base name alias constants")]
345    pub const Unary: Self = Self(1);
346    #[expect(non_upper_case_globals, reason = "Base name alias constants")]
347    pub const Binary: Self = Self(2);
348    #[expect(non_upper_case_globals, reason = "Base name alias constants")]
349    pub const Octal: Self = Self(8);
350    #[expect(non_upper_case_globals, reason = "Base name alias constants")]
351    pub const Decimal: Self = Self(10);
352    #[expect(non_upper_case_globals, reason = "Base name alias constants")]
353    pub const Hex: Self = Self(16);
354    #[expect(non_upper_case_globals, reason = "Base name alias constants")]
355    pub const Hexadecimal: Self = Self(16);
356
357    /// Creates a `Base` with range validation (1..=64).
358    pub fn new(radix: u8) -> Result<Self> {
359        ensure!((1..=64).contains(&radix), "Unsupported base radix: {radix}");
360        Ok(Self(radix))
361    }
362
363    /// Creates a `Base` with const evaluation without range check.
364    #[must_use]
365    pub const fn from_radix_const(radix: u8) -> Self {
366        Self(radix)
367    }
368
369    /// Creates a `Base` from a numeric radix with range validation.
370    pub fn from_radix(radix: u8) -> Result<Self> {
371        Self::new(radix)
372    }
373
374    /// Returns the integer radix represented by this base.
375    #[must_use]
376    pub const fn radix(self) -> u8 {
377        self.0
378    }
379
380    /// Parses a base from a string representation, including numeric radices ("1".."64")
381    /// and standard names/aliases ("unary", "bin", "binary", "oct", "octal", "dec", "decimal",
382    /// "hex", "hexadecimal", "base64", etc.).
383    pub fn from_str_or_name(s: &str) -> Result<Self> {
384        let trimmed = s.trim();
385        if let Ok(radix) = trimmed.parse::<u8>() {
386            return Self::from_radix(radix);
387        }
388        match trimmed.to_ascii_lowercase().as_str() {
389            "unary" | "un" => Ok(Self::Unary),
390            "bin" | "binary" => Ok(Self::Binary),
391            "oct" | "octal" => Ok(Self::Octal),
392            "dec" | "decimal" => Ok(Self::Decimal),
393            "hex" | "hexadecimal" => Ok(Self::Hex),
394            _ => bail!("Unknown or unsupported base: '{s}'"),
395        }
396    }
397}
398
399#[expect(non_upper_case_globals, reason = "Base name alias constants")]
400pub const Unary: Base = Base::Unary;
401#[expect(non_upper_case_globals, reason = "Base name alias constants")]
402pub const Binary: Base = Base::Binary;
403#[expect(non_upper_case_globals, reason = "Base name alias constants")]
404pub const Octal: Base = Base::Octal;
405#[expect(non_upper_case_globals, reason = "Base name alias constants")]
406pub const Decimal: Base = Base::Decimal;
407#[expect(non_upper_case_globals, reason = "Base name alias constants")]
408pub const Hex: Base = Base::Hex;
409#[expect(non_upper_case_globals, reason = "Base name alias constants")]
410pub const Hexadecimal: Base = Base::Hexadecimal;
411
412impl TryFrom<u8> for Base {
413    type Error = anyhow::Error;
414
415    fn try_from(value: u8) -> Result<Self, Self::Error> {
416        Self::from_radix(value)
417    }
418}
419
420impl From<Base> for u8 {
421    fn from(base: Base) -> Self {
422        base.radix()
423    }
424}
425
426/// Returns the single-character digit for a numeric value in the given base.
427pub fn digit_to_char(digit: u8, base: Base) -> Result<char> {
428    NumeralSystem::from(base).char_for_digit(digit)
429}
430
431/// Parses a single character into a digit value in the given base.
432pub fn char_to_digit(c: char, base: Base) -> Result<u8> {
433    NumeralSystem::from(base).digit_for_char(c)
434}
435
436/// Returns true if the numeric base is supported (1..=64).
437/// Radices greater than 36 require an expanded alphabet such as
438/// [`BaseAlphabet::Base64Standard`].
439#[must_use]
440pub fn is_supported_base(base: u8) -> bool {
441    (1..=64).contains(&base)
442}
443
444/// Returns true if the base is supported by the standard alphanumeric alphabet
445/// (1..=36).
446#[must_use]
447pub fn is_supported_base_with_default_alphabet(base: u8) -> bool {
448    (1..=36).contains(&base)
449}
450
451/// Returns true if the character is a valid digit for the given base in the
452/// specified alphabet.
453#[must_use]
454pub fn is_base_digit_alphabet(
455    ch: char,
456    base: u8,
457    alphabet: BaseAlphabet,
458) -> bool {
459    alphabet.is_digit(ch, base)
460}
461
462/// Returns true if all characters in the string are valid digits for the given
463/// base in the specified alphabet.
464#[must_use]
465pub fn is_base_str_alphabet(s: &str, base: u8, alphabet: BaseAlphabet) -> bool {
466    if !alphabet.is_supported_base(base) {
467        return false;
468    }
469    for ch in s.chars() {
470        if !alphabet.is_digit(ch, base) {
471            return false;
472        }
473    }
474    true
475}
476
477/// Returns true if the single-character string is a valid digit in the standard
478/// alphabet for the given base.
479pub fn is_base_digit(ch: &str, base: u8) -> Result<bool> {
480    if ch.chars().count() != 1 {
481        bail!("Invalid digit");
482    }
483    if !is_supported_base(base) {
484        bail!("Unsupported base {base}");
485    }
486    let Some(c) = ch.chars().next() else {
487        bail!("Empty character string");
488    };
489    Ok(BaseAlphabet::Standard.is_digit(c, base))
490}
491
492/// Returns true if all characters in the string are valid digits in the standard
493/// alphabet for the given base.
494pub fn is_base_str(s: &str, base: u8) -> Result<bool> {
495    if !is_supported_base(base) {
496        bail!("Unsupported base {base}");
497    }
498    Ok(is_base_str_alphabet(s, base, BaseAlphabet::Standard))
499}
500
501/// Parses a string representing a number in the given numeral system into a `Natural`.
502#[expect(
503    clippy::arithmetic_side_effects,
504    reason = "Natural is arbitrary-precision and cannot overflow"
505)]
506pub fn parse_natural_system(s: &str, system: NumeralSystem) -> Result<Natural> {
507    ensure!(!s.is_empty(), "Cannot parse empty string as number");
508    let radix = system.radix.radix();
509    if radix == 1 {
510        for ch in s.chars() {
511            let d = system.alphabet.digit_for_char(ch)?;
512            ensure!(d == 0, "Invalid digit '{ch}' for base 1");
513        }
514        return Ok(Natural::from(s.chars().count()));
515    }
516
517    let s = match system.radix {
518        // Reason for fallback: numbers without base prefix retain original string representation.
519        Base::Hex => s
520            .strip_prefix("0x")
521            .or_else(|| s.strip_prefix("0X"))
522            .unwrap_or(s),
523        // Reason for fallback: numbers without base prefix retain original string representation.
524        Base::Binary => s
525            .strip_prefix("0b")
526            .or_else(|| s.strip_prefix("0B"))
527            .unwrap_or(s),
528        // Reason for fallback: numbers without base prefix retain original string representation.
529        Base::Octal => s
530            .strip_prefix("0o")
531            .or_else(|| s.strip_prefix("0O"))
532            .unwrap_or(s),
533        _ => s,
534    };
535    ensure!(
536        !s.is_empty(),
537        "Cannot parse empty number string after prefix"
538    );
539    let mut acc = Natural::ZERO;
540    let base_nat = Natural::from(radix);
541    for ch in s.chars() {
542        let d = system.digit_for_char(ch)?;
543        acc = acc * &base_nat + Natural::from(d);
544    }
545    Ok(acc)
546}
547
548/// Parses a string representing a number in the given base into a `Natural`.
549pub fn parse_natural(s: &str, base: Base) -> Result<Natural> {
550    parse_natural_system(s, base.into())
551}
552
553/// Formats a `Natural` number in the given numeral system with optional minimum width.
554#[expect(
555    clippy::arithmetic_side_effects,
556    reason = "Natural is arbitrary-precision and cannot overflow"
557)]
558pub fn format_natural_system(
559    n: &Natural,
560    system: NumeralSystem,
561    min_width: usize,
562) -> Result<String> {
563    let radix = system.radix.radix();
564    let mut raw = if radix == 1 {
565        if *n == Natural::ZERO {
566            String::new()
567        } else {
568            let count = usize::try_from(n).map_err(|e| {
569                anyhow!("Value too large for base 1 format: {e:?}")
570            })?;
571            std::iter::repeat_n(system.zero_char(), count).collect()
572        }
573    } else if *n == Natural::ZERO {
574        let zero_char = system.zero_char();
575        zero_char.to_string()
576    } else {
577        let base_nat = Natural::from(radix);
578        let mut digits = Vec::new();
579        let mut val = n.clone();
580        while val > Natural::ZERO {
581            let rem = &val % &base_nat;
582            let digit_u8 = u8::try_from(&rem)
583                .map_err(|e| anyhow!("Remainder out of u8 range: {e:?}"))?;
584            digits.push(system.char_for_digit(digit_u8)?);
585            val /= &base_nat;
586        }
587        digits.into_iter().rev().collect::<String>()
588    };
589
590    if raw.len() < min_width {
591        let zero_char = system.zero_char();
592        let pad_len = min_width.saturating_sub(raw.len());
593        let padding: String = std::iter::repeat_n(zero_char, pad_len).collect();
594        raw = format!("{padding}{raw}");
595    }
596    Ok(raw)
597}
598
599/// Formats a `Natural` number in the given base with optional minimum width.
600pub fn format_natural(
601    n: &Natural,
602    base: Base,
603    min_width: usize,
604) -> Result<String> {
605    format_natural_system(n, base.into(), min_width)
606}
607
608/// Returns the integer represented by n in the requested base.
609pub fn int_from_base_str_u32(s: &str, base: u8) -> Result<u32> {
610    let nat = int_from_base_str_big_alphabet(s, base, BaseAlphabet::Standard)?;
611    u32::try_from(&nat).map_err(|_| anyhow!("Did not fit in u32"))
612    /* Old implementation:
613        if !is_supported_base(base) {
614        bail!("Unsupported base {base}");
615    }
616    let mut acc: u64 = 0;
617    for ch in s.chars() {
618        let d = int_from_base36_char(&ch.to_string())?;
619        if d >= base {
620            bail!("Digit {d} >= base {base}");
621        }
622        acc = acc
623            .checked_mul(u64::from(base))
624            .ok_or_else(|| anyhow!("Overflow converting {s} base {base}"))?;
625        acc = acc
626            .checked_add(u64::from(d))
627            .ok_or_else(|| anyhow!("Overflow converting {s} base {base}"))?;
628        if acc > u64::from(u32::MAX) {
629            bail!("Overflow converting {s} base {base}");
630        }
631    }
632    u32::try_from(acc).context("Did not fit in u32")
633    */
634}
635
636/// Returns the integer represented by n in the requested base.
637pub fn int_from_base_str_u128(s: &str, base: u8) -> Result<u128> {
638    let nat = int_from_base_str_big_alphabet(s, base, BaseAlphabet::Standard)?;
639    u128::try_from(&nat).map_err(|_| anyhow!("Did not fit in u128"))
640    /* Old implementation:
641
642        if !is_supported_base(base) {
643        bail!("Unsupported base {base}");
644    }
645    let mut acc: u128 = 0;
646    for ch in s.chars() {
647        let d = int_from_base36_char(&ch.to_string())?;
648        if d >= base {
649            bail!("Digit {d} >= base {base}");
650        }
651        acc = acc
652            .checked_mul(u128::from(base))
653            .ok_or_else(|| anyhow!("Overflow converting {s} base {base}"))?;
654        acc = acc
655            .checked_add(u128::from(d))
656            .ok_or_else(|| anyhow!("Overflow converting {s} base {base}"))?;
657    }
658    Ok(acc) */
659}
660
661/// Returns the integer represented by n in the requested base using the given alphabet.
662#[expect(
663    clippy::arithmetic_side_effects,
664    reason = "Natural is arbitrary-precision and cannot overflow"
665)]
666pub fn int_from_base_str_big_alphabet(
667    s: &str,
668    base: u8,
669    alphabet: BaseAlphabet,
670) -> Result<Natural> {
671    ensure!(
672        alphabet.is_supported_base(base),
673        "Unsupported base {base} for alphabet {alphabet:?}"
674    );
675    if base == 1 {
676        for ch in s.chars() {
677            let d = alphabet.digit_for_char(ch)?;
678            if d >= 1 {
679                bail!("Digit '{ch}' (value {d}) >= base 1");
680            }
681        }
682        return Ok(Natural::from(s.chars().count()));
683    }
684    let mut acc = Natural::ZERO;
685    let base_nat = Natural::from(base);
686    for ch in s.chars() {
687        let d = alphabet.digit_for_char(ch)?;
688        if d >= base {
689            bail!("Digit '{ch}' (value {d}) >= base {base}");
690        }
691        acc = acc * &base_nat + Natural::from(d);
692    }
693    Ok(acc)
694}
695
696/// Returns the string representation of an arbitrary-precision integer in the requested base and alphabet.
697#[expect(
698    clippy::arithmetic_side_effects,
699    reason = "Natural is arbitrary-precision and cannot overflow"
700)]
701pub fn int_to_base_str_big_alphabet(
702    mut n: Natural,
703    base: u8,
704    alphabet: BaseAlphabet,
705) -> Result<String> {
706    ensure!(
707        alphabet.is_supported_base(base),
708        "Unsupported base {base} for alphabet {alphabet:?}"
709    );
710    if base == 1 {
711        if n == 0 {
712            return Ok(String::new());
713        }
714        let count = usize::try_from(&n).map_err(|e| {
715            anyhow!("Value too large for base 1 conversion: {e:?}")
716        })?;
717        return Ok(std::iter::repeat_n(alphabet.zero_char(), count).collect());
718    }
719    if n == 0 {
720        return Ok(alphabet.char_for_digit(0)?.to_string());
721    }
722    let base_nat = Natural::from(base);
723    let mut digits = Vec::new();
724    while n > 0 {
725        let rem_nat = &n % &base_nat;
726        let rem = u8::try_from(&rem_nat)
727            .map_err(|e| anyhow!("Digit out of range: {e:?}"))?;
728        digits.push(alphabet.char_for_digit(rem)?);
729        n /= &base_nat;
730    }
731    digits.reverse();
732    Ok(digits.into_iter().collect())
733}
734
735/// Returns the integer represented by n in the requested base.
736pub fn int_from_base_str_big(s: &str, base: u8) -> Result<Natural> {
737    int_from_base_str_big_alphabet(s, base, BaseAlphabet::Standard)
738}
739
740/// Returns the integer represented by n in the requested base.
741pub fn int_to_base_str(n: u32, base: u8) -> Result<String> {
742    int_to_base_str_big_alphabet(Natural::from(n), base, BaseAlphabet::Standard)
743
744    /* Old implementation:
745        if !is_supported_base(base) {
746        bail!("Unsupported base {base}");
747    }
748    if n == 0 {
749        return Ok("0".into());
750    }
751    let mut out = String::new();
752    while n > 0 {
753        let digit = n
754            .checked_rem(u32::from(base))
755            .ok_or_else(|| anyhow!("Base cannot be zero"))?;
756        let c_str = int_to_base36_char(digit.try_into()?)?;
757        let ch = c_str
758            .chars()
759            .next()
760            .ok_or_else(|| anyhow!("int_to_base36_char returned empty string"))?;
761        out.push(ch);
762        n = n
763            .checked_div(u32::from(base))
764            .ok_or_else(|| anyhow!("Base cannot be zero"))?;
765    }
766    Ok(out.chars().rev().collect())
767    */
768}
769
770pub fn hex_to_dec_single(s: &str) -> Result<u32> {
771    int_from_base_str_u32(s, 16)
772}
773
774pub fn dec_to_hex_single(n: u32) -> Result<String> {
775    int_to_base_str(n, 16)
776}
777
778#[expect(
779    clippy::arithmetic_side_effects,
780    reason = "Natural is arbitrary-precision and cannot overflow"
781)]
782pub fn get_digits_needed(
783    n: Natural,
784    base: u8,
785    alphabet: BaseAlphabet,
786) -> Result<Natural> {
787    ensure!(alphabet.is_supported_base(base), "Unsupported base {base}");
788    if base == 1 {
789        return Ok(n);
790    }
791    let mut digits = Natural::ZERO;
792    let mut value = n;
793    while value > 0 {
794        value /= Natural::from(base);
795        digits += Natural::from(1u8);
796    }
797    Ok(digits)
798}
799
800// ============================================================================
801// SECTION 2: Delimited Text Stream Parsing & Formatting (String Processing)
802// ============================================================================
803
804/// Zero-padding configuration for delimited base string conversion.
805#[derive(Clone, Debug, PartialEq, Eq)]
806pub struct BaseConversionPaddingMode {
807    /// Left-pad each number with leading zeros to at least this many digits
808    /// (e.g. `pad_l: 4` formats 5 as `"0005"`).
809    pub pad_l: u32,
810    /// If true, automatically pads each number to the full digit width required
811    /// to hold `limit` (e.g. padding to 2 hex digits or 8 binary digits when
812    /// `limit = 255`). Requires a limit to be set.
813    pub pad_fit: bool,
814}
815
816impl Default for BaseConversionPaddingMode {
817    fn default() -> Self {
818        Self {
819            pad_l: 1,
820            pad_fit: false,
821        }
822    }
823}
824
825impl BaseConversionPaddingMode {
826    #[must_use]
827    pub fn none() -> Self {
828        Self::default()
829    }
830}
831
832/// Settings for parsing and formatting delimited strings of numbers across bases.
833///
834/// This configuration controls the batch transformation of lists of numbers
835/// embedded within a string (such as `"0x1A, 0x10, 0x04"`).
836///
837/// Note: The `separator` parameter controls delimiters *between separate
838/// numbers* in the output list. It does not insert internal digit grouping
839/// separators (like thousands separators in `"123,456"`).
840#[derive(Clone, Debug, PartialEq, Eq)]
841#[expect(clippy::struct_excessive_bools, reason = "conversion format flags")]
842pub struct BaseStringFormatSettings {
843    /// The prefix to prepend to each output number (e.g. `"0x"` for hexadecimal).
844    pub prefix: String,
845    /// The separator string inserted between separate numbers in the output list.
846    pub separator: String,
847    /// Whether letter digits in bases > 10 should be lowercased.
848    pub lowercase: bool,
849    /// Whether to strip or replace non-digit input characters (other than
850    /// spaces and commas) in the formatted output.
851    ///
852    /// When `true` (default), non-digit input characters that are not collapsed
853    /// are stripped from the output stream. When `false`, they are preserved as
854    /// literal tokens in the output string.
855    pub filter_chars: bool,
856    /// Should non-digit characters be completely ignored inline while parsing
857    /// numbers?
858    ///
859    /// When `true`, characters like `_` in `"10_000"` will not split the number,
860    /// allowing `"10_000"` to parse as a single number `10000`.
861    pub collapse_filtered: bool,
862    /// A selective list of specific non-digit characters to collapse inline
863    /// without splitting numbers (e.g. `vec!["_".to_string()]`).
864    ///
865    /// Characters in this list are stripped silently without emitting
866    /// warnings, while other non-digit characters will still split numbers and
867    /// generate "unexpected character" warnings.
868    pub collapse_only: Vec<String>,
869    /// Determines whether to recognize standard radix prefixes (such as `"0x"`,
870    /// `"0b"`, or `"0o"`) as part of the number while parsing.
871    ///
872    /// If `false`, prefixes are not stripped or recognized:
873    /// - If the prefix character is not a digit in the input base (such as `'x'`
874    ///   in hexadecimal), the leading `'0'` is parsed as a number, followed
875    ///   by the prefix letter as a non-digit delimiter, and the remaining
876    ///   digits as another number.
877    /// - If the prefix character *is* a valid digit in the input base (such as
878    ///   `'b'` in base 16, or `'x'` in bases 34..=36 and base 64), the prefix
879    ///   character is parsed directly as part of a single larger number.
880    pub parse_prefixes: bool,
881    /// Derives the maximum digit chunk width for numbers based on the maximum
882    /// value to be represented (e.g. `limit = 255` chunks numbers into byte-sized
883    /// units: 2 hex digits, 8 binary digits, or up to 3 decimal digits).
884    /// Set to 0 to disable chunk limiting.
885    pub limit: u64,
886    /// Controls zero-padding on the left of each formatted number, either to a
887    /// fixed minimum digit width (`pad_l`) or sized to fit the configured
888    /// `limit` (e.g. padding hex bytes to 2 digits or binary to 8 bits).
889    pub pad: BaseConversionPaddingMode,
890    /// Alphabet to use when parsing input numbers.
891    pub input_alphabet: BaseAlphabet,
892    /// Alphabet to use when formatting output numbers.
893    pub output_alphabet: BaseAlphabet,
894}
895
896impl Default for BaseStringFormatSettings {
897    fn default() -> Self {
898        Self {
899            prefix: String::new(),
900            separator: " ".into(),
901            lowercase: false,
902            limit: 0,
903            filter_chars: true,
904            collapse_only: Vec::new(),
905            collapse_filtered: false,
906            parse_prefixes: true,
907            pad: BaseConversionPaddingMode {
908                pad_l: 1,
909                pad_fit: false,
910            },
911            input_alphabet: BaseAlphabet::Standard,
912            output_alphabet: BaseAlphabet::Standard,
913        }
914    }
915}
916
917pub fn casefold_base_chars_in_string(
918    s: &str,
919    base: u8,
920    uppercase: bool,
921) -> Result<String> {
922    ensure!(
923        is_supported_base_with_default_alphabet(base),
924        "Unsupported base {base} (case folding is only supported for bases up to 36)"
925    );
926    let mut result = String::new();
927    for c in s.chars() {
928        if is_base_digit(c.to_string().as_str(), base)? {
929            result.push(if uppercase {
930                c.to_ascii_uppercase()
931            } else {
932                c.to_ascii_lowercase()
933            });
934        } else {
935            result.push(c);
936        }
937    }
938    Ok(result)
939}
940
941/// Parse a string containing numbers in base 2 through 64 and print it
942/// formatted. Will warn for extra characters other than spaces and commas.
943pub fn format_base_string(
944    s: &str,
945    base: u8,
946    settings: &BaseStringFormatSettings,
947) -> Result<(String, FormatLog)> {
948    let parsed = _parse_base_string(
949        s,
950        base,
951        base,
952        settings.parse_prefixes,
953        settings.filter_chars,
954        settings.limit,
955        settings.collapse_filtered,
956        &settings.collapse_only,
957        settings.input_alphabet,
958        settings.output_alphabet,
959    )?;
960    let (out, mut log) = parsed;
961
962    let formatted =
963        _format_base_string(out, base, settings, settings.output_alphabet)?;
964    log.merge(&formatted.1);
965
966    Ok((formatted.0, log))
967}
968
969/// Parse a string containing numbers in base 2 through 64, convert it to the
970/// target base, and print it formatted. Will warn for extra characters other
971/// than spaces and commas.
972pub fn base_to_base_string(
973    s: &str,
974    from_base: u8,
975    to_base: u8,
976    format_settings: &BaseStringFormatSettings,
977) -> Result<(String, FormatLog)> {
978    let converted = _parse_base_string(
979        s,
980        from_base,
981        to_base,
982        format_settings.parse_prefixes,
983        format_settings.filter_chars,
984        format_settings.limit,
985        format_settings.collapse_filtered,
986        &format_settings.collapse_only,
987        format_settings.input_alphabet,
988        format_settings.output_alphabet,
989    )?;
990
991    let (res, mut log) = converted;
992
993    let (formatted_res, formatted_log) = _format_base_string(
994        res,
995        to_base,
996        format_settings,
997        format_settings.output_alphabet,
998    )?;
999    log.merge(&formatted_log);
1000
1001    Ok((formatted_res, log))
1002}
1003
1004/// Convenience function to convert a delimited string of hexadecimal numbers
1005/// to decimal using default format settings.
1006pub fn hex_to_dec_string(s: &str) -> Result<(String, FormatLog)> {
1007    base_to_base_string(s, 16, 10, &BaseStringFormatSettings::default())
1008}
1009
1010/// Convenience function to convert a delimited string of decimal numbers to
1011/// hexadecimal using default format settings.
1012pub fn dec_to_hex_string(s: &str) -> Result<(String, FormatLog)> {
1013    base_to_base_string(s, 10, 16, &BaseStringFormatSettings::default())
1014}
1015
1016/// Converts all characters that match the requested base into the target base.
1017/// It will leave other characters alone, so you can convert a list of numbers.
1018/// It allows hex input numbers like 0x1A.
1019fn _parse_base_string(
1020    s: &str,
1021    from_base: u8,
1022    to_base: u8,
1023    parse_prefixes: bool,
1024    filter_chars: bool,
1025    limit: u64,
1026    collapse_filtered: bool,
1027    collapse_only: &Vec<String>,
1028    from_alphabet: BaseAlphabet,
1029    to_alphabet: BaseAlphabet,
1030) -> Result<(Vec<String>, FormatLog)> {
1031    ensure!(
1032        from_alphabet.is_supported_base(from_base),
1033        "Unsupported from_base {from_base} for alphabet {from_alphabet:?}"
1034    );
1035    ensure!(
1036        to_alphabet.is_supported_base(to_base),
1037        "Unsupported to_base {to_base} for alphabet {to_alphabet:?}"
1038    );
1039    let mut log = FormatLog::default();
1040    let mut out: Vec<String> = Vec::new();
1041
1042    if s.is_empty() && from_base == 1 {
1043        let nat = int_from_base_str_big_alphabet("", from_base, from_alphabet)?;
1044        let formatted =
1045            int_to_base_str_big_alphabet(nat, to_base, to_alphabet)?;
1046        out.push(formatted);
1047        return Ok((out, log));
1048    }
1049
1050    let chars: Vec<char> = s.chars().collect();
1051    let mut i = 0;
1052    let mut in_num = false;
1053    let mut num_chars: String = String::new();
1054    let max_digits =
1055        get_digits_needed(Natural::from(limit), from_base, from_alphabet)?;
1056    let max_digits: usize = usize::try_from(&max_digits).map_err(|e| {
1057        anyhow!(
1058            "Base conversion length of digits greater than usize, limited by String.len(): {e:?}"
1059        )
1060    })?;
1061    let max_digits = if limit == 0 { 0 } else { max_digits };
1062
1063    let multiple_of_base = limit
1064        .checked_add(1)
1065        .is_some_and(|val| val.is_multiple_of(u64::from(from_base)));
1066    if (limit > 1) && !multiple_of_base {
1067        log.warn(format!("The limit was derived from the number of digits required to represent {limit}, but {limit} + 1 is not a multiple of the input base {from_base}. That's not necessarily wrong, but note that the limit is not directly the maximum number of digits, but the maximum value representable in the number of digits to limit to.").as_str());
1068    }
1069
1070    let base_prefix_char: Option<char> = if parse_prefixes {
1071        match from_base {
1072            2 => Some('b'),
1073            8 => Some('o'),
1074            16 => Some('x'),
1075            _ => None,
1076        }
1077    } else {
1078        None
1079    };
1080
1081    let base_prefix: Option<String> = base_prefix_char.map(|c| format!("0{c}"));
1082
1083    let finalize_num = |num_chars: &mut String,
1084                        out: &mut Vec<String>|
1085     -> Result<()> {
1086        if let Some(base_prefix) = &base_prefix
1087            && num_chars.starts_with(base_prefix)
1088        {
1089            *num_chars = num_chars.trim_start_matches(base_prefix).to_string();
1090        }
1091        let nat = int_from_base_str_big_alphabet(
1092            num_chars,
1093            from_base,
1094            from_alphabet,
1095        )?;
1096        let formatted =
1097            int_to_base_str_big_alphabet(nat, to_base, to_alphabet)?;
1098        out.push(formatted);
1099        Ok(())
1100    };
1101    let normalize_or_push_char = |out: &mut Vec<String>, c: char| {
1102        if !filter_chars {
1103            out.push(c.to_string());
1104        }
1105    };
1106    while i < chars.len() {
1107        let c: char = chars
1108            .get(i)
1109            .copied()
1110            .ok_or_else(|| anyhow!("Index out of bounds"))?;
1111
1112        let this_is_base_digit = from_alphabet.is_digit(c, from_base);
1113
1114        if let Some(base_prefix_char) = base_prefix_char {
1115            let potential_prefix = if let Some(potential_prefix) =
1116                i.checked_add(2).and_then(|end| chars.get(i..end))
1117            {
1118                potential_prefix
1119                    .first()
1120                    .copied()
1121                    .zip(potential_prefix.get(1).copied())
1122            } else {
1123                None
1124            };
1125
1126            let next = i.checked_add(2).and_then(|idx| chars.get(idx));
1127            let next_is_base_digit = if let Some(next) = next {
1128                from_alphabet.is_digit(*next, from_base)
1129            } else {
1130                false
1131            };
1132            if let Some(potential_prefix) = potential_prefix
1133                && potential_prefix.0 == '0'
1134                && potential_prefix.1 == base_prefix_char
1135                && next_is_base_digit
1136            {
1137                if in_num {
1138                    finalize_num(&mut num_chars, &mut out)?;
1139                    in_num = false;
1140                    num_chars.clear();
1141                }
1142
1143                i = i.saturating_add(2);
1144                continue;
1145            }
1146        }
1147
1148        if this_is_base_digit {
1149            in_num = true;
1150
1151            num_chars.push(c);
1152        } else {
1153            let mut this_collapse_filtered = false;
1154            let mut in_collapse_only = false;
1155            if c != ' ' && c != ',' {
1156                // Potentially filtered character
1157                in_collapse_only =
1158                    collapse_only.iter().any(|s| s == &c.to_string());
1159                this_collapse_filtered = collapse_filtered;
1160                if !in_collapse_only {
1161                    // Assume that if the character is being explicitly
1162                    // collapsed, it's not worth warning about.
1163                    log.import_warning(
1164                        i.try_into()?,
1165                        &format!(
1166                            "Unexpected character '{c}' in base {from_base}"
1167                        ),
1168                    );
1169                }
1170            }
1171            if !this_collapse_filtered && !in_collapse_only {
1172                if in_num {
1173                    finalize_num(&mut num_chars, &mut out)?;
1174                    in_num = false;
1175                    num_chars.clear();
1176                }
1177
1178                normalize_or_push_char(&mut out, c);
1179            }
1180        }
1181
1182        if in_num && (max_digits > 0) && (num_chars.len() == max_digits) {
1183            finalize_num(&mut num_chars, &mut out)?;
1184            in_num = false;
1185            num_chars.clear();
1186        }
1187
1188        i = i.saturating_add(1);
1189    }
1190
1191    if in_num && !num_chars.is_empty() {
1192        finalize_num(&mut num_chars, &mut out)?;
1193    }
1194
1195    Ok((out, log))
1196}
1197
1198fn _format_base_string(
1199    tokens: Vec<String>,
1200    base: u8,
1201    settings: &BaseStringFormatSettings,
1202    to_alphabet: BaseAlphabet,
1203) -> Result<(String, FormatLog)> {
1204    let mut log: FormatLog = FormatLog::default();
1205
1206    let pad = &settings.pad;
1207    let limit = settings.limit;
1208    let num_prefix = &settings.prefix;
1209
1210    let padded_width: u32 = if pad.pad_fit {
1211        let max_digits =
1212            get_digits_needed(Natural::from(limit), base, to_alphabet)?;
1213        u32::try_from(&max_digits)
1214            .map_err(|e| anyhow!("Padding to more than 32 bits of digits is not supported just because it seems unnecessary, but could be increased: {e:?}"))?
1215    } else if pad.pad_l <= 1 {
1216        0
1217    } else {
1218        pad.pad_l
1219    };
1220    if (pad.pad_fit) && (limit == 0) {
1221        log.import_error(
1222            0,
1223            "Padding to fit limit was requested, but no limit was set.",
1224        );
1225        bail!("Incompatible padding and limit settings");
1226    }
1227    if (pad.pad_fit) && (limit == 1) && (base != 1) {
1228        log.import_warning(0, "Padding to fit limit was requested, but limit was set to 1. 0 is always shown as 0 anyway, so the padding option will do nothing.");
1229    }
1230    if (pad.pad_fit) && (pad.pad_l > 1) {
1231        // Some cases of this don't technically need to be a fatal error, and it
1232        // could conceivably be useful to allow in some cases, for instance when
1233        // programmatically building CLI argument strings, but it is redundant,
1234        // and it's simplest to just require one or the other.
1235        log.import_error(0, "Padding to fit limit was requested, but a separate padding width was also requested. Please set one or the other.");
1236        bail!("Multiple padding configurations given");
1237    }
1238
1239    let mut out: String = String::new();
1240    for (index, token) in tokens.iter().enumerate() {
1241        let formatted = if is_base_str_alphabet(token, base, to_alphabet) {
1242            let separator = if index < tokens.len().saturating_sub(1) {
1243                &settings.separator
1244            } else {
1245                ""
1246            };
1247            let pad_len = usize::try_from(padded_width)?
1248                .saturating_sub(token.chars().count());
1249            let padding = to_alphabet.zero_char().to_string().repeat(pad_len);
1250            format!("{num_prefix}{padding}{token}{separator}")
1251        } else {
1252            token.clone()
1253        };
1254        out.push_str(&formatted);
1255    }
1256
1257    Ok((
1258        if to_alphabet.is_case_sensitive() {
1259            out
1260        } else if settings.lowercase {
1261            casefold_base_chars_in_string(&out, base, false)?
1262        } else {
1263            casefold_base_chars_in_string(&out, base, true)?
1264        },
1265        log,
1266    ))
1267}
1268
1269#[cfg(test)]
1270#[allow(
1271    clippy::panic,
1272    clippy::expect_used,
1273    clippy::unwrap_used,
1274    clippy::unwrap_in_result,
1275    clippy::panic_in_result_fn,
1276    clippy::indexing_slicing,
1277    clippy::arithmetic_side_effects,
1278    reason = "Standard repository test boilerplate"
1279)]
1280mod tests {
1281    use super::*;
1282
1283    #[crate::ctb_test]
1284    fn test_base_radices_and_aliases() {
1285        assert_eq!(Base::Unary.radix(), 1);
1286        assert_eq!(Base::Binary.radix(), 2);
1287        assert_eq!(Base::Octal.radix(), 8);
1288        assert_eq!(Base::Decimal.radix(), 10);
1289        assert_eq!(Base::Hex.radix(), 16);
1290        assert_eq!(Base::Hexadecimal.radix(), 16);
1291
1292        for r in 1..=64 {
1293            let b = Base::from_radix(r).unwrap();
1294            assert_eq!(b.radix(), r);
1295        }
1296        Base::from_radix(0).unwrap_err();
1297        Base::from_radix(65).unwrap_err();
1298    }
1299
1300    #[crate::ctb_test]
1301    fn test_numeral_system() {
1302        let unary = NumeralSystem::UNARY;
1303        assert_eq!(unary.radix.radix(), 1);
1304        assert_eq!(unary.char_for_digit(0).unwrap(), '0');
1305        unary.char_for_digit(1).unwrap_err();
1306
1307        let dec = NumeralSystem::DECIMAL;
1308        assert_eq!(dec.radix.radix(), 10);
1309        assert_eq!(dec.alphabet, BaseAlphabet::Standard);
1310        assert_eq!(dec.char_for_digit(9).unwrap(), '9');
1311        dec.char_for_digit(10).unwrap_err();
1312
1313        let hex = NumeralSystem::HEX;
1314        assert_eq!(hex.char_for_digit(15).unwrap(), 'F');
1315        assert_eq!(hex.digit_for_char('f').unwrap(), 15);
1316
1317        let b64 = NumeralSystem::base64(Base::new(64).unwrap()).unwrap();
1318        assert_eq!(b64.char_for_digit(63).unwrap(), '/');
1319        assert_eq!(b64.digit_for_char('/').unwrap(), 63);
1320
1321        // Custom base 30 with Base64 alphabet
1322        let b30_b64 = NumeralSystem::new(
1323            Base::new(30).unwrap(),
1324            BaseAlphabet::Base64Standard,
1325        )
1326        .unwrap();
1327        assert_eq!(b30_b64.char_for_digit(0).unwrap(), 'A');
1328        assert_eq!(b30_b64.char_for_digit(20).unwrap(), 'U');
1329        b30_b64.char_for_digit(30).unwrap_err();
1330    }
1331
1332    #[crate::ctb_test]
1333    fn test_digit_conversions() {
1334        // Base 16
1335        assert_eq!(digit_to_char(10, Base::Hex).unwrap(), 'A');
1336        assert_eq!(char_to_digit('a', Base::Hex).unwrap(), 10);
1337        assert_eq!(char_to_digit('A', Base::Hex).unwrap(), 10);
1338        assert_eq!(char_to_digit('F', Base::Hex).unwrap(), 15);
1339        char_to_digit('G', Base::Hex).unwrap_err();
1340
1341        let b64_base = Base::new(64).unwrap();
1342        assert_eq!(digit_to_char(0, b64_base).unwrap(), 'A');
1343        assert_eq!(digit_to_char(25, b64_base).unwrap(), 'Z');
1344        assert_eq!(digit_to_char(26, b64_base).unwrap(), 'a');
1345        assert_eq!(digit_to_char(51, b64_base).unwrap(), 'z');
1346        assert_eq!(digit_to_char(52, b64_base).unwrap(), '0');
1347        assert_eq!(digit_to_char(61, b64_base).unwrap(), '9');
1348        assert_eq!(digit_to_char(62, b64_base).unwrap(), '+');
1349        assert_eq!(digit_to_char(63, b64_base).unwrap(), '/');
1350
1351        assert_eq!(char_to_digit('A', b64_base).unwrap(), 0);
1352        assert_eq!(char_to_digit('Z', b64_base).unwrap(), 25);
1353        assert_eq!(char_to_digit('a', b64_base).unwrap(), 26);
1354        assert_eq!(char_to_digit('z', b64_base).unwrap(), 51);
1355        assert_eq!(char_to_digit('0', b64_base).unwrap(), 52);
1356        assert_eq!(char_to_digit('9', b64_base).unwrap(), 61);
1357        assert_eq!(char_to_digit('+', b64_base).unwrap(), 62);
1358        assert_eq!(char_to_digit('/', b64_base).unwrap(), 63);
1359    }
1360
1361    #[crate::ctb_test]
1362    fn test_parse_and_format_natural() {
1363        let n = parse_natural("1A", Base::Hex).unwrap();
1364        assert_eq!(n, Natural::from(26u32));
1365        assert_eq!(format_natural(&n, Base::Hex, 4).unwrap(), "001A");
1366        assert_eq!(format_natural(&n, Base::Decimal, 1).unwrap(), "26");
1367
1368        let b64_base = Base::new(64).unwrap();
1369        let b64_n = parse_natural("BA", b64_base).unwrap();
1370        // 'B' = 1, 'A' = 0 -> 1 * 64 + 0 = 64
1371        assert_eq!(b64_n, Natural::from(64u32));
1372        assert_eq!(format_natural(&b64_n, b64_base, 3).unwrap(), "ABA");
1373
1374        // Format and parse with custom NumeralSystem
1375        let b30_b64 = NumeralSystem::new(
1376            Base::new(30).unwrap(),
1377            BaseAlphabet::Base64Standard,
1378        )
1379        .unwrap();
1380        let val = Natural::from(25516010u32);
1381        let s = format_natural_system(&val, b30_b64, 0).unwrap();
1382        assert_eq!(s, "BBPBDU");
1383        let parsed = parse_natural_system(&s, b30_b64).unwrap();
1384        assert_eq!(parsed, val);
1385
1386        // Base 1 (unary) tests
1387        let un_val = Natural::from(5u32);
1388        let un_str = format_natural(&un_val, Base::Unary, 0).unwrap();
1389        assert_eq!(un_str, "00000");
1390        let un_parsed = parse_natural(&un_str, Base::Unary).unwrap();
1391        assert_eq!(un_parsed, un_val);
1392
1393        let un_b64_sys =
1394            NumeralSystem::new(Base::Unary, BaseAlphabet::Base64Standard)
1395                .unwrap();
1396        let un_b64_str = format_natural_system(&un_val, un_b64_sys, 0).unwrap();
1397        assert_eq!(un_b64_str, "AAAAA");
1398        let un_b64_parsed =
1399            parse_natural_system(&un_b64_str, un_b64_sys).unwrap();
1400        assert_eq!(un_b64_parsed, un_val);
1401    }
1402
1403    #[crate::ctb_test]
1404    fn test_parse_prefixes_behavior() {
1405        let default_settings = BaseStringFormatSettings::default();
1406
1407        // 1. parse_prefixes = true (default): strips 0x in hex
1408        let (res, log) =
1409            base_to_base_string("0x1A", 16, 10, &default_settings).unwrap();
1410        assert_eq!(res, "26");
1411        assert!(!log.has_warnings());
1412
1413        // 2. parse_prefixes = false in base 16 where 'x' is NOT a digit:
1414        // '0' is parsed as 0, 'x' is non-digit, '1A' is 26 -> output "0 26"
1415        let no_prefix_settings = BaseStringFormatSettings {
1416            parse_prefixes: false,
1417            ..Default::default()
1418        };
1419        let (res, log) =
1420            base_to_base_string("0x1A", 16, 10, &no_prefix_settings).unwrap();
1421        assert_eq!(res, "0 26");
1422        assert!(log.has_warnings());
1423
1424        // 3. parse_prefixes = false in base 16 with '0b' prefix:
1425        // In base 16, 'b' IS a valid hex digit (value 11), so "0b10" parses as
1426        // a single hex number: 0xB10 = 11 * 256 + 1 * 16 = 2832
1427        let (res, _log) =
1428            base_to_base_string("0b10", 16, 10, &no_prefix_settings).unwrap();
1429        assert_eq!(res, "2832");
1430
1431        // 4. parse_prefixes = false in base 36 where 'x' IS a digit (value 33):
1432        // "0x10" parses as single base-36 number: 33 * 36^2 + 1 * 36 = 42804
1433        let (res, _log) =
1434            base_to_base_string("0x10", 36, 10, &no_prefix_settings).unwrap();
1435        assert_eq!(res, "42804");
1436    }
1437
1438    #[crate::ctb_test]
1439    fn test_filter_and_collapse_options() {
1440        // filter_chars = true (default): non-digits stripped, separated by space
1441        let default_settings = BaseStringFormatSettings::default();
1442        let (res, _) =
1443            base_to_base_string("10, 20, 30", 10, 16, &default_settings)
1444                .unwrap();
1445        assert_eq!(res, "A 14 1E");
1446
1447        // filter_chars = false: literal delimiters preserved
1448        let raw_delim_settings = BaseStringFormatSettings {
1449            filter_chars: false,
1450            separator: String::new(),
1451            ..Default::default()
1452        };
1453        let (res, _) =
1454            base_to_base_string("10, 20, 30", 10, 16, &raw_delim_settings)
1455                .unwrap();
1456        assert_eq!(res, "A, 14, 1E");
1457
1458        // collapse_filtered = true: inline non-digits (like '_') do not break numbers
1459        let collapse_settings = BaseStringFormatSettings {
1460            collapse_filtered: true,
1461            ..Default::default()
1462        };
1463        let (res, _) =
1464            base_to_base_string("10_000", 10, 10, &collapse_settings).unwrap();
1465        assert_eq!(res, "10000");
1466
1467        // collapse_only = ["_"]: only '_' is collapsed inline without warnings
1468        let collapse_only_settings = BaseStringFormatSettings {
1469            collapse_only: vec!["_".to_string()],
1470            ..Default::default()
1471        };
1472        let (res, log) =
1473            base_to_base_string("10_000", 10, 10, &collapse_only_settings)
1474                .unwrap();
1475        assert_eq!(res, "10000");
1476        assert!(!log.has_warnings());
1477    }
1478
1479    #[crate::ctb_test]
1480    fn test_padding_modes() {
1481        // Fixed pad_l = 4
1482        let pad_l_settings = BaseStringFormatSettings {
1483            pad: BaseConversionPaddingMode {
1484                pad_l: 4,
1485                pad_fit: false,
1486            },
1487            ..Default::default()
1488        };
1489        let (res, _) =
1490            base_to_base_string("5", 10, 16, &pad_l_settings).unwrap();
1491        assert_eq!(res, "0005");
1492
1493        // pad_fit with limit = 255 in hex (pads to 2 hex digits)
1494        let pad_fit_settings = BaseStringFormatSettings {
1495            limit: 255,
1496            pad: BaseConversionPaddingMode {
1497                pad_l: 0,
1498                pad_fit: true,
1499            },
1500            ..Default::default()
1501        };
1502        let (res, _) =
1503            base_to_base_string("5", 10, 16, &pad_fit_settings).unwrap();
1504        assert_eq!(res, "05");
1505
1506        // pad_fit with limit = 255 in binary (pads to 8 binary digits)
1507        let (res, _) =
1508            base_to_base_string("5", 10, 2, &pad_fit_settings).unwrap();
1509        assert_eq!(res, "00000101");
1510    }
1511
1512    #[crate::ctb_test]
1513    fn test_base_greater_than_36_formatting() {
1514        // 1. Convert decimal to base 64 with prefix, separator, and padding
1515        let b64_out_settings = BaseStringFormatSettings {
1516            prefix: "64#".to_string(),
1517            separator: ", ".to_string(),
1518            pad: BaseConversionPaddingMode {
1519                pad_l: 3,
1520                pad_fit: false,
1521            },
1522            output_alphabet: BaseAlphabet::Base64Standard,
1523            ..Default::default()
1524        };
1525        // 0 -> 'AAA', 1 -> 'AAB', 63 -> 'AA/', 64 -> 'ABA', 255 -> 'AD/'
1526        let (res, log) =
1527            base_to_base_string("0 1 63 64 255", 10, 64, &b64_out_settings)
1528                .unwrap();
1529        assert_eq!(res, "64#AAA, 64#AAB, 64#AA/, 64#ABA, 64#AD/");
1530        assert!(!log.has_warnings());
1531
1532        // 2. Convert base 64 input to hex output
1533        let b64_in_settings = BaseStringFormatSettings {
1534            input_alphabet: BaseAlphabet::Base64Standard,
1535            separator: " ".to_string(),
1536            lowercase: true,
1537            ..Default::default()
1538        };
1539        // 'BA' = 64 (0x40), 'D/' = 255 (0xff)
1540        let (res, log) =
1541            base_to_base_string("BA D/", 64, 16, &b64_in_settings).unwrap();
1542        assert_eq!(res, "40 ff");
1543        assert!(!log.has_warnings());
1544
1545        // 3. Format base 64 in-place with format_base_string
1546        let b64_format_settings = BaseStringFormatSettings {
1547            prefix: "@".to_string(),
1548            separator: " | ".to_string(),
1549            pad: BaseConversionPaddingMode {
1550                pad_l: 4,
1551                pad_fit: false,
1552            },
1553            input_alphabet: BaseAlphabet::Base64Standard,
1554            output_alphabet: BaseAlphabet::Base64Standard,
1555            ..Default::default()
1556        };
1557        let (res, log) =
1558            format_base_string("BA D/", 64, &b64_format_settings).unwrap();
1559        assert_eq!(res, "@AABA | @AAD/");
1560        assert!(!log.has_warnings());
1561
1562        // 4. Custom intermediate base > 36 (e.g. base 48)
1563        let dec_to_b48 = BaseStringFormatSettings {
1564            input_alphabet: BaseAlphabet::Standard,
1565            output_alphabet: BaseAlphabet::Base64Standard,
1566            ..Default::default()
1567        };
1568        // In base64 alphabet: index 47 = 'v', 48 = 'w'.
1569        // 47 in base 48 is 'v'.
1570        // 48 in base 48 is 1 * 48 + 0 = 'BA'.
1571        let (res, log) =
1572            base_to_base_string("47 48", 10, 48, &dec_to_b48).unwrap();
1573        assert_eq!(res, "v BA");
1574        assert!(!log.has_warnings());
1575
1576        // Convert back from base 48 to decimal
1577        let b48_to_dec = BaseStringFormatSettings {
1578            input_alphabet: BaseAlphabet::Base64Standard,
1579            output_alphabet: BaseAlphabet::Standard,
1580            ..Default::default()
1581        };
1582        let (res, log) =
1583            base_to_base_string("v BA", 48, 10, &b48_to_dec).unwrap();
1584        assert_eq!(res, "47 48");
1585        assert!(!log.has_warnings());
1586
1587        // Converting directly between two different bases > 36:
1588        // 'BA' in base 48 is 48. In base 64, 48 is 'w'.
1589        let b48_to_b64 = BaseStringFormatSettings {
1590            input_alphabet: BaseAlphabet::Base64Standard,
1591            output_alphabet: BaseAlphabet::Base64Standard,
1592            ..Default::default()
1593        };
1594        let (res, log) =
1595            base_to_base_string("BA", 48, 64, &b48_to_b64).unwrap();
1596        assert_eq!(res, "w");
1597        assert!(!log.has_warnings());
1598
1599        // 5. Case sensitivity preservation: lowercase setting must not alter
1600        // Base64Standard letters because 'A' (0) != 'a' (26).
1601        let b64_case_settings = BaseStringFormatSettings {
1602            lowercase: true,
1603            output_alphabet: BaseAlphabet::Base64Standard,
1604            ..Default::default()
1605        };
1606        let (res, _) =
1607            base_to_base_string("0 26", 10, 64, &b64_case_settings).unwrap();
1608        assert_eq!(res, "A a");
1609
1610        // 6. Chunk limit with base 64:
1611        // Limit = 63 requires 1 digit in base 64 (0..=63) -> "BABA" is chunked
1612        // into 1-digit numbers: 'B' (1), 'A' (0), 'B' (1), 'A' (0) -> "1 0 1 0".
1613        let b64_1digit_limit = BaseStringFormatSettings {
1614            limit: 63,
1615            input_alphabet: BaseAlphabet::Base64Standard,
1616            ..Default::default()
1617        };
1618        let (res, _) =
1619            base_to_base_string("BABA", 64, 10, &b64_1digit_limit).unwrap();
1620        assert_eq!(res, "1 0 1 0");
1621
1622        // Limit = 4095 requires 2 digits in base 64 (0..=4095) -> "BABA" is
1623        // chunked into 2-digit numbers: "BA" (64), "BA" (64) -> "64 64".
1624        let b64_2digit_limit = BaseStringFormatSettings {
1625            limit: 4095,
1626            input_alphabet: BaseAlphabet::Base64Standard,
1627            ..Default::default()
1628        };
1629        let (res, _) =
1630            base_to_base_string("BABA", 64, 10, &b64_2digit_limit).unwrap();
1631        assert_eq!(res, "64 64");
1632    }
1633
1634    #[crate::ctb_test]
1635    fn test_base1_unary_formatting_and_parsing() {
1636        let default_settings = BaseStringFormatSettings::default();
1637
1638        // Single number conversions
1639        let (res0, _) =
1640            base_to_base_string("0", 10, 1, &default_settings).unwrap();
1641        assert_eq!(res0, "");
1642
1643        let (res1, _) =
1644            base_to_base_string("1", 10, 1, &default_settings).unwrap();
1645        assert_eq!(res1, "0");
1646
1647        let (res2, _) =
1648            base_to_base_string("2", 10, 1, &default_settings).unwrap();
1649        assert_eq!(res2, "00");
1650
1651        let (res3, _) =
1652            base_to_base_string("3", 10, 1, &default_settings).unwrap();
1653        assert_eq!(res3, "000");
1654
1655        // Converting back from base 1 to base 10
1656        let (dec0, _) =
1657            base_to_base_string("", 1, 10, &default_settings).unwrap();
1658        assert_eq!(dec0, "0");
1659
1660        let (dec1, _) =
1661            base_to_base_string("0", 1, 10, &default_settings).unwrap();
1662        assert_eq!(dec1, "1");
1663
1664        let (dec2, _) =
1665            base_to_base_string("00", 1, 10, &default_settings).unwrap();
1666        assert_eq!(dec2, "2");
1667
1668        let (dec3, _) =
1669            base_to_base_string("000", 1, 10, &default_settings).unwrap();
1670        assert_eq!(dec3, "3");
1671
1672        // Multiple numbers in a string: "0 1 2 3" -> " 0 00 000"
1673        let (multi, _) =
1674            base_to_base_string("0 1 2 3", 10, 1, &default_settings).unwrap();
1675        assert_eq!(multi, " 0 00 000");
1676
1677        // Explicit pad_l > 1 in base 1
1678        let pad4_settings = BaseStringFormatSettings {
1679            pad: BaseConversionPaddingMode {
1680                pad_l: 4,
1681                pad_fit: false,
1682            },
1683            ..Default::default()
1684        };
1685        let (padded0, _) =
1686            base_to_base_string("0", 10, 1, &pad4_settings).unwrap();
1687        assert_eq!(padded0, "0000");
1688
1689        let (padded2, _) =
1690            base_to_base_string("2", 10, 1, &pad4_settings).unwrap();
1691        assert_eq!(padded2, "0000");
1692
1693        let (padded5, _) =
1694            base_to_base_string("5", 10, 1, &pad4_settings).unwrap();
1695        assert_eq!(padded5, "00000");
1696    }
1697}