pub enum MaybeOwned<'a, T: 'a> {
    Owned(T),
    Borrowed(&'a T),
}
Expand description

This type provides a way to store data to which you either have a reference to or which you do own.

It provides From<T>, From<&'a T> implementations and, in difference to Cow does not require ToOwned to be implemented which makes it compatible with non cloneable data, as a draw back of this it does not know about ToOwned. As a consequence of it can’t know that &str should be the borrowed version of String and not &String this is especially bad wrt. Box as the borrowed version of Box<T> would be &Box<T>.

While this crate has some drawbacks compared to Cow is has the benefit, that it works with Types which neither implement Clone nor ToOwned. Another benefit lies in the ability to write API functions which accept a generic parameter E: Into<MaybeOwned<'a, T>> as the API consumer can pass T, &'a T and MaybeOwned<'a, T> as argument, without requiring a explicit Cow::Owned or a split into two functions one accepting owed and the other borrowed values.

Alternatives

If you mainly have values implementing ToOwned like &str/String, Path/PathBuf or &[T]/Vec<T> using std::borrow::Cow might be preferable.

If you want to be able to treat &T, &mut T, Box<T> and Arc<T> the same consider using reffers::rbma::RBMA (through not all types/platforms are supported because as it relies on the fact that for many pointers the lowest two bits are 0, and stores the discriminant in them, nevertheless this is can only be used with 32bit-aligned data, e.g. using a &u8 might fail). RBMA also allows you to recover a &mut T if it was created from Box<T>, &mut T or a unique Arc.

Examples

struct PseudoBigData(u8);
fn pseudo_register_fn<'a, E>(_val: E) where E: Into<MaybeOwned<'a, PseudoBigData>> { }

let data = PseudoBigData(12);
let data2 = PseudoBigData(13);

pseudo_register_fn(&data);
pseudo_register_fn(&data);
pseudo_register_fn(data2);
pseudo_register_fn(MaybeOwned::Owned(PseudoBigData(111)));
#[repr(C)]
struct OpaqueFFI {
    ref1:  * const u8
    //we also might want to have PhantomData etc.
}

// does not work as it does not implement `ToOwned`
// let _ = Cow::Owned(OpaqueFFI { ref1: 0 as *const u8});

// ok, MaybeOwned can do this (but can't do &str<->String as tread of)
let _ = MaybeOwned::Owned(OpaqueFFI { ref1: 0 as *const u8 });
use std::collections::HashMap;

#[derive(Serialize, Deserialize)]
struct SerializedData<'a> {
    data: MaybeOwned<'a, HashMap<String, i32>>,
}

let mut map = HashMap::new();
map.insert("answer".to_owned(), 42);

// serializing can use borrowed data to avoid unnecessary copying
let bytes = serde_json::to_vec(&SerializedData { data: (&map).into() }).unwrap();

// deserializing creates owned data
let deserialized: SerializedData = serde_json::from_slice(&bytes).unwrap();
assert_eq!(deserialized.data["answer"], 42);

Transitive std::ops implementations

There are transitive implementations for most operator in std::ops.

A Op between a MaybeOwned<L> and MaybeOwned<R> is implemented if:

  • L impl the Op with R
  • L impl the Op with &R
  • &L impl the Op with R
  • &L impl the Op with &R
  • the Output of all aboves implementations is the same type

The Neg (- prefix) op is implemented for V if:

  • V impl Neg
  • &V impl Neg
  • both have the same Output

The Not (! prefix) op is implemented for V if:

  • V impl Not
  • &V impl Not
  • both have the same Output

Adding implementations for Ops which add a MaybeOwned to a non MaybeOwned value (like MaybeOwned<T> + T) requires far reaching specialization in rust and is therefore not done for now.

Variants

Owned(T)

owns T

Borrowed(&'a T)

has a reference to T

Implementations

Returns true if the data is owned else false.

Return the contained data in it’s owned form.

If it’s borrowed this will clone it.

Internally converts the type into it’s owned variant.

Conversion from a reference to the owned variant is done by cloning.

This returns a &mut T and as such can be used to “unconditionally” get an &mut T. Be aware that while this works with both MaybeOwned and MaybeOwnedMut it also converts it to an owned variant in both cases. So while it’s the best way to get a &mut T for MaybeOwned for MaybeOwnedMut it’s preferable to use as_mut from AsMut.

Example
use maybe_owned::MaybeOwned;

#[derive(Clone, Debug, PartialEq, Eq)]
struct PseudoBigData(u8);

let data = PseudoBigData(12);

let mut maybe: MaybeOwned<PseudoBigData> = (&data).into();
assert_eq!(false, maybe.is_owned());

{
    let reference = maybe.make_owned();
    assert_eq!(&mut PseudoBigData(12), reference);
}
assert!(maybe.is_owned());

Returns a &mut if possible.

If the internal representation is borrowed (&T) then this method will return None

👎 Deprecated:

use make_owned instead

Acquires a mutable reference to owned data.

Clones data if it is not already owned.

Example
use maybe_owned::MaybeOwned;

#[derive(Clone, Debug, PartialEq, Eq)]
struct PseudoBigData(u8);

let data = PseudoBigData(12);

let mut maybe: MaybeOwned<PseudoBigData> = (&data).into();
assert_eq!(false, maybe.is_owned());

{
    let reference = maybe.to_mut();
    assert_eq!(&mut PseudoBigData(12), reference);
}
assert!(maybe.is_owned());

Trait Implementations

The resulting type after applying the + operator.

Performs the + operation. Read more

Performs the += operation. Read more

Performs the conversion.

The resulting type after applying the & operator.

Performs the & operation. Read more

Performs the &= operation. Read more

The resulting type after applying the | operator.

Performs the | operation. Read more

Performs the |= operation. Read more

The resulting type after applying the ^ operator.

Performs the ^ operation. Read more

Performs the ^= operation. Read more

Immutably borrows from an owned value. Read more

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Returns the “default value” for a type. Read more

The resulting type after dereferencing.

Dereferences the value.

Formats the value using the given formatter. Read more

The resulting type after applying the / operator.

Performs the / operation. Read more

Performs the /= operation. Read more

Performs the conversion.

Performs the conversion.

Performs the conversion.

The associated error which can be returned from parsing.

Parses a string s to return a value of this type. Read more

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

Performs the conversion.

The resulting type after applying the * operator.

Performs the * operation. Read more

Performs the *= operation. Read more

The resulting type after applying the - operator.

Performs the unary - operation. Read more

The resulting type after applying the ! operator.

Performs the unary ! operation. Read more

This method returns an Ordering between self and other. Read more

Compares and returns the maximum of two values. Read more

Compares and returns the minimum of two values. Read more

Restrict a value to a certain interval. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

This method returns an ordering between self and other values if one exists. Read more

This method tests less than (for self and other) and is used by the < operator. Read more

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

This method tests greater than (for self and other) and is used by the > operator. Read more

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

The resulting type after applying the << operator.

Performs the << operation. Read more

Performs the <<= operation. Read more

The resulting type after applying the >> operator.

Performs the >> operation. Read more

Performs the >>= operation. Read more

The resulting type after applying the - operator.

Performs the - operation. Read more

Performs the -= operation. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

Uses borrowed data to replace owned data, usually by cloning. Read more

Converts the given value to a String. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.