5 releases

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

#210 in Data structures

Download history 2955/week @ 2024-01-13 1449/week @ 2024-01-20 3118/week @ 2024-01-27 2969/week @ 2024-02-03 4406/week @ 2024-02-10 7005/week @ 2024-02-17 5493/week @ 2024-02-24 5463/week @ 2024-03-02 6383/week @ 2024-03-09 7378/week @ 2024-03-16 5641/week @ 2024-03-23 4013/week @ 2024-03-30 5801/week @ 2024-04-06 3969/week @ 2024-04-13 4692/week @ 2024-04-20 4059/week @ 2024-04-27

18,826 downloads per month
Used in 5 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–680KB
~14K SLoC