Nutype is a proc macro that allows adding extra constraints like sanitization and validation to the regular newtype pattern. The generated code makes it impossible to instantiate a value without passing the checks. It works this way even with serde
deserialization.
- Quick start
- Inner types (String | Integer | Float | Other)
- Custom (sanitizers | validators | errors)
- Recipes
- Breaking constraints with new_unchecked
- Feature Flags
- Support Ukrainian military forces
- Similar projects
Quick start
use nutype;
// Define newtype Username
;
// We can obtain a value of Username with `::try_new()`.
// Note that Username holds a sanitized string
assert_eq!;
// It's impossible to obtain an invalid Username
// Note that we also got `UsernameError` enum generated implicitly
// based on the validation rules.
assert_eq!;
assert_eq!;
For more please see:
Inner types
Available sanitizers, validators, and derivable traits are determined by the inner type, which falls into the following categories:
- String
- Integer (
u8
,u16
,u32
,u64
,u128
,i8
,i16
,i32
,i64
,i128
,usize
,isize
) - Float (
f32
,f64
) - Anything else
String
At the moment the string inner type supports only String
(owned) type.
String sanitizers
Sanitizer | Description | Example |
---|---|---|
trim |
Removes leading and trailing whitespaces | trim |
lowercase |
Converts the string to lowercase | lowercase |
uppercase |
Converts the string to uppercase | uppercase |
with |
Custom sanitizer. A function or closure that receives String and returns String |
with = |mut s: String| ( s.truncate(5); s ) |
String validators
Validator | Description | Error variant | Example |
---|---|---|---|
len_char_min |
Min length of the string (in chars, not bytes) | LenCharMinViolated |
len_char_min = 5 |
len_char_max |
Max length of the string (in chars, not bytes) | LenCharMaxViolated |
len_char_max = 255 |
not_empty |
Rejects an empty string | NotEmptyViolated |
not_empty |
regex |
Validates format with a regex. Requires regex feature. |
RegexViolated |
regex = "^[0-9]{7}$" or regex = ID_REGEX |
predicate |
Custom validator. A function or closure that receives &str and returns bool |
PredicateViolated |
predicate = |s: &str| s.contains('@') |
with |
Custom validator with a custom error | N/A | (see example below) |
Regex validation
Requirements:
regex
feature ofnutype
is enabled.- You have to explicitly include
regex
as a dependency.
There are a number of ways you can use regex.
A regular expression can be defined right in place:
;
or it can be defined with std::sync::LazyLock
:
use Regex;
static PHONE_NUMBER_REGEX: = new;
;
or it can be defined with lazy_static
:
use lazy_static;
use Regex;
lazy_static!
;
or once_cell
:
use Lazy;
use Regex;
static PHONE_NUMBER_REGEX: =
new;
;
String derivable traits
The following traits can be derived for a string-based type:
Debug
, Clone
, PartialEq
, Eq
, PartialOrd
, Ord
, FromStr
, AsRef
, Deref
,
From
, TryFrom
, Into
, Hash
, Borrow
, Display
, Default
, Serialize
, Deserialize
.
Integer
The integer inner types are: u8
, u16
,u32
, u64
, u128
, i8
, i16
, i32
, i64
, i128
, usize
, isize
.
Integer sanitizers
Sanitizer | Description | Example |
---|---|---|
with |
Custom sanitizer. | with = |raw| raw.clamp(0, 100) |
Integer validators
Validator | Description | Error variant | Example |
---|---|---|---|
less |
Exclusive upper bound | LessViolated |
less = 100 |
less_or_equal |
Inclusive upper bound | LessOrEqualViolated |
less_or_equal = 99 |
greater |
Exclusive lower bound | GreaterViolated |
greater = 17 |
greater_or_equal |
Inclusive lower bound | GreaterOrEqualViolated |
greater_or_equal = 18 |
predicate |
Custom predicate | PredicateViolated |
predicate = |num| num % 2 == 0 |
with |
Custom validator with a custom error | N/A | (see example below) |
Integer derivable traits
The following traits can be derived for an integer-based type:
Debug
, Clone
, Copy
, PartialEq
, Eq
, PartialOrd
, Ord
, FromStr
, AsRef
, Deref
,
Into
, From
, TryFrom
, Hash
, Borrow
, Display
, Default
, Serialize
, Deserialize
.
Float
The float inner types are: f32
, f64
.
Float sanitizers
Sanitizer | Description | Example |
---|---|---|
with |
Custom sanitizer. | with = |val| val.clamp(0.0, 100.0) |
Float validators
Validator | Description | Error variant | Example |
---|---|---|---|
less |
Exclusive upper bound | LessViolated |
less = 100.0 |
less_or_equal |
Inclusive upper bound | LessOrEqualViolated |
less_or_equal = 100.0 |
greater |
Exclusive lower bound | GreaterViolated |
greater = 0.0 |
greater_or_equal |
Inclusive lower bound | GreaterOrEqualViolated |
greater_or_equal = 0.0 |
finite |
Check against NaN and infinity | FiniteViolated |
finite |
predicate |
Custom predicate | PredicateViolated |
predicate = |val| val != 50.0 |
with |
Custom validator with a custom error | N/A | (see example below) |
Float derivable traits
The following traits can be derived for a float-based type:
Debug
, Clone
, Copy
, PartialEq
, Eq
, PartialOrd
, Ord
, FromStr
, AsRef
, Deref
,
Into
, From
, TryFrom
, Hash
, Borrow
, Display
, Default
, Serialize
, Deserialize
.
It's also possible to derive Eq
and Ord
if the validation rules guarantee that NaN
is excluded.
This can be done applying by finite
validation. For example:
;
Other inner types and generics
For any other type it is possible to define custom sanitizers with with
and custom
validations with predicate
:
use nutype;
;
It's also possible to use generics:
;
let wise_friends = try_new.unwrap;
assert_eq!;
assert_eq!;
let numbers = try_new.unwrap;
assert_eq!;
assert_eq!;
Custom sanitizers
You can set custom sanitizers using the with
option.
A custom sanitizer is a function or closure that receives a value of an inner type with ownership and returns a sanitized value.
For example, this one
;
is equal to the following one:
;
And works the same way:
let city = new;
assert_eq!;
Custom validators
In similar fashion it's possible to define custom validators, but a validation function receives a reference and returns bool
.
Think of it as a predicate.
;
Custom validation with a custom error type
To define your own error type and implement custom validation logic, you can combine the with
and error
attributes:
// Define a custom error type for validation failures.
// Although it's best practice to implement `std::error::Error` for custom error types,
// we are omitting that for simplicity here.
// Define a custom validation function for `Name`.
// The function returns `Result<(), NameError>`, where `Ok(())` indicates a valid name,
// and `Err(NameError)` represents a specific validation failure.
// Define a newtype `Name` with custom validation logic and custom error.
;
It's important to ensure that the type specified in the error
attribute matches the error type returned by the validation function.
Recipes
Derive Default
;
Derive Eq
and Ord
on float types
With nutype it's possible to derive Eq
and Ord
if there is finite
validation set.
The finite
validation ensures that the valid value excludes NaN
.
;
Breaking constraints with new_unchecked
It's discouraged, but it's possible to bypass the constraints by enabling new_unchecked
crate feature and marking a type with new_unchecked
:
;
// Yes, you're forced to use `unsafe` here, so everyone will point fingers at YOU.
let name = unsafe ;
// `name` violates the sanitization and validation rules!!!
assert_eq!;
Feature flags
arbitrary
- enables derive ofarbitrary::Arbitrary
.new_unchecked
- enables generation of unsafe::new_unchecked()
function.regex
- allows to useregex =
validation on string-based types. Note: your crate also has to explicitly haveregex
within its dependencies.serde
- integrations withserde
crate. Allows to deriveSerialize
andDeserialize
traits.schemars08
- allows to deriveJsonSchema
trait of schemars crate. Note that at the moment validation rules are not respected.std
- enabled by default. Usedefault-features = false
to disable.
When nutype is a good fit for you?
- If you enjoy newtype pattern and you like the idea of leveraging the Rust type system to enforce the correctness of the business logic.
- If you want to use type system to hold invariants
- If you're a DDD fan, nutype is a great helper to make your domain models even more expressive.
- You want to prototype quickly without sacrificing quality.
When nutype is not that good?
- You care too much about compiler time (nutype relies on heavy usage of proc macros).
- You think metaprogramming is too much implicit magic.
- IDEs may not be very helpful at giving you hints about proc macros.
- Design of nutype may enforce you to run unnecessary validation (e.g. on loading data from DB), which may have a negative impact if you aim for extreme performance.
Support Ukrainian military forces
Today I live in Berlin, I have the luxury to live a physically safe life. But I am Ukrainian. The first 25 years of my life I spent in Kharkiv, the second-largest city in Ukraine, 60km away from the border with russia. Today about a third of my home city is destroyed by russians. My parents, my relatives and my friends had to survive the artillery and air attack, living for over a month in basements.
Some of them have managed to evacuate to EU. Some others are trying to live "normal lives" in Kharkiv, doing there daily duties. And some are at the front line right now, risking their lives every second to protect the rest.
I encourage you to donate to Charity foundation of Serhiy Prytula. Just pick the project you like and donate. This is one of the best-known foundations, you can watch a little documentary about it. Your contribution to the Ukrainian military force is a contribution to my calmness, so I can spend more time developing the project.
Thank you.
Similar projects
- prae - A very similar crate that aims to solve the same problems but with slightly different approach.
- bounded-integer - Bounded integers for Rust.
- refinement - Convenient creation of type-safe refinement types (based on generics).
- semval - Semantic validation for Rust.
- validator - Simple validation for Rust structs (powered by macros).
License
MIT © Serhii Potapov