satsnet_units/
parse.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! Parsing utilities.
4
5use alloc::string::String;
6use core::fmt;
7use core::str::FromStr;
8
9use internals::write_err;
10
11/// Error with rich context returned when a string can't be parsed as an integer.
12///
13/// This is an extension of [`core::num::ParseIntError`], which carries the input that failed to
14/// parse as well as type information. As a result it provides very informative error messages that
15/// make it easier to understand the problem and correct mistakes.
16///
17/// Note that this is larger than the type from `core` so if it's passed through a deep call stack
18/// in a performance-critical application you may want to box it or throw away the context by
19/// converting to `core` type.
20#[derive(Debug, Clone, PartialEq, Eq)]
21#[non_exhaustive]
22pub struct ParseIntError {
23    pub(crate) input: String,
24    // for displaying - see Display impl with nice error message below
25    bits: u8,
26    // We could represent this as a single bit but it wouldn't actually derease the cost of moving
27    // the struct because String contains pointers so there will be padding of bits at least
28    // pointer_size - 1 bytes: min 1B in practice.
29    is_signed: bool,
30    pub(crate) source: core::num::ParseIntError,
31}
32
33impl ParseIntError {
34    /// Returns the input that was attempted to be parsed.
35    pub fn input(&self) -> &str {
36        &self.input
37    }
38}
39
40impl fmt::Display for ParseIntError {
41    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
42        let signed = if self.is_signed { "signed" } else { "unsigned" };
43        let n = if self.bits == 8 { "n" } else { "" };
44        write_err!(f, "failed to parse '{}' as a{} {}-bit {} integer", self.input, n, self.bits, signed; self.source)
45    }
46}
47
48#[cfg(feature = "std")]
49impl std::error::Error for ParseIntError {
50    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
51        Some(&self.source)
52    }
53}
54
55impl From<ParseIntError> for core::num::ParseIntError {
56    fn from(value: ParseIntError) -> Self {
57        value.source
58    }
59}
60
61impl AsRef<core::num::ParseIntError> for ParseIntError {
62    fn as_ref(&self) -> &core::num::ParseIntError {
63        &self.source
64    }
65}
66
67/// Not strictly necessary but serves as a lint - avoids weird behavior if someone accidentally
68/// passes non-integer to the `parse()` function.
69pub trait Integer: FromStr<Err = core::num::ParseIntError> + TryFrom<i8> + Sized {}
70
71macro_rules! impl_integer {
72    ($($type:ty),* $(,)?) => {
73        $(
74        impl Integer for $type {}
75        )*
76    }
77}
78
79impl_integer!(u8, i8, u16, i16, u32, i32, u64, i64, u128, i128);
80
81/// Parses the input string as an integer returning an error carrying rich context.
82///
83/// If the caller owns `String` or `Box<str>` which is not used later it's better to pass it as
84/// owned since it avoids allocation in error case.
85pub fn int<T: Integer, S: AsRef<str> + Into<String>>(s: S) -> Result<T, ParseIntError> {
86    s.as_ref().parse().map_err(|error| {
87        ParseIntError {
88            input: s.into(),
89            bits: u8::try_from(core::mem::size_of::<T>() * 8).expect("max is 128 bits for u128"),
90            // We detect if the type is signed by checking if -1 can be represented by it
91            // this way we don't have to implement special traits and optimizer will get rid of the
92            // computation.
93            is_signed: T::try_from(-1i8).is_ok(),
94            source: error,
95        }
96    })
97}
98
99/// Parses a `u32` from a hex string.
100///
101/// Input string may or may not contain a `0x` prefix.
102pub fn hex_u32<S: AsRef<str> + Into<String>>(s: S) -> Result<u32, ParseIntError> {
103    let stripped = strip_hex_prefix(s.as_ref());
104    u32::from_str_radix(stripped, 16).map_err(|error| ParseIntError {
105        input: s.into(),
106        bits: 32,
107        is_signed: false,
108        source: error,
109    })
110}
111
112/// Parses a `u128` from a hex string.
113///
114/// Input string may or may not contain a `0x` prefix.
115pub fn hex_u128<S: AsRef<str> + Into<String>>(s: S) -> Result<u128, ParseIntError> {
116    let stripped = strip_hex_prefix(s.as_ref());
117    u128::from_str_radix(stripped, 16).map_err(|error| ParseIntError {
118        input: s.into(),
119        bits: 128,
120        is_signed: false,
121        source: error,
122    })
123}
124
125/// Strips the hex prefix off `s` if one is present.
126pub(crate) fn strip_hex_prefix(s: &str) -> &str {
127    if let Some(stripped) = s.strip_prefix("0x") {
128        stripped
129    } else if let Some(stripped) = s.strip_prefix("0X") {
130        stripped
131    } else {
132        s
133    }
134}
135
136/// Implements `TryFrom<$from> for $to` using `parse::int`, mapping the output using infallible
137/// conversion function `fn`.
138#[macro_export]
139macro_rules! impl_tryfrom_str_from_int_infallible {
140    ($($from:ty, $to:ident, $inner:ident, $fn:ident);*) => {
141        $(
142        impl core::convert::TryFrom<$from> for $to {
143            type Error = $crate::parse::ParseIntError;
144
145            fn try_from(s: $from) -> core::result::Result<Self, Self::Error> {
146                $crate::parse::int::<$inner, $from>(s).map($to::$fn)
147            }
148        }
149        )*
150    }
151}
152
153/// Implements `FromStr` and `TryFrom<{&str, String, Box<str>}> for $to` using `parse::int`, mapping
154/// the output using infallible conversion function `fn`.
155///
156/// The `Error` type is `ParseIntError`
157#[macro_export]
158macro_rules! impl_parse_str_from_int_infallible {
159    ($to:ident, $inner:ident, $fn:ident) => {
160        #[cfg(all(feature = "alloc", not(feature = "std")))]
161        $crate::impl_tryfrom_str_from_int_infallible!(&str, $to, $inner, $fn; alloc::string::String, $to, $inner, $fn; alloc::boxed::Box<str>, $to, $inner, $fn);
162        #[cfg(feature = "std")]
163        $crate::impl_tryfrom_str_from_int_infallible!(&str, $to, $inner, $fn; std::string::String, $to, $inner, $fn; std::boxed::Box<str>, $to, $inner, $fn);
164
165        impl core::str::FromStr for $to {
166            type Err = $crate::parse::ParseIntError;
167
168            fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {
169                $crate::parse::int::<$inner, &str>(s).map($to::$fn)
170            }
171        }
172
173    }
174}
175
176/// Implements `TryFrom<$from> for $to`.
177#[macro_export]
178macro_rules! impl_tryfrom_str {
179    ($($from:ty, $to:ty, $err:ty, $inner_fn:expr);*) => {
180        $(
181            impl core::convert::TryFrom<$from> for $to {
182                type Error = $err;
183
184                fn try_from(s: $from) -> core::result::Result<Self, Self::Error> {
185                    $inner_fn(s)
186                }
187            }
188        )*
189    }
190}
191
192/// Implements standard parsing traits for `$type` by calling into `$inner_fn`.
193#[macro_export]
194macro_rules! impl_parse_str {
195    ($to:ty, $err:ty, $inner_fn:expr) => {
196        $crate::impl_tryfrom_str!(&str, $to, $err, $inner_fn; String, $to, $err, $inner_fn; Box<str>, $to, $err, $inner_fn);
197
198        impl core::str::FromStr for $to {
199            type Err = $err;
200
201            fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {
202                $inner_fn(s)
203            }
204        }
205    }
206}