use core::num::*;
use core::str::FromStr;
use crate::parse_error::ParseError;
pub trait Parse<'a> {
fn from_str(s: &'a str) -> Result<Self, ParseError>
where
Self: Sized;
}
impl<'a> Parse<'a> for &'a str {
fn from_str(s: &'a str) -> Result<Self, ParseError> {
Ok(s)
}
}
macro_rules! impl_parse {
( $( $Ty: ty )+) => {
$(
impl<'a> Parse<'a> for $Ty {
fn from_str(s: &'a str) -> Result<Self, ParseError> {
<Self as FromStr>::from_str(s.trim()).map_err(|e| e.into())
}
}
)+
};
}
#[cfg(feature = "alloc")]
macro_rules! impl_parse_infallible {
( $( $Ty: ty )+) => {
$(
impl<'a> Parse<'a> for $Ty {
fn from_str(s: &'a str) -> Result<Self, ParseError> {
Ok(<Self as FromStr>::from_str(&s).unwrap())
}
}
)+
};
}
impl_parse!(isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128);
impl_parse!(bool char f32 f64);
impl_parse!(NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize);
impl_parse!(NonZeroI8 NonZeroI16 NonZeroI32 NonZeroI64 NonZeroI128 NonZeroIsize);
#[cfg(feature = "alloc")]
mod impl_alloc {
extern crate alloc;
use alloc::string::String;
use super::{FromStr, Parse, ParseError};
impl_parse_infallible!(String);
}
#[cfg(feature = "std")]
mod impl_std {
use std::ffi::OsString;
use std::net::*;
use std::path::PathBuf;
use super::{FromStr, Parse, ParseError};
impl_parse_infallible!(OsString PathBuf);
impl_parse!(IpAddr SocketAddr Ipv4Addr Ipv6Addr SocketAddrV4 SocketAddrV6);
}
pub trait ExtParseStr: __private::Sealed {
fn lending_parse<'a, F: Parse<'a>>(&'a self) -> Result<F, ParseError>;
}
impl ExtParseStr for str {
fn lending_parse<'a, F: Parse<'a>>(&'a self) -> Result<F, ParseError> {
Parse::from_str(self)
}
}
#[doc(hidden)]
mod __private {
pub trait Sealed {}
impl Sealed for str {}
}