Safe wrappers around string types made easy
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.
Example
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 StrNewType;
/// An `str` that is equal to `"foo"`.
;
The validation methods (validate_*) are provided by us, but StrNewType
will use them to derive the following:
- An error type
InvalidFooStr<T = String>(pub T); - A constructor
FooStr::new<T: ?Sized + AsRef<[u8]>>(input: &T) -> Result<&Self, InvalidFooStr<&T>> FooStr: Deref<Target = str>implementationFooStr: AsRef<str>implementationFooStr: Borrow<str>implementation
Since we added the owned(FooString) attribute, it will also generate:
- A sized/owned version of
FooStr:struct FooString(String); - A constructor
FooString::new<T: Buffer>(s: T) -> Result<Self, InvalidFooStr<T>> FooString: Deref<Target = FooStr>FooString: AsRef<FooStr>implementationFooString: Borrow<FooStr>implementation
And 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.
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contribution
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.