A Rust trait for arbitrary type validation
Find a file
2022-07-04 22:37:24 -07:00
.github/workflows Add CI workflow 2022-07-04 22:37:24 -07:00
src Enable use in no_std environments 2022-07-04 22:25:13 -07:00
.gitignore Initial commit 2022-07-04 02:26:48 -07:00
Cargo.lock Initial commit 2022-07-04 02:26:48 -07:00
Cargo.toml Enable use in no_std environments 2022-07-04 22:25:13 -07:00
license-apache.txt Initial commit 2022-07-04 02:26:48 -07:00
license-mit.txt Initial commit 2022-07-04 02:26:48 -07:00
readme.md Initial commit 2022-07-04 02:26:48 -07:00
rustfmt.toml Initial commit 2022-07-04 02:26:48 -07:00

Vet

A library for validation of arbitrary types.

Usage

Add a dependency entry in Cargo.toml.

[dependencies]
vet = "0.1"
use vet::{Vet, Vetted};

#[derive(Debug)]
struct Username(String);

#[derive(Debug, PartialEq)]
enum UsernameVetError {
    TooShort,
    TooLong,
    InvalidChar,
}

impl Vet for Username {
    type VetError = UsernameVetError;
    fn is_valid(&self) -> Result<(), Self::VetError> {
        if self.0.len() < 3 {
            return Err(Self::VetError::TooShort);
        }
        if self.0.len() > 32 {
            return Err(Self::VetError::TooLong);
        }
        if self.0.chars().any(|c| !c.is_alphanumeric()) {
            return Err(Self::VetError::InvalidChar);
        }
        Ok(())
    }
}

fn main() {
    let username = Username(String::from("hi"));
    assert_eq!(username.is_valid(), Err(UsernameVetError::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: Vetted<Username>) {
    println!("Account {:?} created", username);
}

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.