Enum Cow

pub enum Cow<'a, B>
where
    B: ToOwned + ?Sized + 'a,

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][crate::rc::Rc::make_mut] and [Arc::make_mut][crate::sync::Arc::make_mut] can provide clone-on-write functionality as well.

Examples

use std::borrow::Cow;

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

// 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(vec![-1, 0, 1]);
abs_all(&mut input);

Another example showing how to keep Cow in a struct:

use std::borrow::Cow;

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

impl<'a, X: Clone + 'a> Items<'a, X> where [X]: ToOwned<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.to_mut().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(&'a B)

Borrowed data.

Owned(<B as ToOwned>::Owned)

Owned data.

Implementations

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

const fn is_borrowed(c: &Self) -> bool

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

Note: this is an associated function, which means that you have to call it as Cow::is_borrowed(&c) instead of c.is_borrowed(). This is so that there is no conflict with a method on the inner type.

Examples

#![feature(cow_is_borrowed)]
use std::borrow::Cow;

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

let bull: Cow<'_, str> = Cow::Owned("...moo?".to_string());
assert!(!Cow::is_borrowed(&bull));
const fn is_owned(c: &Self) -> bool

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

Note: this is an associated function, which means that you have to call it as Cow::is_owned(&c) instead of c.is_owned(). This is so that there is no conflict with a method on the inner type.

Examples

#![feature(cow_is_borrowed)]
use std::borrow::Cow;

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

let bull = Cow::Borrowed("...moo?");
assert!(!Cow::is_owned(&bull));
fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned

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

Clones the data if it is not already owned.

Examples

use std::borrow::Cow;

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

assert_eq!(
  cow,
  Cow::Owned(String::from("FOO")) as Cow<'_, str>
);
fn into_owned(self) -> <B as ToOwned>::Owned

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 std::borrow::Cow;

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

assert_eq!(
  cow.into_owned(),
  String::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 std::borrow::Cow;

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

assert_eq!(
  cow.into_owned(),
  String::from(s)
);

Trait Implementations

impl DerefPure for Cow<'_, str>

impl PartialEq<&ByteStr> for Cow<'_, ByteStr>

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

impl PartialEq<&ByteStr> for Cow<'_, [u8]>

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

impl PartialEq<&ByteStr> for Cow<'_, str>

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

impl PartialEq<&CStr> for Cow<'_, CStr>

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

impl PartialEq<&str> for Cow<'_, str>

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

impl PartialEq<ByteString> for Cow<'_, ByteStr>

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

impl PartialEq<ByteString> for Cow<'_, [u8]>

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

impl PartialEq<ByteString> for Cow<'_, str>

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

impl PartialEq<CStr> for Cow<'_, CStr>

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

impl PartialEq<CString> for Cow<'_, CStr>

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

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

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

impl PartialEq<str> for Cow<'_, str>

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

impl PartialOrd<&ByteStr> for Cow<'_, ByteStr>

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

impl PartialOrd<&ByteStr> for Cow<'_, [u8]>

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

impl PartialOrd<&ByteStr> for Cow<'_, str>

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

impl PartialOrd<ByteString> for Cow<'_, ByteStr>

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

impl PartialOrd<ByteString> for Cow<'_, [u8]>

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

impl PartialOrd<ByteString> for Cow<'_, str>

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

impl SpecToString for Cow<'_, str>

fn spec_to_string(&self) -> String

impl<'a> Add for Cow<'a, str>

type Output = Cow<'a, str>;
fn add(self, rhs: Cow<'a, str>) -> Self::Output

impl<'a> Add<&'a str> for Cow<'a, str>

type Output = Cow<'a, str>;
fn add(self, rhs: &'a str) -> Self::Output

impl<'a> AddAssign for Cow<'a, str>

fn add_assign(&mut self, rhs: Cow<'a, str>)

impl<'a> AddAssign<&'a str> for Cow<'a, str>

fn add_assign(&mut self, rhs: &'a str)

impl<'a> From<&'a ByteStr> for Cow<'a, ByteStr>

fn from(s: &'a ByteStr) -> Self

impl<'a> From<&'a ByteString> for Cow<'a, ByteStr>

fn from(s: &'a ByteString) -> Self

impl<'a> From<&'a CStr> for Cow<'a, CStr>

fn from(s: &'a CStr) -> Cow<'a, CStr>

Converts a CStr into a borrowed Cow without copying or allocating.

impl<'a> From<&'a CString> for Cow<'a, CStr>

fn from(s: &'a CString) -> Cow<'a, CStr>

Converts a &CString into a borrowed Cow without copying or allocating.

impl<'a> From<&'a String> for Cow<'a, str>

fn from(s: &'a String) -> Cow<'a, str>

Converts a String reference into a Borrowed variant. No heap allocation is performed, and the string is not copied.

Example

# use std::borrow::Cow;
let s = "eggplant".to_string();
assert_eq!(Cow::from(&s), Cow::Borrowed("eggplant"));

impl<'a> From<&'a str> for Cow<'a, str>

fn from(s: &'a str) -> Cow<'a, str>

Converts a string slice into a Borrowed variant. No heap allocation is performed, and the string is not copied.

Example

# use std::borrow::Cow;
assert_eq!(Cow::from("eggplant"), Cow::Borrowed("eggplant"));

impl<'a> From<ByteString> for Cow<'a, ByteStr>

fn from(s: ByteString) -> Self

impl<'a> From<CString> for Cow<'a, CStr>

fn from(s: CString) -> Cow<'a, CStr>

Converts a CString into an owned Cow without copying or allocating.

impl<'a> From<String> for Cow<'a, str>

fn from(s: String) -> Cow<'a, str>

Converts a String into an Owned variant. No heap allocation is performed, and the string is not copied.

Example

# use std::borrow::Cow;
let s = "eggplant".to_string();
let s2 = "eggplant".to_string();
assert_eq!(Cow::from(s), Cow::<'static, str>::Owned(s2));

impl<'a> FromIterator<AsciiChar> for Cow<'a, str>

fn from_iter<I: IntoIterator<Item = Char>>(it: I) -> Self

impl<'a> FromIterator<String> for Cow<'a, str>

fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str>

impl<'a> FromIterator<char> for Cow<'a, str>

fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str>

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

fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str>

impl<'a, 'b, B, C> PartialEq<Cow<'b, C>> for Cow<'a, B> where B: PartialEq<C> + ToOwned + ?Sized, C: ToOwned + ?Sized,

fn eq(&self, other: &Cow<'b, C>) -> bool

impl<'a, B> PartialOrd for Cow<'a, B> where B: PartialOrd + ToOwned + ?Sized,

fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering>

impl<'a, B: ?Sized + ToOwned> Borrow<B> for Cow<'a, B>

fn borrow(&self) -> &B

impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone,

fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]>

impl<'a, T: Clone> From<&'a Vec<T>> for Cow<'a, [T]>

fn from(v: &'a Vec<T>) -> Cow<'a, [T]>

Creates a Borrowed variant of Cow from a reference to Vec.

This conversion does not allocate or clone the data.

impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]>

fn from(s: &'a [T]) -> Cow<'a, [T]>

Creates a Borrowed variant of Cow from a slice.

This conversion does not allocate or clone the data.

impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]>

fn from(v: Vec<T>) -> Cow<'a, [T]>

Creates an Owned variant of Cow from an owned instance of Vec.

This conversion does not allocate or clone the data.

impl<'a, T: Clone, const N: usize> From<&'a [T; N]> for Cow<'a, [T]>

fn from(s: &'a [T; N]) -> Cow<'a, [T]>

Creates a Borrowed variant of Cow from a reference to an array.

This conversion does not allocate or clone the data.

impl<B> Debug for Cow<'_, B> where B: Debug + ToOwned<Owned: Debug> + ?Sized,

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

impl<B> Default for Cow<'_, B> where B: ToOwned<Owned: Default> + ?Sized,

fn default() -> Self

Creates an owned Cow<'a, B> with the default value for the contained owned value.

impl<B> Display for Cow<'_, B> where B: Display + ToOwned<Owned: Display> + ?Sized,

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

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

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

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

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

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

impl<B: ?Sized + ToOwned> Clone for Cow<'_, B>

fn clone(&self) -> Self
fn clone_from(&mut self, source: &Self)

impl<B: ?Sized + ToOwned> Deref for Cow<'_, B>

type Target = B;
fn deref(&self) -> &B

impl<T, U> PartialEq<&[U]> for Cow<'_, [T]> where T: PartialEq<U> + Clone,

fn eq(&self, other: &&[U]) -> bool
fn ne(&self, other: &&[U]) -> bool

impl<T, U> PartialEq<&mut [U]> for Cow<'_, [T]> where T: PartialEq<U> + Clone,

fn eq(&self, other: &&mut [U]) -> bool
fn ne(&self, other: &&mut [U]) -> bool

impl<T, U, A: Allocator> PartialEq<Vec<U, A>> for Cow<'_, [T]> where T: PartialEq<U> + Clone,

fn eq(&self, other: &Vec<U, A>) -> bool
fn ne(&self, other: &Vec<U, A>) -> bool

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

fn as_ref(&self) -> &T

impl<T: Clone> DerefPure for Cow<'_, T>

impl<T: Clone> DerefPure for Cow<'_, [T]>

Auto Trait Implementations

impl<'a, B> Freeze for Cow<'a, B> where &'a B: Freeze, <B as ToOwned>::Owned: Freeze, B: ?Sized,

impl<'a, B> RefUnwindSafe for Cow<'a, B> where &'a B: RefUnwindSafe, <B as ToOwned>::Owned: RefUnwindSafe, B: ?Sized,

impl<'a, B> Send for Cow<'a, B> where &'a B: Send, <B as ToOwned>::Owned: Send, B: ?Sized,

impl<'a, B> Sync for Cow<'a, B> where &'a B: Sync, <B as ToOwned>::Owned: Sync, B: ?Sized,

impl<'a, B> Unpin for Cow<'a, B> where &'a B: Unpin, <B as ToOwned>::Owned: Unpin, B: ?Sized,

impl<'a, B> UnsafeUnpin for Cow<'a, B> where &'a B: UnsafeUnpin, <B as ToOwned>::Owned: UnsafeUnpin, B: ?Sized,

impl<'a, B> UnwindSafe for Cow<'a, B> where &'a B: UnwindSafe, <B as ToOwned>::Owned: UnwindSafe, B: ?Sized,

Blanket Implementations

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

type Target = T;

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

fn type_id(&self) -> TypeId

impl<T> Borrow<T> for Cow<'a, B> where T: ?Sized,

fn borrow(&self) -> &T

impl<T> BorrowMut<T> for Cow<'a, B> where T: ?Sized,

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

impl<T> CloneToUninit for Cow<'a, B> where T: Clone,

unsafe fn clone_to_uninit(&self, dest: *mut u8)

impl<T> From<T> for Cow<'a, B>

fn from(t: T) -> T

Returns the argument unchanged.

impl<T> SizeHint for Cow<'a, B> where T: ?Sized,

fn lower_bound(&self) -> usize
fn upper_bound(&self) -> Option<usize>

impl<T> SizedTypeProperties for Cow<'a, B>

impl<T> ToOwned for Cow<'a, B> where T: Clone,

type Owned = T;
fn to_owned(&self) -> T
fn clone_into(&self, target: &mut T)

impl<T> ToString for Cow<'a, B> where T: Display + ?Sized,

fn to_string(&self) -> String

impl<T, U> Into<U> for Cow<'a, B> where U: From<T>,

fn into(self) -> U

Calls U::from(self).

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

impl<T, U> TryFrom<U> for Cow<'a, B> where U: Into<T>,

type Error = never;
fn try_from(value: U) -> Result<T, never>

impl<T, U> TryInto<U> for Cow<'a, B> where U: TryFrom<T>,

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