Trait parse_display::FromStrFormat

source ·
pub trait FromStrFormat<T> {
    type Err;

    // Required method
    fn parse(&self, s: &str) -> Result<T, Self::Err>;

    // Provided method
    fn regex(&self) -> Option<String> { ... }
}
Expand description

Required Associated Types§

Required Methods§

source

fn parse(&self, s: &str) -> Result<T, Self::Err>

Parsing function used in place of FromStr::from_str.

Provided Methods§

source

fn regex(&self) -> Option<String>

Available on crate feature std only.

Return a regular expression that the input string needs to match.

If None is returned, the input will be a string that matches .*?.

§Examples
use parse_display::{FromStr, FromStrFormat};

struct Number;
impl FromStrFormat<String> for Number {
    type Err = <String as std::str::FromStr>::Err;
    fn parse(&self, s: &str) -> std::result::Result<String, Self::Err> {
        s.parse()
    }
    fn regex(&self) -> Option<String> {
        Some(r"[0-9]+".into())
    }
}

#[derive(FromStr, PartialEq, Debug)]
#[display("{0}{1}")]
struct X(String, String);

#[derive(FromStr, PartialEq, Debug)]
#[display("{0}{1}")]
struct Y(#[from_str(with = Number)] String, String);

assert_eq!("123abc".parse(), Ok(X("".into(), "123abc".into())));
assert_eq!("123abc".parse(), Ok(Y("123".into(), "abc".into())));

If the field type includes type parameters, the regex must be the same regardless of the type parameters.

If the regex differs, it will panic in debug mode and result in an incorrect parse in release mode.

use parse_display::{FromStr, FromStrFormat ,ParseError};
use std::any::{type_name, Any};
use std::str::FromStr;

struct TypeNameFormat;
impl<T: Default + Any> FromStrFormat<T> for TypeNameFormat {
    type Err = ParseError;
    fn parse(&self, _s: &str) -> core::result::Result<T, Self::Err> {
        Ok(Default::default())
    }
    fn regex(&self) -> Option<String> {
        Some(type_name::<T>().to_string())
    }
}

#[derive(FromStr)]
struct X<T: Default + std::any::Any>(#[from_str(with = TypeNameFormat)] T);
let _ = X::<u32>::from_str("u32");
let _ = X::<u16>::from_str("u16"); // panic on debug mode

Implementors§