pub trait ZeroFrom<'zf, C: ?Sized>: 'zf {
// Required method
fn zero_from(other: &'zf C) -> Self;
}
Expand description
Trait for types that can be created from a reference to a different type C
with no allocations,
i.e. a zero-copy (zero-alloc) version of “From”
A type can be the ZeroFrom
target of multiple other types.
The intention is for ZeroFrom
to produce a struct from a other with as little work as
possible. Although it is technically possible to implement ZeroFrom
without being
zero-copy (using heap allocations), doing so defeats the purpose of ZeroFrom
.
For example, impl ZeroFrom<C> for Cow<str>
should return a Cow::Borrowed
pointing at
data in the other type C
, even if the other type is itself fully owned.
One can use the #[derive(ZeroFrom)]
custom derive to automatically
implement this trait.
§Examples
Implementing ZeroFrom
on a custom data struct:
use std::borrow::Cow;
use zerofrom::ZeroFrom;
struct MyStruct<'data> {
message: Cow<'data, str>,
}
// Reference from a borrowed version of self
impl<'zf> ZeroFrom<'zf, MyStruct<'_>> for MyStruct<'zf> {
fn zero_from(other: &'zf MyStruct<'_>) -> Self {
MyStruct {
message: Cow::Borrowed(&other.message),
}
}
}
// Reference from a string slice directly
impl<'zf> ZeroFrom<'zf, str> for MyStruct<'zf> {
fn zero_from(other: &'zf str) -> Self {
MyStruct {
message: Cow::Borrowed(other),
}
}
}
Required Methods§
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<'zf, B: ToOwned + ?Sized> ZeroFrom<'zf, Cow<'_, B>> for Cow<'zf, B>
Available on crate feature alloc
only.
impl<'zf, B: ToOwned + ?Sized> ZeroFrom<'zf, Cow<'_, B>> for Cow<'zf, B>
alloc
only.