| Crates.io | str-newtype |
| lib.rs | str-newtype |
| version | 1.0.2 |
| created_at | 2025-12-05 16:19:48.5942+00 |
| updated_at | 2026-01-12 18:03:52.53762+00 |
| description | Derive macro to define safe wrappers around string types |
| homepage | |
| repository | https://github.com/timothee-haudebourg/str-newtype-rs |
| max_upload_size | |
| id | 1968626 |
| size | 96,127 |
This library provides a handy derive macro to create type-safe wrappers
around borrowed and owned string types (str and String), guaranteeing
through the type system that those string have been validated.
With this derive macro, all you need to do is define the base borrowed type, specify the name of the associated owned type and what trait you want them to implement.
In this example, we wish to define the types FooStr and FooString,
similar to str (borrowed) and String (owned), with the extra guarantee
that the string is always equal to "foo".
use str_newtype::StrNewType;
/// An `str` that is equal to `"foo"`.
#[derive(StrNewType)]
#[newtype(owned(FooString))]
pub struct FooStr(str);
impl FooStr {
pub const fn validate_bytes(s: &[u8]) -> bool {
s.len() == 3 && s[0] == b'f' && s[1] == b'f' && s[2] == b'f'
}
pub const fn validate_str(s: &str) -> bool {
Self::validate_bytes(s.as_bytes())
}
}
The validation methods (validate_*) are provided by us, but StrNewType
will use them to derive the following:
InvalidFooStr<T = String>(pub T);FooStr::new<T: ?Sized + AsRef<[u8]>>(input: &T) -> Result<&Self, InvalidFooStr<&T>>FooStr: Deref<Target = str> implementationFooStr: AsRef<str> implementationFooStr: Borrow<str> implementationSince we added the owned(FooString) attribute, it will also generate:
FooStr: struct FooString(String);FooString::new<T: Buffer>(s: T) -> Result<Self, InvalidFooStr<T>>FooString: Deref<Target = FooStr>FooString: AsRef<FooStr> implementationFooString: Borrow<FooStr> implementationAnd much more. See the the [StrNewType] documentation for a full
specification of what items are derived and how it can be controlled with
the newtype attribute.
Licensed under either of
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.