g-type
A lightweight, no_std-friendly validated value type.
GType<T, V> wraps a value of type T and guarantees that it satisfies the constraints defined by a validator V.
Validators can provide:
- Minimum and maximum bounds
- Arbitrary validation logic
- Custom error types
Features
no_stdcompatible- Zero-cost abstraction after construction
- Optional validation
- Compile-time validator definitions
- Custom validation errors
- Works with primitive and user-defined types
- Preserves common traits such as
Clone,Copy,Eq,Ord,Hash,Display, andDebug
Basic Usage
use ;
;
type Percentage = ;
let value = try_new.unwrap;
assert_eq!;
Custom Validation
Validators may perform arbitrary runtime checks.
use ;
;
;
type EvenNumber = ;
assert!;
assert!;
No Validation
Use the default validator when no validation is required.
use GType;
let value = try_new.unwrap;
assert_eq!;
Transforming Values
map() transforms the inner value and validates the result using the destination validator.
let value = try_new.unwrap;
;
let percent = value..unwrap;
assert_eq!;
and_then() allows chaining validated transformations.
let value = try_new.unwrap;
;
let percent = value..unwrap;
Error Handling
Construction may fail for three reasons:
MinExceedsMax— minimum value exceeds maximum value.BelowMinimum— value is below the validator minimum.AboveMaximum— value exceeds the validator maximum.Validation(E)— custom validator rejected the value.
Design
A validator is a type implementing:
Validators are stateless marker types. All constraints are defined through associated functions, making them easy to use in const contexts and zero-sized at runtime.