Skip to main content

FromStrFormat

Trait FromStrFormat 

Source
pub trait FromStrFormat<T> {
    type Err;

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

    // Provided methods
    fn regex_pattern(&self) -> String { ... }
    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_pattern(&self) -> String

Available on crate feature std only.

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

By default, ANY_REGEX is returned, which matches any string.

§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_pattern(&self) -> String {
        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_pattern(&self) -> String {
        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
Source

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

👎Deprecated:

use regex_pattern instead. In regex_pattern, use ANY_REGEX instead of None for patterns that matches any string.

Available on crate feature std only.

Implementors§