Crates.io | borrow-or-share |
lib.rs | borrow-or-share |
version | 0.2.2 |
source | src |
created_at | 2024-03-05 05:13:27.669339 |
updated_at | 2024-03-24 08:32:04.704753 |
description | Traits for either borrowing or sharing data. |
homepage | |
repository | https://github.com/yescallop/borrow-or-share |
max_upload_size | |
id | 1162683 |
size | 13,295 |
Traits for either borrowing or sharing data.
See below for a basic usage of the crate. See the documentation for a detailed walkthrough.
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 goes to @beepster4096 for figuring out a safe version of the code.