Expand description
This crate provides the IntoOwned trait, which converts a
borrowed form of a type into its owned form.
§Motivation
A common pattern in performance-sensitive code is to maintain two parallel representations of a type: a borrowed form that holds references into existing data (cheap to create and copy), and an owned form that carries its own heap-allocated data (can outlive the source).
// Cheap to push onto a stack during processing — no allocation.
#[derive(Clone, Copy)]
enum EventRef<'a> {
Started(&'a str),
Finished(&'a str, u64),
}
// Stored in the final result — heap-allocated, lifetime-free.
enum Event {
Started(String),
Finished(String, u64),
}
impl<'a> IntoOwned for EventRef<'a> {
type Owned = Event;
fn into_owned(self) -> Event {
match self {
EventRef::Started(name) => Event::Started(name.to_owned()),
EventRef::Finished(name, ts) => Event::Finished(name.to_owned(), ts),
}
}
}
let frame = EventRef::Finished("build", 42);
let owned = frame.into_owned();IntoOwned gives generic code a single, uniform interface for this
conversion, regardless of how complex the borrowed type’s internal
structure is.
§Built-in implementations
Two implementations are provided out of the box as convenience building blocks when implementing the trait for your own types:
&TwhereT:ToOwned(delegates toToOwned::to_owned)Cow<'a, T>whereT:ToOwned(delegates toCow::into_owned)
Structs§
- MapInto
Owned - An iterator adapter that converts each item from its borrowed form to its
owned form using
IntoOwned::into_owned. - MapOk
Into Owned - An iterator adapter that converts the
Okvariant of eachResultitem usingIntoOwned::into_owned, passingErritems through unchanged.
Traits§
- Into
Owned - Conversion of a borrowed type into its fully owned counterpart.