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§
Implementations§
Source§impl<B> Cow<'_, B>where
B: TryToOwned + ?Sized,
impl<B> Cow<'_, B>where
B: TryToOwned + ?Sized,
Sourcepub const fn is_borrowed(&self) -> bool
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());
Sourcepub const fn is_owned(&self) -> bool
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());
Sourcepub fn try_to_mut(&mut self) -> Result<&mut <B as TryToOwned>::Owned, Error>
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")?));
Sourcepub fn try_into_owned(self) -> Result<<B as TryToOwned>::Owned, Error>
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<'de, 'a, T> Deserialize<'de> for Cow<'a, T>
impl<'de, 'a, T> Deserialize<'de> for Cow<'a, T>
Source§fn deserialize<D>(
deserializer: D,
) -> Result<Cow<'a, T>, <D as Deserializer<'de>>::Error>where
D: Deserializer<'de>,
fn deserialize<D>(
deserializer: D,
) -> Result<Cow<'a, T>, <D as Deserializer<'de>>::Error>where
D: Deserializer<'de>,
Source§impl IntoComponent for Cow<'_, str>
impl IntoComponent for Cow<'_, str>
Source§fn as_component_ref(&self) -> ComponentRef<'_>
fn as_component_ref(&self) -> ComponentRef<'_>
Source§impl<B> Ord for Cow<'_, B>
impl<B> Ord for Cow<'_, B>
1.21.0 · Source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
fn max(self, other: Self) -> Selfwhere
Self: Sized,
Source§impl<B> PartialOrd for Cow<'_, B>
impl<B> PartialOrd for Cow<'_, B>
Source§impl<T> Serialize for Cow<'_, T>
impl<T> Serialize for Cow<'_, T>
Source§fn serialize<S>(
&self,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where
S: Serializer,
fn serialize<S>(
&self,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where
S: Serializer,
Source§impl TryFrom<Cow<'_, str>> for Box<str>
impl TryFrom<Cow<'_, str>> for Box<str>
Source§impl TryFrom<Cow<'_, str>> for String
impl TryFrom<Cow<'_, str>> for String
Source§fn try_from(s: Cow<'_, str>) -> Result<String, Error>
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");
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>,
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>,
impl<B> Eq for Cow<'_, B>
Auto Trait Implementations§
impl<'b, T> Freeze for Cow<'b, T>
impl<'b, T> RefUnwindSafe for Cow<'b, T>
impl<'b, T> Send for Cow<'b, T>
impl<'b, T> Sync for Cow<'b, T>
impl<'b, T> Unpin for Cow<'b, T>
impl<'b, T> UnwindSafe for Cow<'b, T>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<Q, K> Comparable<K> for Q
impl<Q, K> Comparable<K> for Q
Source§impl<T> EncodedChars for T
impl<T> EncodedChars for T
Source§fn encoding(&self) -> *mut OnigEncodingTypeST
fn encoding(&self) -> *mut OnigEncodingTypeST
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key
and return true
if they are equal.