borrow-or-share 0.0.0

Traits for either borrowing data or sharing references
Documentation

borrow-or-share

Traits for either borrowing data or sharing references.

crates.io license

See the documentation for a walkthrough of the crate.

TL;DR - The following code compiles

use borrow_or_share::BorrowOrShare;

struct Text<T>(T);

impl<'i, 'o, T: BorrowOrShare<'i, 'o, str>> Text<T> {
    fn as_str(&'i self) -> &'o str {
        self.0.borrow_or_share()
    }
}

// The returned reference, which is borrowed from `*t`, lives as long as `t`.
fn owned_as_str(t: &Text<String>) -> &str {
    t.as_str()
}

// The returned reference, which is copied from `t.0`, lives longer than `t`.
fn borrowed_as_str(t: Text<&str>) -> &str {
    t.as_str()
}

Credit

Credit goes to @beepster4096 for figuring out a safe version of the code.