Skip to main content

brush_core/
int_utils.rs

1//! Generic utilities.
2
3use crate::error;
4
5/// Trait for integer types that support parsing from strings with a radix.
6pub trait ParseIntRadix: Sized {
7    /// Parse a string as this integer type using the specified radix.
8    fn from_str_radix(s: &str, radix: u32) -> Result<Self, std::num::ParseIntError>;
9
10    /// Returns the name of the integer type as a static string.
11    fn type_name() -> &'static str;
12}
13
14macro_rules! impl_parse_int_radix {
15    ($t:ty) => {
16        impl ParseIntRadix for $t {
17            fn from_str_radix(s: &str, radix: u32) -> Result<Self, std::num::ParseIntError> {
18                Self::from_str_radix(s, radix)
19            }
20
21            fn type_name() -> &'static str {
22                stringify!($t)
23            }
24        }
25    };
26}
27
28impl_parse_int_radix!(u8);
29impl_parse_int_radix!(u16);
30impl_parse_int_radix!(i32);
31impl_parse_int_radix!(u32);
32impl_parse_int_radix!(usize);
33
34/// Parse the given string as an integer in the specified radix.
35///
36/// # Arguments
37///
38/// * `s` - The string to parse.
39/// * `radix` - The base to use for parsing.
40///
41/// # Type Parameters
42///
43/// * `T` - The integer type to parse. Must implement `ParseIntRadix`.
44///
45/// # Examples
46///
47/// ```
48/// use brush_core::int_utils::parse;
49///
50/// let result: u32 = parse("42", 10)?;
51/// assert_eq!(result, 42);
52///
53/// let result: u8 = parse("FF", 16)?;
54/// assert_eq!(result, 255);
55/// # Ok::<(), brush_core::error::Error>(())
56/// ```
57pub fn parse<T: ParseIntRadix>(s: &str, radix: u32) -> Result<T, error::Error> {
58    T::from_str_radix(s, radix).map_err(|inner| {
59        error::ErrorKind::IntParseError {
60            s: s.to_owned(),
61            int_type_name: T::type_name(),
62            radix,
63            inner,
64        }
65        .into()
66    })
67}