maybe-owned-trait

Crates.iomaybe-owned-trait
lib.rsmaybe-owned-trait
version0.2.1
sourcesrc
created_at2023-09-14 03:16:21.990764
updated_at2023-09-14 03:35:35.7399
descriptionEither an owned or borrowed value, with type known at compile time.
homepage
repositoryhttps://github.com/JohnScience/maybe-owned-trait
max_upload_size
id972195
size21,524
Dmitrii - Demenev (JohnScience)

documentation

https://docs.rs/maybe-owned-trait

README

Either an owned or borrowed value, with type known at compile time

Crates.io Downloads Documentation License Dependency Status

This crate offers a MaybeOwned trait which allows you to pass either an owned or a borrowed value to a function. As opposed to std::borrow::Cow and beef::Cow, this trait

However, it also creates additional mental overhead and in some cases might cause genericity-induced problems.

Eventually, definition sites might become cleaner with an attribute proc macro.

Example

use rand::Rng;
use maybe_owned_trait::MaybeOwned;
use std::path::{Path, PathBuf};

// Definition site is a bit more verbose than with `Cow`, yet still reasonable
fn my_fn(path: impl for<'a> MaybeOwned<Owned = PathBuf, Borrowed<'a> = &'a Path>) {
    // Of course, you'll have a meaningful condition here
    if rand::thread_rng().gen::<bool>() {
        let path_buf: PathBuf = path.to_owned();
        println!("Owned buf: {:?}", path_buf);
    } else {
        let path: &Path = path.borrow();
        println!("Borrowed path: {:?}", path);
    };
}

let path = PathBuf::from("hello");
// Call sites are clean
my_fn(&path);
my_fn(path);

With beef feature enabled, this crate also provides the implementations of MaybeOwned for beef::Cow and beef::lean::Cow.

Commit count: 8

cargo fmt