5 releases

0.2.4 Dec 31, 2023
0.2.3 Dec 3, 2023
0.1.1 Dec 2, 2023

#248 in Data structures

Download history 4269/week @ 2024-09-02 4238/week @ 2024-09-09 2770/week @ 2024-09-16 3425/week @ 2024-09-23 2459/week @ 2024-09-30 4071/week @ 2024-10-07 4772/week @ 2024-10-14 3325/week @ 2024-10-21 3645/week @ 2024-10-28 4458/week @ 2024-11-04 3596/week @ 2024-11-11 4297/week @ 2024-11-18 4744/week @ 2024-11-25 4146/week @ 2024-12-02 4299/week @ 2024-12-09 4571/week @ 2024-12-16

18,309 downloads per month
Used in 13 crates (via openraft)

MIT/Apache

37KB
943 lines

validit

Discord Chat Crates.io docs.rs Crates.io Crates.io

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 Foo(u64) and you want to make sure that a is always less than to 5, you can implement Validate trait for Foo and use less! macro to validate a.

struct Foo(u64);

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

fn main() {
  let v1 = Valid::new(Foo(1));
  let _x = v1.0; // Good.

  let v6 = Foo(6);
  let _x = v6.0; // No panic without validation.
  
  let v6 = Valid::new(Foo(6));
  let _x = v6.0; // panic: panicked at 'invalid state: expect: self.0(6) < 5(5) ...
}

Contribution

Dependencies

~0–5MB
~14K SLoC