Hey there!
I want to share my recent work - release of nutype 0.5.0.
What is Nutype?
Nutype is a procedural macro designed to add sanitization and validation to newtypes, ensuring values always meet specified checks, even when using serde for deserialization.
What’s New in Nutype 0.5.0?
With Nutype version 0.5.0, users now have the capability to define their own error types and validation logic. This update brings enhanced flexibility while still maintaining robust sanitization and validation guarantees.
Example Code
Here's a quick example demonstrating how to define a newtype Name
with custom validation logic and a specific error type:
use nutype::nutype;
// Creating a `Name` newtype with custom validation logic and error type `NameError`.
// If validation fails, creating an instance of `Name` won't be possible.
#[nutype(
validate(with = validate_name, error = NameError),
derive(Debug, AsRef, PartialEq),
)]
struct Name(String);
// Custom error type for `Name` validation, leveraging crates like `thiserror` for detailed error messages.
#[derive(Debug, PartialEq)]
enum NameError {
TooShort { min: usize, length: usize },
TooLong { max: usize, length: usize },
}
// Function to validate `Name` based on its length.
fn validate_name(name: &str) -> Result<(), NameError> {
const MIN: usize = 3;
const MAX: usize = 10;
let length = name.encode_utf16().count();
if length < MIN {
Err(NameError::TooShort { min: MIN, length })
} else if length > MAX {
Err(NameError::TooLong { max: MAX, length })
} else {
Ok(())
}
}
fn main() {
// Attempt to create a `Name` with an invalid input, demonstrating validation in action.
assert_eq!(Name::try_new("Fo"), Err(NameError::TooShort { min: 3, length: 2 }));
}
Special Thanks
Huge thanks to my in-laws, the unsung heroes of this release! They took care of my wife and kid for a weekend, giving me uninterrupted time to work on Nutype!