Skip to main content

Validated

Derive Macro Validated 

Source
#[derive(Validated)]
{
    // Attributes available to this derive:
    #[valid]
}
Expand description

Turns a single-field newtype into a validated parse-dont-validate type.

Apply #[derive(Validated)] to a one-field tuple struct and annotate it with #[valid(<Validator>)], where <Validator> is any type implementing Validator for the field’s type — a built-in rule, a combinator, or your own.

The derive generates, on the struct:

  • fn new(value: T) -> Result<Self, <V as Validator<T>>::Error> — validates value and wraps it, or returns the validator’s error.
  • fn get(&self) -> &T and fn into_inner(self) -> T.
  • Deref<Target = T> and AsRef<T>.

The inner field stays private, so the only way to build the type from outside its module is through new — which is what makes the invariant trustworthy. Add ordinary derives (Debug, Clone, PartialEq, …) alongside as usual.

§Example

use type_lib::combinator::And;
use type_lib::rules::{LenRange, Trimmed};
use type_lib::Validated;

#[derive(Validated)]
#[valid(And<Trimmed, LenRange<3, 16>>)]
pub struct Username(String);

let user = Username::new("alice".to_owned()).unwrap();
assert_eq!(user.get(), "alice");
assert!(Username::new("  ".to_owned()).is_err());

(The example is ignored here because this crate cannot depend on type-lib; the compiled version runs from type-lib itself.)

§Compile errors

The derive reports a clear error when applied to anything other than a single-field tuple struct, when generics are present, or when the #[valid(...)] attribute is missing or duplicated.