#reference-data #borrow #borrowing #sharing #share #traits #shared

no-std borrow-or-share

Traits for either borrowing or sharing data

6 releases

0.2.2 Mar 24, 2024
0.2.1 Mar 24, 2024
0.1.0 Mar 6, 2024
0.0.1 Mar 5, 2024

#566 in Rust patterns

Download history 449/week @ 2024-09-03 480/week @ 2024-09-10 397/week @ 2024-09-17 2048/week @ 2024-09-24 5887/week @ 2024-10-01 8192/week @ 2024-10-08 9787/week @ 2024-10-15 10823/week @ 2024-10-22 10597/week @ 2024-10-29 13006/week @ 2024-11-05 14508/week @ 2024-11-12 15154/week @ 2024-11-19 14987/week @ 2024-11-26 18573/week @ 2024-12-03 20282/week @ 2024-12-10 18156/week @ 2024-12-17

75,158 downloads per month
Used in 47 crates (via fluent-uri)

MIT-0 license

12KB
94 lines

borrow-or-share

Traits for either borrowing or sharing data.

crates.io build license

See below for a basic usage of the crate. See the documentation for a detailed walkthrough.

Basic usage

Suppose that you have a generic type that either owns some data or holds a reference to them. You can use this crate to implement on this type a method taking &self that either borrows from *self or from behind a reference it holds:

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 is borrowed from `*text`
// and lives as long as `text`.
fn borrow(text: &Text<String>) -> &str {
    text.as_str()
}

// The returned reference is borrowed from `*text.0`, lives
// longer than `text` and is said to be shared with `*text`.
fn share<'a>(t: &Text<&'a str>) -> &'a str {
    text.as_str()
}

Credit

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

No runtime deps

Features