Enum rune::alloc::borrow::Cow

source ·
pub enum Cow<'b, T>
where T: 'b + TryToOwned + ?Sized,
{ 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> Cow<'_, B>
where B: TryToOwned + ?Sized,

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> AsRef<T> for Cow<'_, T>
where T: TryToOwned + ?Sized,

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<(), Error>

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

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

§

type Target = B

The resulting type after dereferencing.
source§

fn deref(&self) -> &B

Dereferences the value.
source§

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

source§

fn deserialize<D>( deserializer: D ) -> Result<Cow<'a, T>, <D as Deserializer<'de>>::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<(), Error>

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

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

source§

fn from(b: &'a T) -> Cow<'a, T>

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>) -> Cow<'_, [T]>

Converts to this type from the input type.
source§

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

source§

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

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 IntoComponent for Cow<'_, str>

source§

fn as_component_ref(&self) -> ComponentRef<'_>

Convert into a component directly.
source§

fn into_component(self) -> Result<Component, Error>

Convert into component.
source§

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

source§

fn cmp(&self, other: &Cow<'_, B>) -> 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 + PartialOrd,

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

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

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

This method 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

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

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

This method 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

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

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

This method 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

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

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

This method 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

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

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

This method 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

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

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

This method 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: &Cow<'_, B>) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

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

This method 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: &Cow<'_, B>) -> 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

This method 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

This method 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

This method 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

This method 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 as Serializer>::Ok, <S as Serializer>::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<Cow<'_, str>, 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<Box<str>, 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());
§

type Error = Error

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

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

source§

fn try_from(s: Cow<'_, str>) -> Result<String, 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");
§

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: 'a + ToOwned + TryToOwned + ?Sized, <T as TryToOwned>::Owned: TryFrom<<T as ToOwned>::Owned>,

§

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<Cow<'a, T>, <Cow<'a, T> as TryFrom<Cow<'a, T>>>::Error>

Performs the conversion.
source§

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

Auto Trait Implementations§

§

impl<'b, T: ?Sized> RefUnwindSafe for Cow<'b, T>

§

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

§

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

§

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

§

impl<'b, T: ?Sized> 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> Comparable<K> for Q
where Q: Ord + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn compare(&self, key: &K) -> Ordering

Compare self to key and return their ordering.
source§

impl<T> EncodedChars for T
where T: AsRef<str>,

source§

fn start_ptr(&self) -> *const u8

Pointer to the start of the pattern Read more
source§

fn limit_ptr(&self) -> *const u8

Pointer to the limit of the pattern buffer Read more
source§

fn len(&self) -> usize

The length of this buffer
source§

fn encoding(&self) -> *mut OnigEncodingTypeST

The encoding of the contents of the buffer
source§

fn is_empty(&self) -> bool

Is the buffer empty?
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<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<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

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

Compare self to key and return true if they are equal.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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<T> Same for T

§

type Output = T

Should always be Self
source§

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

source§

default 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>,

§

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>,

§

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,

§

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<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

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

source§

impl<T> Formattable for T
where T: Deref, <T as Deref>::Target: Formattable,

source§

impl<T> Parsable for T
where T: Deref, <T as Deref>::Target: Parsable,