rune_alloc::borrow

Enum Cow

Source
pub enum Cow<'b, T>
where T: TryToOwned + ?Sized + 'b,
{ Borrowed(&'b T), Owned(<T as TryToOwned>::Owned), }
Expand description

A clone-on-write smart pointer.

The type Cow is a smart pointer providing clone-on-write functionality: it can enclose and provide immutable access to borrowed data, and clone the data lazily when mutation or ownership is required. The type is designed to work with general borrowed data via the Borrow trait.

Cow implements Deref, which means that you can call non-mutating methods directly on the data it encloses. If mutation is desired, to_mut will obtain a mutable reference to an owned value, cloning if necessary.

If you need reference-counting pointers, note that Rc::make_mut and Arc::make_mut can provide clone-on-write functionality as well.

§Examples

use rune::alloc::borrow::Cow;
use rune::alloc::try_vec;
use rune::alloc::prelude::*;

fn abs_all(input: &mut Cow<'_, [i32]>) -> rune::alloc::Result<()> {
    for i in 0..input.len() {
        let v = input[i];
        if v < 0 {
            // Clones into a vector if not already owned.
            input.try_to_mut()?[i] = -v;
        }
    }

    Ok(())
}

// No clone occurs because `input` doesn't need to be mutated.
let slice = [0, 1, 2];
let mut input = Cow::from(&slice[..]);
abs_all(&mut input)?;

// Clone occurs because `input` needs to be mutated.
let slice = [-1, 0, 1];
let mut input = Cow::from(&slice[..]);
abs_all(&mut input)?;

// No clone occurs because `input` is already owned.
let mut input = Cow::from(try_vec![-1, 0, 1]);
abs_all(&mut input)?;

Another example showing how to keep Cow in a struct:

use rune::alloc::Vec;
use rune::alloc::borrow::Cow;
use rune::alloc::prelude::*;

struct Items<'a, X> where [X]: TryToOwned<Owned = Vec<X>> {
    values: Cow<'a, [X]>,
}

impl<'a, X: TryClone + 'a> Items<'a, X> where [X]: TryToOwned<Owned = Vec<X>> {
    fn new(v: Cow<'a, [X]>) -> Self {
        Items { values: v }
    }
}

// Creates a container from borrowed values of a slice
let readonly = [1, 2];
let borrowed = Items::new((&readonly[..]).into());
match borrowed {
    Items { values: Cow::Borrowed(b) } => println!("borrowed {b:?}"),
    _ => panic!("expect borrowed value"),
}

let mut clone_on_write = borrowed;
// Mutates the data from slice into owned vec and pushes a new value on top
clone_on_write.values.try_to_mut()?.try_push(3)?;
println!("clone_on_write = {:?}", clone_on_write.values);

// The data was mutated. Let's check it out.
match clone_on_write {
    Items { values: Cow::Owned(_) } => println!("clone_on_write contains owned data"),
    _ => panic!("expect owned data"),
}

Variants§

§

Borrowed(&'b T)

Borrowed data.

§

Owned(<T as TryToOwned>::Owned)

Owned data.

Implementations§

Source§

impl<B: ?Sized + TryToOwned> Cow<'_, B>

Source

pub const fn is_borrowed(&self) -> bool

Returns true if the data is borrowed, i.e. if to_mut would require additional work.

§Examples
use rune::alloc::borrow::Cow;
use rune::alloc::prelude::*;

let cow = Cow::Borrowed("moo");
assert!(cow.is_borrowed());

let bull: Cow<'_, str> = Cow::Owned("...moo?".try_to_string()?);
assert!(!bull.is_borrowed());
Source

pub const fn is_owned(&self) -> bool

Returns true if the data is owned, i.e. if to_mut would be a no-op.

§Examples
use rune::alloc::borrow::Cow;
use rune::alloc::prelude::*;

let cow: Cow<'_, str> = Cow::Owned("moo".try_to_string()?);
assert!(cow.is_owned());

let bull = Cow::Borrowed("...moo?");
assert!(!bull.is_owned());
Source

pub fn try_to_mut(&mut self) -> Result<&mut <B as TryToOwned>::Owned, Error>

Acquires a mutable reference to the owned form of the data.

Clones the data if it is not already owned.

§Examples
use rune::alloc::borrow::Cow;
use rune::alloc::String;

let mut cow = Cow::Borrowed("foo");
cow.try_to_mut()?.make_ascii_uppercase();

assert_eq!(cow, Cow::Owned(String::try_from("FOO")?));
Source

pub fn try_into_owned(self) -> Result<<B as TryToOwned>::Owned, Error>

Extracts the owned data.

Clones the data if it is not already owned.

§Examples

Calling into_owned on a Cow::Borrowed returns a clone of the borrowed data:

use rune::alloc::borrow::Cow;
use rune::alloc::String;

let s = "Hello world!";
let cow = Cow::Borrowed(s);

assert_eq!(cow.try_into_owned()?, String::try_from(s)?);

Calling into_owned on a Cow::Owned returns the owned data. The data is moved out of the Cow without being cloned.

use rune::alloc::borrow::Cow;
use rune::alloc::String;

let s = "Hello world!";
let cow: Cow<'_, str> = Cow::Owned(String::try_from(s)?);

assert_eq!(cow.try_into_owned()?, String::try_from(s)?);

Trait Implementations§

Source§

impl<T: ?Sized + TryToOwned> AsRef<T> for Cow<'_, T>

Source§

fn as_ref(&self) -> &T

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl<T> Debug for Cow<'_, T>
where T: Debug + TryToOwned + ?Sized,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<B: ?Sized + TryToOwned> Deref for Cow<'_, B>
where B::Owned: Borrow<B>,

Source§

type Target = B

The resulting type after dereferencing.
Source§

fn deref(&self) -> &B

Dereferences the value.
Source§

impl<'de, T> Deserialize<'de> for Cow<'_, T>
where T: TryToOwned + ?Sized, T::Owned: Deserialize<'de>,

Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<T> Display for Cow<'_, T>
where T: Display + TryToOwned + ?Sized,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'a, T> From<&'a T> for Cow<'a, T>
where T: TryToOwned + ?Sized + 'a,

Source§

fn from(b: &'a T) -> Self

Construct a Cow from a reference.

§Examples
use rune::alloc::borrow::Cow;

let s = Cow::from("Hello World");
assert_eq!("Hello World", s);
Source§

impl<T> From<Vec<T>> for Cow<'_, [T]>
where T: TryClone,

Source§

fn from(vec: Vec<T>) -> Self

Converts to this type from the input type.
Source§

impl<B> Hash for Cow<'_, B>
where B: Hash + TryToOwned + ?Sized,

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

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

impl<B> Ord for Cow<'_, B>
where B: Ord + TryToOwned + ?Sized,

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<'a, 'b> PartialEq<&'b str> for Cow<'a, str>

Source§

fn eq(&self, other: &&'b str) -> bool

Tests for self and other values to be equal, and is used by ==.
Source§

fn ne(&self, other: &&'b str) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, 'b> PartialEq<Cow<'a, str>> for &'b str

Source§

fn eq(&self, other: &Cow<'a, str>) -> bool

Tests for self and other values to be equal, and is used by ==.
Source§

fn ne(&self, other: &Cow<'a, str>) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, 'b> PartialEq<Cow<'a, str>> for String

Source§

fn eq(&self, other: &Cow<'a, str>) -> bool

Tests for self and other values to be equal, and is used by ==.
Source§

fn ne(&self, other: &Cow<'a, str>) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, 'b> PartialEq<Cow<'a, str>> for str

Source§

fn eq(&self, other: &Cow<'a, str>) -> bool

Tests for self and other values to be equal, and is used by ==.
Source§

fn ne(&self, other: &Cow<'a, str>) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, 'b> PartialEq<String> for Cow<'a, str>

Source§

fn eq(&self, other: &String) -> bool

Tests for self and other values to be equal, and is used by ==.
Source§

fn ne(&self, other: &String) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, 'b> PartialEq<str> for Cow<'a, str>

Source§

fn eq(&self, other: &str) -> bool

Tests for self and other values to be equal, and is used by ==.
Source§

fn ne(&self, other: &str) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<B> PartialEq for Cow<'_, B>
where B: PartialEq + TryToOwned + ?Sized,

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<B> PartialOrd for Cow<'_, B>
where B: PartialOrd + TryToOwned + ?Sized,

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

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

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<T> Serialize for Cow<'_, T>
where T: Serialize + TryToOwned + ?Sized,

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl TryClone for Cow<'_, str>

Source§

fn try_clone(&self) -> Result<Self, Error>

Try to clone the current value, raising an allocation error if it’s unsuccessful.
Source§

fn try_clone_from(&mut self, source: &Self) -> Result<(), Error>

Performs copy-assignment from source. Read more
Source§

impl TryFrom<Cow<'_, str>> for Box<str>

Source§

fn try_from(s: Cow<'_, str>) -> Result<Self, Error>

Converts the given String to a boxed str slice that is owned.

§Examples
use rune::alloc::Box;
use rune::alloc::borrow::Cow;

let s2: Box<str> = Box::try_from(Cow::Borrowed("Hello World"))?;

assert_eq!("Hello World", s2.as_ref());
Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

impl TryFrom<Cow<'_, str>> for String<Global>

Source§

fn try_from(s: Cow<'_, str>) -> Result<Self, Error>

Converts a Cow<str> into a String.

The result is fallibly allocated on the heap unless the values is Cow::Owned.

use rune::alloc::String;
use rune::alloc::borrow::Cow;

let s = Cow::Borrowed("Hello World");
let s = String::try_from(s)?;
assert_eq!(s, "Hello World");

let s = Cow::Owned(String::try_from("Hello World")?);
let s = String::try_from(s)?;
assert_eq!(s, "Hello World");
Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

impl<'a, T> TryFrom<Cow<'a, T>> for Cow<'a, T>
where T: ToOwned + TryToOwned + ?Sized + 'a, <T as TryToOwned>::Owned: TryFrom<<T as ToOwned>::Owned>,

Source§

type Error = <<T as TryToOwned>::Owned as TryFrom<<T as ToOwned>::Owned>>::Error

The type returned in the event of a conversion error.
Source§

fn try_from(value: Cow<'a, T>) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl<B> Eq for Cow<'_, B>
where B: Eq + TryToOwned + ?Sized,

Auto Trait Implementations§

§

impl<'b, T> Freeze for Cow<'b, T>
where <T as TryToOwned>::Owned: Freeze, T: ?Sized,

§

impl<'b, T> RefUnwindSafe for Cow<'b, T>

§

impl<'b, T> Send for Cow<'b, T>
where <T as TryToOwned>::Owned: Send, T: Sync + ?Sized,

§

impl<'b, T> Sync for Cow<'b, T>
where <T as TryToOwned>::Owned: Sync, T: Sync + ?Sized,

§

impl<'b, T> Unpin for Cow<'b, T>
where <T as TryToOwned>::Owned: Unpin, T: ?Sized,

§

impl<'b, T> UnwindSafe for Cow<'b, T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> TryToOwned for T
where T: TryClone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn try_to_owned(&self) -> Result<T, Error>

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

impl<T> TryToString for T
where T: Display,

Source§

fn try_to_string(&self) -> Result<String, Error>

Converts the given value to a String. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,