| Crates.io | newstr |
| lib.rs | newstr |
| version | 0.3.0 |
| created_at | 2021-04-16 01:19:55.795803+00 |
| updated_at | 2025-10-22 21:41:35.433984+00 |
| description | Simple macros for declaring String-base new types. |
| homepage | |
| repository | https://github.com/johnstonskj/rust-newstr.git |
| max_upload_size | |
| id | 385150 |
| size | 36,318 |
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.AsRef for T with the target type str.Deref for T with the target type str.FromStr.Additional user-required traits can also be added to the macro to be derived by the implementation.
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;
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")
);
The macro new_unchecked will add a constructor to the type that allows a
trusted client to bypass the validity checks.
new_unchecked!(pub(crate) Identifier);
assert_eq!(
Identifier::from_str("hi").unwrap(),
Identifier::new_unchecked("hi")
);
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.
lazy_static crate to use std::sync::LazyLock
to remove a client dependency.; instead of , to separate the additional derive macros,use_required macro any
more,FromStr.new_unchecked macro for validity bypass.derive attribute on the generated struct. *
Refactored the macros to reduce repetition. * Added some additional tests.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.