Skip to main content

IntoValidated

Trait IntoValidated 

Source
pub trait IntoValidated<V: Validated>: Sized {
    // Required method
    fn into_validated(self) -> MaybeValidOwned<V, Self>;
}
Expand description

Consumes Self into a validated value of type V, if self satisfies V’s predicate.

IntoValidated<V> expresses that Self can be converted into V whenever self’s contents satisfy the validation predicate declared by V: Validated. On failure, self is returned unchanged alongside the diagnostic, so the caller does not lose their input.

This is the owning counterpart to AsValidated. Use it when the validated form is an owned value (for example, converting Vec<u8> into String) rather than a borrowed view.

§Contract

Implementers of IntoValidated<V> promise:

  1. Precursor recovery on failure. When validation fails, the returned MaybeValidOwned::Invalid variant contains self unchanged. The caller can always recover their input.

  2. No precursor cloning. Recovery on the invalid path returns the original self by move, not a clone. The trait does not require Self: Clone.

  3. Cost bounded by validation and construction. The method performs at most the work inherent to deciding whether self satisfies V’s predicate and constructing the resulting V. Unlike AsValidated, construction may involve allocation or transformation when producing the owned V requires it.

  4. Diagnostic-only reason. The InvalidReason component of the invalid branch does not carry a copy of self; the precursor is returned structurally via the tuple.

  5. Deterministic classification. Whether a given self produces Valid or Invalid depends only on self’s observable state.

These are logical contracts, not compiler-enforced ones.

§Examples

Consuming Vec<u8> into String, recovering the bytes on failure without a clone:

let bytes = vec![0xff, 0xfe, 0xfd];
let validated: MaybeValidOwned<String, Vec<u8>> = bytes.into_validated();
match validated {
    MaybeValidOwned::Valid(s) => {
        println!("got string: {}", s);
    }
    MaybeValidOwned::Invalid(bytes, reason) => {
        // `bytes` is the original Vec<u8>, moved back to us.
        // No clone occurred on the failure path.
        eprintln!(
            "invalid UTF-8 at byte {}; recovered {} bytes",
            reason.valid_up_to(),
            bytes.len(),
        );
    }
}

Converting u32 into NonZeroU32:

let candidates = [1u32, 0, 42];
for n in candidates {
    let validated: MaybeValidOwned<NonZeroU32, u32> = n.into_validated();
    match validated {
        MaybeValidOwned::Valid(nz) => println!("{} is nonzero", nz),
        MaybeValidOwned::Invalid(original, _) => {
            assert_eq!(original, 0);
            println!("zero, skipping");
        }
    }
}

§Relationship to AsValidated

IntoValidated and AsValidated are peers: the second borrows, the first consumes. Both route through the same Validated target type and share its InvalidReason. Paired borrowed/owned validated types should share an InvalidReason so that outcomes can round-trip between the two via MaybeValidRef::into_owned (when the alloc feature is enabled).

§Relationship to TryFrom

IntoValidated<V> overlaps in shape with TryFrom<Self> for V, but differs in three ways:

  • Canonical reason type. IntoValidated<V> routes all failures through V::InvalidReason, which is fixed by the target type. TryFrom lets each impl choose its own error.

  • Structural precursor recovery. IntoValidated guarantees via its signature that self is returned on failure. TryFrom::Error may or may not carry the precursor, depending on the impl; callers cannot rely on recovery in generic code.

  • Scope. IntoValidated is intended for structural refinements, where V is a subset of Self’s representation with a validation predicate. Use TryFrom for conversions that change representation (parsing, decoding, reinterpretation).

These differences make IntoValidated a better fit for generic code that needs to rely on precursor recovery or uniform error handling, and TryFrom a better fit for general fallible conversion.

§Relationship to FromStr

FromStr parses a string into a value, which is typically a representation-changing operation. IntoValidated is for structural refinements and does not apply to parsing. Types like IpAddr or Duration, which are constructed from strings but have internal binary representations unrelated to the string’s bytes, use FromStr, not IntoValidated.

Required Methods§

Source

fn into_validated(self) -> MaybeValidOwned<V, Self>

Consumes self into a validated V, if valid.

Returns MaybeValidOwned::Valid(v) when self satisfies V’s predicate. Returns MaybeValidOwned::Invalid(self, reason) otherwise, with self returned unchanged.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl IntoValidated<char> for u32

Source§

impl IntoValidated<CString> for Vec<u8>

Source§

impl IntoValidated<String> for Vec<u8>

Source§

impl IntoValidated<NonZero<i8>> for i8

Source§

impl IntoValidated<NonZero<i16>> for i16

Source§

impl IntoValidated<NonZero<i32>> for i32

Source§

impl IntoValidated<NonZero<i64>> for i64

Source§

impl IntoValidated<NonZero<i128>> for i128

Source§

impl IntoValidated<NonZero<isize>> for isize

Source§

impl IntoValidated<NonZero<u8>> for u8

Source§

impl IntoValidated<NonZero<u16>> for u16

Source§

impl IntoValidated<NonZero<u32>> for u32

Source§

impl IntoValidated<NonZero<u64>> for u64

Source§

impl IntoValidated<NonZero<u128>> for u128

Source§

impl IntoValidated<NonZero<usize>> for usize

Implementors§