use alloc::string::String;
use core::fmt;
use core::str::FromStr;
use internals::write_err;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ParseIntError {
pub(crate) input: String,
bits: u8,
is_signed: bool,
pub(crate) source: core::num::ParseIntError,
}
impl ParseIntError {
pub fn input(&self) -> &str { &self.input }
}
impl fmt::Display for ParseIntError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let signed = if self.is_signed { "signed" } else { "unsigned" };
let n = if self.bits == 8 { "n" } else { "" };
write_err!(f, "failed to parse '{}' as a{} {}-bit {} integer", self.input, n, self.bits, signed; self.source)
}
}
#[cfg(feature = "std")]
impl std::error::Error for ParseIntError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.source) }
}
impl From<ParseIntError> for core::num::ParseIntError {
fn from(value: ParseIntError) -> Self { value.source }
}
impl AsRef<core::num::ParseIntError> for ParseIntError {
fn as_ref(&self) -> &core::num::ParseIntError { &self.source }
}
pub trait Integer: FromStr<Err = core::num::ParseIntError> + TryFrom<i8> + Sized {}
macro_rules! impl_integer {
($($type:ty),* $(,)?) => {
$(
impl Integer for $type {}
)*
}
}
impl_integer!(u8, i8, u16, i16, u32, i32, u64, i64, u128, i128);
pub fn int<T: Integer, S: AsRef<str> + Into<String>>(s: S) -> Result<T, ParseIntError> {
s.as_ref().parse().map_err(|error| {
ParseIntError {
input: s.into(),
bits: u8::try_from(core::mem::size_of::<T>() * 8).expect("max is 128 bits for u128"),
is_signed: T::try_from(-1i8).is_ok(),
source: error,
}
})
}
#[macro_export]
macro_rules! impl_tryfrom_str_from_int_infallible {
($($from:ty, $to:ident, $inner:ident, $fn:ident);*) => {
$(
impl core::convert::TryFrom<$from> for $to {
type Error = $crate::parse::ParseIntError;
fn try_from(s: $from) -> core::result::Result<Self, Self::Error> {
$crate::parse::int::<$inner, $from>(s).map($to::$fn)
}
}
)*
}
}
#[macro_export]
macro_rules! impl_parse_str_from_int_infallible {
($to:ident, $inner:ident, $fn:ident) => {
#[cfg(all(feature = "alloc", not(feature = "std")))]
$crate::impl_tryfrom_str_from_int_infallible!(&str, $to, $inner, $fn; alloc::string::String, $to, $inner, $fn; alloc::boxed::Box<str>, $to, $inner, $fn);
#[cfg(feature = "std")]
$crate::impl_tryfrom_str_from_int_infallible!(&str, $to, $inner, $fn; std::string::String, $to, $inner, $fn; std::boxed::Box<str>, $to, $inner, $fn);
impl core::str::FromStr for $to {
type Err = $crate::parse::ParseIntError;
fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {
$crate::parse::int::<$inner, &str>(s).map($to::$fn)
}
}
}
}
#[macro_export]
macro_rules! impl_tryfrom_str {
($($from:ty, $to:ty, $err:ty, $inner_fn:expr);*) => {
$(
impl core::convert::TryFrom<$from> for $to {
type Error = $err;
fn try_from(s: $from) -> core::result::Result<Self, Self::Error> {
$inner_fn(s)
}
}
)*
}
}
#[macro_export]
macro_rules! impl_parse_str {
($to:ty, $err:ty, $inner_fn:expr) => {
$crate::impl_tryfrom_str!(&str, $to, $err, $inner_fn; String, $to, $err, $inner_fn; Box<str>, $to, $err, $inner_fn);
impl core::str::FromStr for $to {
type Err = $err;
fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {
$inner_fn(s)
}
}
}
}
pub fn hex_remove_prefix(s: &str) -> Result<&str, PrefixedHexError> {
if let Some(checked) = s.strip_prefix("0x") {
Ok(checked)
} else if let Some(checked) = s.strip_prefix("0X") {
Ok(checked)
} else {
Err(MissingPrefixError::new(s.into()).into())
}
}
pub fn hex_check_unprefixed(s: &str) -> Result<&str, UnprefixedHexError> {
if s.starts_with("0x") || s.starts_with("0X") {
return Err(ContainsPrefixError::new(s.into()).into());
}
Ok(s)
}
pub fn hex_u32(s: &str) -> Result<u32, ParseIntError> {
let unchecked = hex_remove_optional_prefix(s);
Ok(hex_u32_unchecked(unchecked)?)
}
pub fn hex_u32_prefixed(s: &str) -> Result<u32, PrefixedHexError> {
let checked = hex_remove_prefix(s)?;
Ok(hex_u32_unchecked(checked)?)
}
pub fn hex_u32_unprefixed(s: &str) -> Result<u32, UnprefixedHexError> {
let checked = hex_check_unprefixed(s)?;
Ok(hex_u32_unchecked(checked)?)
}
pub fn hex_u32_unchecked(s: &str) -> Result<u32, ParseIntError> {
u32::from_str_radix(s, 16).map_err(|error| ParseIntError {
input: s.into(),
bits: 32,
is_signed: false,
source: error,
})
}
pub fn hex_u128(s: &str) -> Result<u128, ParseIntError> {
let unchecked = hex_remove_optional_prefix(s);
Ok(hex_u128_unchecked(unchecked)?)
}
pub fn hex_u128_prefixed(s: &str) -> Result<u128, PrefixedHexError> {
let checked = hex_remove_prefix(s)?;
Ok(hex_u128_unchecked(checked)?)
}
pub fn hex_u128_unprefixed(s: &str) -> Result<u128, UnprefixedHexError> {
let checked = hex_check_unprefixed(s)?;
Ok(hex_u128_unchecked(checked)?)
}
pub fn hex_u128_unchecked(s: &str) -> Result<u128, ParseIntError> {
u128::from_str_radix(s, 16).map_err(|error| ParseIntError {
input: s.into(),
bits: 128,
is_signed: false,
source: error,
})
}
pub(crate) fn hex_remove_optional_prefix(s: &str) -> &str {
if let Some(stripped) = s.strip_prefix("0x") {
stripped
} else if let Some(stripped) = s.strip_prefix("0X") {
stripped
} else {
s
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum PrefixedHexError {
MissingPrefix(MissingPrefixError),
ParseInt(ParseIntError),
}
impl fmt::Display for PrefixedHexError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use PrefixedHexError::*;
match *self {
MissingPrefix(ref e) => write_err!(f, "hex string is missing prefix"; e),
ParseInt(ref e) => write_err!(f, "prefixed hex string invalid int"; e),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for PrefixedHexError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use PrefixedHexError::*;
match *self {
MissingPrefix(ref e) => Some(e),
ParseInt(ref e) => Some(e),
}
}
}
impl From<MissingPrefixError> for PrefixedHexError {
fn from(e: MissingPrefixError) -> Self { Self::MissingPrefix(e) }
}
impl From<ParseIntError> for PrefixedHexError {
fn from(e: ParseIntError) -> Self { Self::ParseInt(e) }
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum UnprefixedHexError {
ContainsPrefix(ContainsPrefixError),
ParseInt(ParseIntError),
}
impl fmt::Display for UnprefixedHexError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use UnprefixedHexError::*;
match *self {
ContainsPrefix(ref e) => write_err!(f, "hex string is contains prefix"; e),
ParseInt(ref e) => write_err!(f, "hex string parse int"; e),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for UnprefixedHexError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use UnprefixedHexError::*;
match *self {
ContainsPrefix(ref e) => Some(e),
ParseInt(ref e) => Some(e),
}
}
}
impl From<ContainsPrefixError> for UnprefixedHexError {
fn from(e: ContainsPrefixError) -> Self { Self::ContainsPrefix(e) }
}
impl From<ParseIntError> for UnprefixedHexError {
fn from(e: ParseIntError) -> Self { Self::ParseInt(e) }
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct MissingPrefixError {
hex: String,
}
impl MissingPrefixError {
pub(crate) fn new(hex: String) -> Self { Self { hex } }
}
impl fmt::Display for MissingPrefixError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "hex string is missing a prefix (e.g. 0x): {}", self.hex)
}
}
#[cfg(feature = "std")]
impl std::error::Error for MissingPrefixError {}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ContainsPrefixError {
hex: String,
}
impl ContainsPrefixError {
pub(crate) fn new(hex: String) -> Self { Self { hex } }
}
impl fmt::Display for ContainsPrefixError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "hex string contains a prefix: {}", self.hex)
}
}
#[cfg(feature = "std")]
impl std::error::Error for ContainsPrefixError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_u32_from_hex_prefixed() {
let want = 171;
let got = hex_u32("0xab").expect("failed to parse prefixed hex");
assert_eq!(got, want);
}
#[test]
fn parse_u32_from_hex_no_prefix() {
let want = 171;
let got = hex_u32("ab").expect("failed to parse non-prefixed hex");
assert_eq!(got, want);
}
#[test]
fn parse_u128_from_hex_prefixed() {
let want = 3735928559;
let got = hex_u128("0xdeadbeef").expect("failed to parse prefixed hex");
assert_eq!(got, want);
}
#[test]
fn parse_u128_from_hex_no_prefix() {
let want = 3735928559;
let got = hex_u128("deadbeef").expect("failed to parse non-prefixed hex");
assert_eq!(got, want);
}
#[test]
fn parse_u32_from_hex_unchecked_errors_on_prefix() {
assert!(hex_u32_unchecked("0xab").is_err());
}
}