Crate newstr[−][src]
This crate provides simple macros that generate String based new types. The two primary macros
implement the validity rules for the new type by either 1) providing a predicate that is used by
the is_valid
associated function, or 2) providing a function to parse and return a string which
is then called by FromStr::from_str
.
Both of these methods produce a new type, with the following:
- An associated predicate function
is_valid
that returnstrue
if the string provided would be a valid value for the type. - This type derives implementations of
Clone
,Debug
,PartialEq
,PartialOrd
,Eq
,Ord
, andHash
. - An implementation of
Display
forT
that simply returns the inner value. - An implementation of
From<T>
forString
. - An implementation of
Deref
forT
with the target typestr
. - An implementation of
FromStr
.
Example
The following example constructs a new string type that implements an Identifier
value. This
value must be ASCII, alphanumeric, the ‘_’ character and must not be empty.
use std::fmt::{Display, Formatter}; use std::str::FromStr; use std::ops::Deref; fn is_identifier_value(s: &str) -> bool { !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') } is_valid_newstring!(Identifier, is_identifier_value); assert!(!Identifier::is_valid("")); assert!(!Identifier::is_valid("hi!")); assert!(!Identifier::is_valid("hello world")); assert!(!Identifier::is_valid("9.99")); assert_eq!( Identifier::from_str("hi").unwrap().to_string(), String::from("hi") ); assert_eq!( Identifier::from_str("hello_world").unwrap().to_string(), String::from("hello_world") );
Macros
from_str_newstring | This macro takes a new type identifier and a predicate function to produce a new type. The
predicate is called by |
is_valid_newstring | This macro takes a new type identifier and a predicate function to produce a new type. The
predicate is called by |
regex_is_valid | This macro takes a string that contains a regular expression will construct a new validity
predicate that may be used by the |