1use alloc::string::String;
6use core::fmt;
7use core::str::FromStr;
8
9use internals::write_err;
10
11#[derive(Debug, Clone, PartialEq, Eq)]
21#[non_exhaustive]
22pub struct ParseIntError {
23 pub(crate) input: String,
24 bits: u8,
26 is_signed: bool,
30 pub(crate) source: core::num::ParseIntError,
31}
32
33impl ParseIntError {
34 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
67pub 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
81pub 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 is_signed: T::try_from(-1i8).is_ok(),
94 source: error,
95 }
96 })
97}
98
99pub 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
112pub 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
125pub(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#[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#[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#[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#[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}