Simple macros for declaring String-base new types.
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:
is_valid
that returns true
if the string provided would be a
valid value for the type.Clone
, Debug
, PartialEq
, PartialOrd
, Eq
, Ord
,
and Hash
.Display
for T
that simply returns the inner value.From<T>
for String
.Deref
for T
with the target type str
.FromStr
.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.
```rust use std::fmt::{Display, Formatter}; use std::str::FromStr; use std::ops::Deref;
fn isidentifiervalue(s: &str) -> bool { !s.isempty() && s.chars().all(|c| c.isasciialphanumeric() || c == '') }
isvalidnewstring!(Identifier, isidentifiervalue);
assert!(!Identifier::isvalid("")); assert!(!Identifier::isvalid("hi!")); assert!(!Identifier::isvalid("hello world")); assert!(!Identifier::isvalid("9.99"));
asserteq!( Identifier::fromstr("hi").unwrap().tostring(), String::from("hi") ); asserteq!( Identifier::fromstr("helloworld").unwrap().tostring(), String::from("helloworld") ); ```
In the example above you can see the necessary use-statements for the trait implementations the
macros generate. Unless you use regex_is_valid
there are no crate dependencies; if you do you will
need to add lazy_static
and regex
dependencies.
If the macros in this crate take on addition dependencies or provide new implementations the set of
use statements may change which will break consumer builds. To avoid this another macro,
use_required
, will add any required use statements the consumer requires.
```rust
use_required!();
isvalidnewstring!(NotEmpty, |s: &str| !s.is_empty()); ```
Version 0.1.1
use_required
macro.lazy_static
and regex
dev dependencies, if you don't use them, you don't need them.cargo-husky
for Git cleanliness.Version 0.1.0