Nutype 0.2.0 is out!
Serhii Potapov April 11, 2023 #rust #macro #newtype #nutypeI recently released nutype version 0.2.0, and I'd like to cover some of it's features in this post.
What is nutype?
Nutype is a Rust library powered by proc macros that allows to define newtypes which are guaranteed to satisfy some specified constraints. The constraints are typically set of sanitizers and validators.
Validating string types with regex
The biggest thing in the release is support of regex
.
For this you'd need the following:
- Enable
regex
feature of nutype - Make sure your crate explicitly declares dependency on
regex
andlazy_static
crates.
Now it's possible to enforce format of a string with a given regex, for example:
use nutype;
;
// valid SSN
let ssn = new.unwrap;
// Invalid SSN
assert_eq!;
If you need to use the regex in multiple places, you're already probably using lazy_static.
So nutype
can handle this too:
use lazy_static;
use Regex;
use nutype;
lazy_static!
;
If you prefer once_cell over lazy_static
, no problem:
use Lazy;
use Regex;
use nutype;
static SSN_REGEX: =
new;
;
Bypassing nutype guards
In very extreme cases, for the sake of performance, you may want to be able to initiate nutype values avoiding sanitization and validation. But it's your responsibility to guarantee that the data satisfy the constraints.
This feature was requested, but since it allows you to shoot your own foot, nutype makes it very verbose and discourages its usage, unless it's really needed.
So, here we are. For this you need to enable new_unchecked
feature of nutype
crate.
;
// Using `::new()` hits the validation guard, which returns TooBig error
assert_eq!;
// But using `::new_unchecked()` within `unsafe` it's possible to bypass
// the guard and obtain invalid instance of Percent.
let percent: Percent = unsafe ;
Please note:
- It's necessary to mark the type with
new_unchecked
Percent::new_unchecked
can be invoked only withinunsafe { }
block.
Other changes
To get full list of changes please refer to nutype v0.2.0 release notes.