malachite_base/num/conversion/string/from_string.rs
1// Copyright © 2025 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;
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
44macro_rules! impl_from_string_base {
45 ($t:ident) => {
46 impl FromStringBase for $t {
47 /// This is a wrapper over the `from_str_radix` functions in the standard library, for
48 /// example [this one](u32::from_str_radix).
49 #[inline]
50 fn from_string_base(base: u8, s: &str) -> Option<Self> {
51 $t::from_str_radix(s, u32::from(base)).ok()
52 }
53 }
54 };
55}
56apply_to_primitive_ints!(impl_from_string_base);