vet 0.1.0

Arbitrary type validation
Documentation
  • Coverage
  • 87.5%
    7 out of 8 items documented1 out of 7 items with examples
  • Size
  • Source code size: 23.64 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 1.7 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Links
  • metanomial/vet
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • metanomial

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);
}