Crate validit

Source
Expand description

Validate variable internal state when the variable is accessed.

  • Implement trait Validate for a type T to define how to validate internal state of T.
  • Wrapper struct Valid<T: Validate> implements Deref and DerefMut traits, and validates the internal state when the variable is accessed.

For example, If in your program you have a struct Lt5 { v: u64 } and you want to make sure that v is always less than to 5, you can implement Validate trait for Foo and use less! macro to validate a.

struct Lt5 { v: u64 }

impl Validate for Lt5 {
    fn validate(&self) -> Result<(), Box<dyn Error>> {
        validit::less!(self.v, 5);
        Ok(())
    }
}

let v1 = Lt5 { v: 1 }.valid();
let _x = v1.v; // Good

let v6 = Lt5 { v: 6 }.valid();
let res = catch_unwind(|| {
    let _x = v6.v; // panic: panicked at 'invalid state: expect: self.v(6) < 5(5) ...
});
assert!(res.is_err());

Modules§

macros
Defines macros for validation check, such as less!(smaller, greater).

Structs§

Valid
A wrapper of T that validate the state of T every time accessing it.

Traits§

Validate
Defines how to validate variable internal state.
ValidateExt

Macros§

be_true
Assert that function call call(a,b,...)(up to 8 arguments) to return true, otherwise it return an error.
less
Assert that a is less than b, otherwise it return an error.
greater
Assert that a is greater than b, otherwise it return an error.
less_equal
Assert that a is less than or equal to b, otherwise it return an error.
greater_equal
Assert that a is greater than or equal to b, otherwise it return an error.
equal
Assert that a equal to b, otherwise it return an error.