Skip to main content

malachite_base/num/conversion/string/
from_string.rs

1// Copyright © 2026 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::num::conversion::traits::{FromStringBase, WrappingFrom};
10
11/// Produces a digit from a byte corresponding to a numeric or alphabetic (lower- or uppercase)
12/// [`char`] that represents the digit.
13///
14/// Bytes corresponding to `char`s from '0' to '9' become digits 0 to 9. Bytes corresponding to
15/// `char`s from 'a' to 'z' become digits 10 to 35. Bytes corresponding to `char`s from 'A' to 'Z'
16/// also become digits 10 to 35. Passing a byte that does not correspond to any of these `char`s
17/// yields `None`.
18///
19/// # Worst-case complexity
20/// Constant time and additional memory.
21///
22/// # Examples
23/// ```
24/// use malachite_base::num::conversion::string::from_string::digit_from_display_byte;
25///
26/// assert_eq!(digit_from_display_byte(b'0'), Some(0));
27/// assert_eq!(digit_from_display_byte(b'9'), Some(9));
28/// assert_eq!(digit_from_display_byte(b'a'), Some(10));
29/// assert_eq!(digit_from_display_byte(b'z'), Some(35));
30/// assert_eq!(digit_from_display_byte(b'A'), Some(10));
31/// assert_eq!(digit_from_display_byte(b'Z'), Some(35));
32/// assert_eq!(digit_from_display_byte(b' '), None);
33/// assert_eq!(digit_from_display_byte(b'!'), None);
34/// ```
35pub const fn digit_from_display_byte(b: u8) -> Option<u8> {
36    match b {
37        b'0'..=b'9' => Some(b - b'0'),
38        b'a'..=b'z' => Some(b - b'a' + 10),
39        b'A'..=b'Z' => Some(b - b'A' + 10),
40        _ => None,
41    }
42}
43
44/// Converts a byte corresponding to a numeric or alphabetic [`char`] to a digit in the large-base
45/// alphabet used for bases from 37 through 62, in which the uppercase and lowercase letters are
46/// distinct digits: `b'0'` through `b'9'` represent 0 through 9, `b'A'` through `b'Z'` represent 10
47/// through 35, and `b'a'` through `b'z'` represent 36 through 61, as in GMP.
48///
49/// Bytes that don't correspond to any digit are converted to [`None`].
50///
51/// # Worst-case complexity
52/// Constant time and additional memory.
53///
54/// # Examples
55/// ```
56/// use malachite_base::num::conversion::string::from_string::digit_from_display_byte_large;
57///
58/// assert_eq!(digit_from_display_byte_large(b'0'), Some(0));
59/// assert_eq!(digit_from_display_byte_large(b'A'), Some(10));
60/// assert_eq!(digit_from_display_byte_large(b'Z'), Some(35));
61/// assert_eq!(digit_from_display_byte_large(b'a'), Some(36));
62/// assert_eq!(digit_from_display_byte_large(b'z'), Some(61));
63/// assert_eq!(digit_from_display_byte_large(b'!'), None);
64/// ```
65pub const fn digit_from_display_byte_large(b: u8) -> Option<u8> {
66    match b {
67        b'0'..=b'9' => Some(b - b'0'),
68        b'A'..=b'Z' => Some(b - b'A' + 10),
69        b'a'..=b'z' => Some(b - b'a' + 36),
70        _ => None,
71    }
72}
73
74macro_rules! impl_from_string_base_unsigned {
75    ($t:ident) => {
76        impl FromStringBase for $t {
77            /// For bases up to 36, this is a wrapper over the `from_str_radix` functions in the
78            /// standard library, for example [this one](u32::from_str_radix). For bases from 37
79            /// through 62, which `from_str_radix` does not support, the digits are read from the
80            /// case-sensitive large-base alphabet (see [`digit_from_display_byte_large`]), as in
81            /// GMP.
82            ///
83            /// # Worst-case complexity
84            /// $T(n) = O(n)$
85            ///
86            /// $M(n) = O(1)$
87            ///
88            /// where $T$ is time, $M$ is additional memory, and $n$ is `s.len()`.
89            ///
90            /// # Panics
91            /// Panics if `base` is less than 2 or greater than 62.
92            fn from_string_base(base: u8, s: &str) -> Option<Self> {
93                assert!((2..=62).contains(&base), "base out of range");
94                if base <= 36 {
95                    return $t::from_str_radix(s, u32::from(base)).ok();
96                }
97                // like `from_str_radix`, allow a single leading `+`
98                let s = s.strip_prefix('+').unwrap_or(s);
99                if s.is_empty() {
100                    return None;
101                }
102                let t_base = $t::wrapping_from(base);
103                let mut x: $t = 0;
104                for b in s.bytes() {
105                    let digit = digit_from_display_byte_large(b)?;
106                    if digit >= base {
107                        return None;
108                    }
109                    x = x
110                        .checked_mul(t_base)?
111                        .checked_add($t::wrapping_from(digit))?;
112                }
113                Some(x)
114            }
115        }
116    };
117}
118apply_to_unsigneds!(impl_from_string_base_unsigned);
119
120macro_rules! impl_from_string_base_signed {
121    ($t:ident) => {
122        impl FromStringBase for $t {
123            /// For bases up to 36, this is a wrapper over the `from_str_radix` functions in the
124            /// standard library, for example [this one](i32::from_str_radix). For bases from 37
125            /// through 62, which `from_str_radix` does not support, the digits are read from the
126            /// case-sensitive large-base alphabet (see [`digit_from_display_byte_large`]), as in
127            /// GMP.
128            ///
129            /// # Worst-case complexity
130            /// $T(n) = O(n)$
131            ///
132            /// $M(n) = O(1)$
133            ///
134            /// where $T$ is time, $M$ is additional memory, and $n$ is `s.len()`.
135            ///
136            /// # Panics
137            /// Panics if `base` is less than 2 or greater than 62.
138            fn from_string_base(base: u8, s: &str) -> Option<Self> {
139                assert!((2..=62).contains(&base), "base out of range");
140                if base <= 36 {
141                    return $t::from_str_radix(s, u32::from(base)).ok();
142                }
143                // like `from_str_radix`, allow a single leading sign; accumulate negatively when it
144                // is a `-`, so that `MIN` parses
145                let (neg, s) = if let Some(r) = s.strip_prefix('-') {
146                    (true, r)
147                } else {
148                    (false, s.strip_prefix('+').unwrap_or(s))
149                };
150                if s.is_empty() {
151                    return None;
152                }
153                let t_base = $t::wrapping_from(base);
154                let mut x: $t = 0;
155                for b in s.bytes() {
156                    let digit = digit_from_display_byte_large(b)?;
157                    if digit >= base {
158                        return None;
159                    }
160                    let t_digit = $t::wrapping_from(digit);
161                    x = x.checked_mul(t_base)?;
162                    x = if neg {
163                        x.checked_sub(t_digit)?
164                    } else {
165                        x.checked_add(t_digit)?
166                    };
167                }
168                Some(x)
169            }
170        }
171    };
172}
173apply_to_signeds!(impl_from_string_base_signed);