Enum Cow

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(self: &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: 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)
);

impl DerefPure for Cow<'_, str>

impl PartialEq for crate::borrow::Cow<'_, core::ffi::CStr>

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

impl PartialEq for crate::borrow::Cow<'_, core::ffi::CStr>

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

impl PartialEq for crate::borrow::Cow<'_, core::ffi::CStr>

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

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

fn add(self: Self, rhs: &'a str) -> <Self as >::Output

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

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

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

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

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

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

impl<'a> From for crate::borrow::Cow<'a, ByteStr>

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

impl<'a> From for crate::borrow::Cow<'a, ByteStr>

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

impl<'a> From for crate::borrow::Cow<'a, ByteStr>

fn from(s: ByteString) -> Self

impl<'a> From for crate::borrow::Cow<'a, core::ffi::CStr>

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

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

impl<'a> From for crate::borrow::Cow<'a, core::ffi::CStr>

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

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

impl<'a> From for crate::borrow::Cow<'a, core::ffi::CStr>

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

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

impl<'a> From for crate::borrow::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 for crate::borrow::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> From for crate::borrow::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> FromIterator for crate::borrow::Cow<'a, str>

fn from_iter<T: IntoIterator<Item = core::ascii::Char>>(it: T) -> Self

impl<'a> FromIterator for crate::borrow::Cow<'a, str>

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

impl<'a> FromIterator for crate::borrow::Cow<'a, str>

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

impl<'a> PartialEq for crate::borrow::Cow<'_, ByteStr>

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

impl<'a> PartialEq for crate::borrow::Cow<'_, [u8]>

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

impl<'a> PartialEq for crate::borrow::Cow<'_, str>

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

impl<'a> PartialEq for crate::borrow::Cow<'a, ByteStr>

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

impl<'a> PartialEq for crate::borrow::Cow<'a, [u8]>

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

impl<'a> PartialEq for crate::borrow::Cow<'a, str>

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

impl<'a> PartialOrd for crate::borrow::Cow<'_, ByteStr>

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

impl<'a> PartialOrd for crate::borrow::Cow<'_, [u8]>

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

impl<'a> PartialOrd for crate::borrow::Cow<'_, str>

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

impl<'a> PartialOrd for crate::borrow::Cow<'a, ByteStr>

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

impl<'a> PartialOrd for crate::borrow::Cow<'a, [u8]>

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

impl<'a> PartialOrd for crate::borrow::Cow<'a, str>

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

impl<'a, 'b> FromIterator for crate::borrow::Cow<'a, str>

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

impl<'a, 'b> PartialEq for crate::borrow::Cow<'a, str>

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

impl<'a, 'b> PartialEq for crate::borrow::Cow<'a, str>

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

impl<'a, 'b> PartialEq for crate::borrow::Cow<'a, str>

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

impl<'a, 'b, B, C> PartialEq for Cow<'a, B>

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

impl<'a, B> Freeze for Cow<'a, B>

impl<'a, B> PartialOrd for Cow<'a, B>

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

impl<'a, B> RefUnwindSafe for Cow<'a, B>

impl<'a, B> Send for Cow<'a, B>

impl<'a, B> Sync for Cow<'a, B>

impl<'a, B> Unpin for Cow<'a, B>

impl<'a, B> UnwindSafe for Cow<'a, B>

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

fn borrow(self: &Self) -> &B

impl<'a, T> FromIterator for crate::borrow::Cow<'a, [T]>

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

impl<'a, T: Clone> From for crate::borrow::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 for crate::borrow::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> From for crate::borrow::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, N: usize> From for crate::borrow::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>

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

impl<B> Default for Cow<'_, B>

fn default() -> Self

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

impl<B> Display for Cow<'_, B>

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

impl<B> Eq for Cow<'_, B>

impl<B> Hash for Cow<'_, B>

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

impl<B> Ord for Cow<'_, B>

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

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

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

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

fn deref(self: &Self) -> &B

impl<P, T> Receiver for Cow<'a, B>

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

fn type_id(self: &Self) -> TypeId

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

fn borrow(self: &Self) -> &T

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

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

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

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

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

fn from(t: T) -> T

Returns the argument unchanged.

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

fn to_owned(self: &Self) -> T
fn clone_into(self: &Self, target: &mut T)

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

fn to_string(self: &Self) -> String

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

fn into(self: 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> PartialEq for crate::borrow::Cow<'_, [T]>

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

impl<T, U> PartialEq for crate::borrow::Cow<'_, [T]>

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

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

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

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

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

impl<T, U, A: Allocator> PartialEq for crate::borrow::Cow<'_, [T]>

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

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

fn as_ref(self: &Self) -> &T

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

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