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:
-
Precursor recovery on failure. When validation fails, the returned
MaybeValidOwned::Invalidvariant containsselfunchanged. The caller can always recover their input. -
No precursor cloning. Recovery on the invalid path returns the original
selfby move, not a clone. The trait does not requireSelf: Clone. -
Cost bounded by validation and construction. The method performs at most the work inherent to deciding whether
selfsatisfiesV’s predicate and constructing the resultingV. UnlikeAsValidated, construction may involve allocation or transformation when producing the ownedVrequires it. -
Diagnostic-only reason. The
InvalidReasoncomponent of the invalid branch does not carry a copy ofself; the precursor is returned structurally via the tuple. -
Deterministic classification. Whether a given
selfproducesValidorInvaliddepends only onself’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 throughV::InvalidReason, which is fixed by the target type.TryFromlets each impl choose its own error. -
Structural precursor recovery.
IntoValidatedguarantees via its signature thatselfis returned on failure.TryFrom::Errormay or may not carry the precursor, depending on the impl; callers cannot rely on recovery in generic code. -
Scope.
IntoValidatedis intended for structural refinements, whereVis a subset ofSelf’s representation with a validation predicate. UseTryFromfor 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§
Sourcefn into_validated(self) -> MaybeValidOwned<V, Self>
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.