Macro newstr::is_valid_newstring
source · [−]macro_rules! is_valid_newstring {
($new_name:ident, $closure:expr; $( $other:ident ),*) => { ... };
($new_name:ident, $closure:expr) => { ... };
}
Expand description
This macro takes a new type identifier and a predicate function to produce a new type. The
predicate is called by T::is_valid
and is then used in the implementation of FromStr
to
determine whether to return a new instance or error. As this is simply a boolean value and does
not differentiate between reasons for invalidity the error type for FromStr
is always ()
.
An optional variadic parameter also allows other trait names to be specified which will be
added to the list of traits in the derive
attribute.
Examples
Create a new string type with a user-defined closure.
is_valid_newstring!(NotEmpty, |s: &str| !s.is_empty());
assert!(!NotEmpty::is_valid(""));
assert!(NotEmpty::from_str("").is_err());
assert!(NotEmpty::is_valid("hi"));
assert!(NotEmpty::from_str("hi").is_ok());
assert_eq!(NotEmpty::from_str("hi").unwrap().len(), 2);
The following creates a new string type using an existing function.
is_valid_newstring!(AsciiStr, str::is_ascii);
In the following our new string type also derives serde attributes for serialization.
use serde::{Deserialize, Serialize};
is_valid_newstring!(NotEmpty, |s: &str| !s.is_empty(); Deserialize, Serialize);