Expand description
Provides an interface for validation of arbitrary types.
The Vet
trait requires an Error
type alias and an implementation of an
is_valid
method, which executes arbitrary validation logic and returns a
result indicating whether the instance is valid.
The Vet
trait also provides a default implementation of a vet
method
which, dependant on the result of is_valid
, either wraps the instance with
a Valid<T>
struct or propagates the validation error.
The Valid<T>
wrapper guarantees that the inner value was successfully
validated and remains immutable as long as it is wrapped.
Implementations for generic arrays, and for the common standard library
types Vec<T>
and Option<T>
are provided.
Examples
use vet::{Valid, Vet};
#[derive(Debug)]
struct Username(String);
#[derive(Debug, PartialEq)]
enum InvalidUsername {
TooShort,
TooLong,
InvalidChar,
}
impl Vet for Username {
type Error = InvalidUsername;
fn is_valid(&self) -> Result<(), Self::Error> {
if self.0.len() < 3 {
return Err(Self::Error::TooShort);
}
if self.0.len() > 32 {
return Err(Self::Error::TooLong);
}
if self.0.chars().any(|c| !c.is_alphanumeric()) {
return Err(Self::Error::InvalidChar);
}
Ok(())
}
}
fn main() {
let username = Username(String::from("hi"));
assert_eq!(username.is_valid(), Err(InvalidUsername::TooShort));
let username = Username(String::from("benjamin"));
match username.vet() {
Ok(username) => create_account(username),
Err(error) => println!("Could not create account: {:?}", error),
}
}
fn create_account(username: Valid<Username>) {
println!("Account {:?} created", username);
}
Structs
A wrapper around a validated instance
Traits
An interface for arbitrary type validation