into-owned-trait 1.2.0

`IntoOwned` trait for converting borrowed types into their owned counterparts
Documentation
  • Coverage
  • 100%
    6 out of 6 items documented4 out of 5 items with examples
  • Size
  • Source code size: 26.57 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 875.48 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 3s Average build duration of successful builds.
  • all releases: 3s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • Homepage
  • Repository
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • timothee-haudebourg

IntoOwned trait for Rust

Build Crate informations License Documentation

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:

  • &T where T: ToOwned (delegates to [ToOwned::to_owned])
  • [Cow<'a, T>][std::borrow::Cow] where T: ToOwned (delegates to [Cow::into_owned])

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.