Skip to main content

Crate vouched

Crate vouched 

Source
Expand description

Validated tuple-struct newtypes.

vouched derives checked construction for single-field tuple structs. A value is accepted only after the constraints in #[vouched(...)] pass, and the generated TryFrom implementations return a structured error when validation fails.

Most users only need this facade crate:

§Quick start

use vouched::Vouched;

#[derive(Debug, PartialEq, Eq, Vouched)]
#[vouched(len(1..=64), chars('a'..='z', '0'..='9', '_'), impls(try_from(&str)))]
struct Slug(String);
impl Slug {
   fn as_str(&self) -> &str {
       &self.0
   }
}

let slug = Slug::try_from("hello_123")?;
assert_eq!(slug.as_str(), "hello_123");

§Generated API

For a type named Slug, #[derive(Vouched)] generates:

  • impl TryFrom<Inner> for Slug, where Inner is the tuple field type.
  • additional TryFrom implementations requested by impls(try_from(...)).
  • a generated error enum named SlugVouchedError by default.
  • Display, core::error::Error, and VouchedError for that error enum.

impls(try_from(...)) supports fallible fixed-width integer conversions before validation. For string validation newtypes, impls(try_from(&str)) validates the borrowed input first and then constructs a supported owned string inner value. Supported inners are String, Box<str>, Rc<str>, and Arc<str>. Custom string wrapper inners and borrowed inners that store the input lifetime are not supported.

The generated error enum uses the derived type’s visibility by default. Its name and visibility can be configured with error(...):

#[derive(Debug, PartialEq, Eq, Vouched)]
#[vouched(error(name = SlugError, vis = pub(crate)), len(1..=64))]
pub(crate) struct Slug(String);

Rust visibility rules still apply. For example, rustc rejects a public derived type if its generated public TryFrom implementation exposes a less visible TryFrom::Error type.

§Markers

markerpurpose
len(range)validates string length by Unicode scalar value count
chars(...)validates allowed characters from literals and inclusive char ranges
range(range)validates numeric bounds for supported fixed-width integers, f32, and f64

len(...), chars(...), and range(...) can each be specified at most once. To combine character sets, put all sources in one marker: chars('a'..='z', '0'..='9', '_'). impls(try_from(...)) can also be specified once to add extra fallible integer or &str TryFrom implementations before validation.

len(...) and chars(...) use AsRef<str> and inspect untrimmed Unicode scalar values. Length is not measured in bytes.

range(...) type-checks bound expressions against the inner numeric type and generates runtime validation. Float ranges reject an actual NaN value as not comparable. Float bound expressions must not evaluate to NaN; Rust float comparison rules make a NaN bound ineffective. range(...) does not prove the range is non-empty.

§Validation Semantics

Validation returns the first error encountered. When multiple constraints fail, the exact evaluation order is an implementation detail. Implementations may evaluate expensive whole-string validations later to reduce validation cost.

§Features

featurescrate modeavailable
default / stdstdderive macro, core errors, generated errors, erased Error
alloc without defaultno_std + allocderive macro, core errors, generated errors, erased Error
no default featuresno_stdderive macro, core errors, generated errors; no erased Error
valuableno_std + allocall alloc items plus valuable::Valuable implementations for structured error observation

std enables alloc. valuable also enables alloc.

Structs§

Error
Wrapper type for handling different Vouched error types uniformly.
FloatValue
Lossless float value captured by generated float range errors.
IntegerValue
Lossless integer value captured by generated integer range and conversion errors.
InvalidCharError
Error returned when a string newtype contains a character rejected by chars.
OutOfRangeFloatError
Error returned when a float newtype is outside its range bounds.
OutOfRangeIntegerError
Error returned when an integer newtype is outside its range bounds.
TooLongError
Error returned when a string newtype is longer than its len upper bound.
TooShortError
Error returned when a string newtype is shorter than its len lower bound.

Enums§

FloatRangeViolation
Reason a float range validation failed.

Traits§

VouchedError
Common interface for generated Vouched errors.

Derive Macros§

Vouched
Derives validated construction for tuple-struct newtypes.