pub struct GType<T, V = NoValidation> { /* private fields */ }Expand description
A validated value.
GType<T, V> wraps a value of type T and guarantees that it
satisfied validator V at construction time.
Validation is performed by GType::try_new. Once constructed,
the contained value cannot be modified directly, preserving the
validator’s invariants.
§Examples
use g_type::GType;
let value = GType::<u32>::try_new(42).unwrap();
assert_eq!(*value.as_ref(), 42);With a custom validator:
use core::convert::Infallible;
use g_type::{GType, Validator};
struct Percent;
impl Validator<u8> for Percent {
type Target = u8;
type Error = Infallible;
fn max() -> Option<&'static Self::Target> {
Some(&100)
}
}
assert!(GType::<u8, Percent>::try_new(50).is_ok());
assert!(GType::<u8, Percent>::try_new(150).is_err());Implementations§
Source§impl<T: PartialOrd<V::Target>, V: Validator<T>> GType<T, V>
impl<T: PartialOrd<V::Target>, V: Validator<T>> GType<T, V>
Sourcepub fn try_new(value: T) -> Result<Self, GTypeError<V::Error>>
pub fn try_new(value: T) -> Result<Self, GTypeError<V::Error>>
Attempts to create a validated value.
Returns an error if the value violates the validator’s minimum bound, maximum bound, or custom validation rules.
Sourcepub fn into_inner(self) -> T
pub fn into_inner(self) -> T
Consumes the wrapper and returns the underlying value.
Sourcepub fn inspect<F>(self, func: F) -> Self
pub fn inspect<F>(self, func: F) -> Self
Calls a function with a reference to the contained value.
Returns self unchanged.
This is primarily useful for debugging and logging in method chains.
Sourcepub fn map<U, UV, F>(
self,
func: F,
) -> Result<GType<U, UV>, GTypeError<UV::Error>>
pub fn map<U, UV, F>( self, func: F, ) -> Result<GType<U, UV>, GTypeError<UV::Error>>
Transforms the contained value into another validated type.
The transformed value is validated using the destination validator before being returned.
This behaves similarly to Option::map and Result::map.
Sourcepub fn and_then<U, UV, F>(
self,
func: F,
) -> Result<GType<U, UV>, GTypeError<UV::Error>>where
U: PartialOrd<UV::Target>,
UV: Validator<U>,
F: FnOnce(T) -> Result<GType<U, UV>, GTypeError<UV::Error>>,
pub fn and_then<U, UV, F>(
self,
func: F,
) -> Result<GType<U, UV>, GTypeError<UV::Error>>where
U: PartialOrd<UV::Target>,
UV: Validator<U>,
F: FnOnce(T) -> Result<GType<U, UV>, GTypeError<UV::Error>>,
Chains another fallible validated transformation.
This behaves similarly to Option::and_then and
Result::and_then.