borrowme

github crates.io docs.rs build status

The missing compound borrowing for Rust.

Rust comes with two sibling traits which that can convert from owned to borrowed: ToOwned and Borrow.

These can convert most simple types such as &str to and from String. But lets think of this in a broader perspective. How to we convert a type that has lifetimes, to one which does not? This crate defines its own [ToOwned] and [Borrow] traits which serve a similar purpose to the ones in std but are implemented so that they can do this not only for simple references but also for compound types which receives lifetimes.

To help us implement these traits the #[borrowme] attribute macro is provided (see this section for why it's not a derive).

```rust

[borrowme]

[derive(Debug, Clone)]

struct Word<'a> { text: &'a str, lang: Option<&'a str>, examples: Vec, } ```

With this we get the following additional structs and trait implementations:

```rust

[derive(Debug, Clone)]

struct OwnedWord { text: String, lang: Option, examples: Vec, }

impl borrowme::ToOwned for Word<'_> { /* .. */ }

impl borrowme::Borrow for OwnedWord { /* .. */ } ```

By itself this isn't much, but here's the big trick. Types using this crate can be composed and converted into their borrowed or owned counterparts as needed:

```rust use std::collections::HashMap;

[borrowme]

struct Word<'a> { text: &'a str, lang: Option<&'a str>, examples: Vec<&'a str>, }

[borrowme]

struct Dictionary<'a> { words: HashMap<&'a str, Word<'a>>, }

let dictionary = Dictionary { /* .. */ };

let owneddictionary: OwnedDictionary = borrowme::toowned(&dictionary); let dictionary2: Dictionary<'> = borrowme::borrow(&owneddictionary); ```