A Rust trait for arbitrary type validation
Find a file
2025-10-11 20:13:29 -07:00
.github/workflows Write units tests 2025-10-11 20:13:29 -07:00
src Write units tests 2025-10-11 20:13:29 -07:00
.gitignore Initial commit 2025-10-11 20:13:29 -07:00
Cargo.lock Initial commit 2025-10-11 20:13:29 -07:00
Cargo.toml Enable use in no_std environments 2025-10-11 20:13:29 -07:00
license-apache.txt Initial commit 2025-10-11 20:13:29 -07:00
license-mit.txt Initial commit 2025-10-11 20:13:29 -07:00
readme.md Rename wrapper struct to "Valid" 2025-10-11 20:13:29 -07:00
rustfmt.toml Initial commit 2025-10-11 20:13:29 -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;

#[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.