1 //! A module for working with borrowed data.
3 #![stable(feature = "rust1", since = "1.0.0")]
5 use core::cmp::Ordering;
6 use core::hash::{Hash, Hasher};
8 #[cfg(not(no_global_oom_handling))]
9 use core::ops::{Add, AddAssign};
11 #[stable(feature = "rust1", since = "1.0.0")]
12 pub use core::borrow::{Borrow, BorrowMut};
15 #[cfg(not(no_global_oom_handling))]
16 use crate::string::String;
20 #[stable(feature = "rust1", since = "1.0.0")]
21 impl<'a, B: ?Sized> Borrow<B> for Cow<'a, B>
24 <B as ToOwned>::Owned: 'a,
26 fn borrow(&self) -> &B {
31 /// A generalization of `Clone` to borrowed data.
33 /// Some types make it possible to go from borrowed to owned, usually by
34 /// implementing the `Clone` trait. But `Clone` works only for going from `&T`
35 /// to `T`. The `ToOwned` trait generalizes `Clone` to construct owned data
36 /// from any borrow of a given type.
37 #[cfg_attr(not(test), rustc_diagnostic_item = "ToOwned")]
38 #[stable(feature = "rust1", since = "1.0.0")]
40 /// The resulting type after obtaining ownership.
41 #[stable(feature = "rust1", since = "1.0.0")]
42 type Owned: Borrow<Self>;
44 /// Creates owned data from borrowed data, usually by cloning.
51 /// let s: &str = "a";
52 /// let ss: String = s.to_owned();
54 /// let v: &[i32] = &[1, 2];
55 /// let vv: Vec<i32> = v.to_owned();
57 #[stable(feature = "rust1", since = "1.0.0")]
58 #[must_use = "cloning is often expensive and is not expected to have side effects"]
59 fn to_owned(&self) -> Self::Owned;
61 /// Uses borrowed data to replace owned data, usually by cloning.
63 /// This is borrow-generalized version of [`Clone::clone_from`].
70 /// let mut s: String = String::new();
71 /// "hello".clone_into(&mut s);
73 /// let mut v: Vec<i32> = Vec::new();
74 /// [1, 2][..].clone_into(&mut v);
76 #[stable(feature = "toowned_clone_into", since = "1.63.0")]
77 fn clone_into(&self, target: &mut Self::Owned) {
78 *target = self.to_owned();
82 #[stable(feature = "rust1", since = "1.0.0")]
88 fn to_owned(&self) -> T {
92 fn clone_into(&self, target: &mut T) {
93 target.clone_from(self);
97 /// A clone-on-write smart pointer.
99 /// The type `Cow` is a smart pointer providing clone-on-write functionality: it
100 /// can enclose and provide immutable access to borrowed data, and clone the
101 /// data lazily when mutation or ownership is required. The type is designed to
102 /// work with general borrowed data via the `Borrow` trait.
104 /// `Cow` implements `Deref`, which means that you can call
105 /// non-mutating methods directly on the data it encloses. If mutation
106 /// is desired, `to_mut` will obtain a mutable reference to an owned
107 /// value, cloning if necessary.
109 /// If you need reference-counting pointers, note that
110 /// [`Rc::make_mut`][crate::rc::Rc::make_mut] and
111 /// [`Arc::make_mut`][crate::sync::Arc::make_mut] can provide clone-on-write
112 /// functionality as well.
117 /// use std::borrow::Cow;
119 /// fn abs_all(input: &mut Cow<[i32]>) {
120 /// for i in 0..input.len() {
121 /// let v = input[i];
123 /// // Clones into a vector if not already owned.
124 /// input.to_mut()[i] = -v;
129 /// // No clone occurs because `input` doesn't need to be mutated.
130 /// let slice = [0, 1, 2];
131 /// let mut input = Cow::from(&slice[..]);
132 /// abs_all(&mut input);
134 /// // Clone occurs because `input` needs to be mutated.
135 /// let slice = [-1, 0, 1];
136 /// let mut input = Cow::from(&slice[..]);
137 /// abs_all(&mut input);
139 /// // No clone occurs because `input` is already owned.
140 /// let mut input = Cow::from(vec![-1, 0, 1]);
141 /// abs_all(&mut input);
144 /// Another example showing how to keep `Cow` in a struct:
147 /// use std::borrow::Cow;
149 /// struct Items<'a, X: 'a> where [X]: ToOwned<Owned = Vec<X>> {
150 /// values: Cow<'a, [X]>,
153 /// impl<'a, X: Clone + 'a> Items<'a, X> where [X]: ToOwned<Owned = Vec<X>> {
154 /// fn new(v: Cow<'a, [X]>) -> Self {
155 /// Items { values: v }
159 /// // Creates a container from borrowed values of a slice
160 /// let readonly = [1, 2];
161 /// let borrowed = Items::new((&readonly[..]).into());
163 /// Items { values: Cow::Borrowed(b) } => println!("borrowed {b:?}"),
164 /// _ => panic!("expect borrowed value"),
167 /// let mut clone_on_write = borrowed;
168 /// // Mutates the data from slice into owned vec and pushes a new value on top
169 /// clone_on_write.values.to_mut().push(3);
170 /// println!("clone_on_write = {:?}", clone_on_write.values);
172 /// // The data was mutated. Let's check it out.
173 /// match clone_on_write {
174 /// Items { values: Cow::Owned(_) } => println!("clone_on_write contains owned data"),
175 /// _ => panic!("expect owned data"),
178 #[stable(feature = "rust1", since = "1.0.0")]
179 #[cfg_attr(not(test), rustc_diagnostic_item = "Cow")]
180 pub enum Cow<'a, B: ?Sized + 'a>
185 #[stable(feature = "rust1", since = "1.0.0")]
186 Borrowed(#[stable(feature = "rust1", since = "1.0.0")] &'a B),
189 #[stable(feature = "rust1", since = "1.0.0")]
190 Owned(#[stable(feature = "rust1", since = "1.0.0")] <B as ToOwned>::Owned),
193 #[stable(feature = "rust1", since = "1.0.0")]
194 impl<B: ?Sized + ToOwned> Clone for Cow<'_, B> {
195 fn clone(&self) -> Self {
197 Borrowed(b) => Borrowed(b),
199 let b: &B = o.borrow();
205 fn clone_from(&mut self, source: &Self) {
206 match (self, source) {
207 (&mut Owned(ref mut dest), &Owned(ref o)) => o.borrow().clone_into(dest),
208 (t, s) => *t = s.clone(),
213 impl<B: ?Sized + ToOwned> Cow<'_, B> {
214 /// Returns true if the data is borrowed, i.e. if `to_mut` would require additional work.
219 /// #![feature(cow_is_borrowed)]
220 /// use std::borrow::Cow;
222 /// let cow = Cow::Borrowed("moo");
223 /// assert!(cow.is_borrowed());
225 /// let bull: Cow<'_, str> = Cow::Owned("...moo?".to_string());
226 /// assert!(!bull.is_borrowed());
228 #[unstable(feature = "cow_is_borrowed", issue = "65143")]
229 #[rustc_const_unstable(feature = "const_cow_is_borrowed", issue = "65143")]
230 pub const fn is_borrowed(&self) -> bool {
237 /// Returns true if the data is owned, i.e. if `to_mut` would be a no-op.
242 /// #![feature(cow_is_borrowed)]
243 /// use std::borrow::Cow;
245 /// let cow: Cow<'_, str> = Cow::Owned("moo".to_string());
246 /// assert!(cow.is_owned());
248 /// let bull = Cow::Borrowed("...moo?");
249 /// assert!(!bull.is_owned());
251 #[unstable(feature = "cow_is_borrowed", issue = "65143")]
252 #[rustc_const_unstable(feature = "const_cow_is_borrowed", issue = "65143")]
253 pub const fn is_owned(&self) -> bool {
257 /// Acquires a mutable reference to the owned form of the data.
259 /// Clones the data if it is not already owned.
264 /// use std::borrow::Cow;
266 /// let mut cow = Cow::Borrowed("foo");
267 /// cow.to_mut().make_ascii_uppercase();
271 /// Cow::Owned(String::from("FOO")) as Cow<str>
274 #[stable(feature = "rust1", since = "1.0.0")]
275 pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned {
277 Borrowed(borrowed) => {
278 *self = Owned(borrowed.to_owned());
280 Borrowed(..) => unreachable!(),
281 Owned(ref mut owned) => owned,
284 Owned(ref mut owned) => owned,
288 /// Extracts the owned data.
290 /// Clones the data if it is not already owned.
294 /// Calling `into_owned` on a `Cow::Borrowed` returns a clone of the borrowed data:
297 /// use std::borrow::Cow;
299 /// let s = "Hello world!";
300 /// let cow = Cow::Borrowed(s);
303 /// cow.into_owned(),
308 /// Calling `into_owned` on a `Cow::Owned` returns the owned data. The data is moved out of the
309 /// `Cow` without being cloned.
312 /// use std::borrow::Cow;
314 /// let s = "Hello world!";
315 /// let cow: Cow<str> = Cow::Owned(String::from(s));
318 /// cow.into_owned(),
322 #[stable(feature = "rust1", since = "1.0.0")]
323 pub fn into_owned(self) -> <B as ToOwned>::Owned {
325 Borrowed(borrowed) => borrowed.to_owned(),
326 Owned(owned) => owned,
331 #[stable(feature = "rust1", since = "1.0.0")]
332 #[rustc_const_unstable(feature = "const_deref", issue = "88955")]
333 impl<B: ?Sized + ToOwned> const Deref for Cow<'_, B>
335 B::Owned: ~const Borrow<B>,
339 fn deref(&self) -> &B {
341 Borrowed(borrowed) => borrowed,
342 Owned(ref owned) => owned.borrow(),
347 #[stable(feature = "rust1", since = "1.0.0")]
348 impl<B: ?Sized> Eq for Cow<'_, B> where B: Eq + ToOwned {}
350 #[stable(feature = "rust1", since = "1.0.0")]
351 impl<B: ?Sized> Ord for Cow<'_, B>
356 fn cmp(&self, other: &Self) -> Ordering {
357 Ord::cmp(&**self, &**other)
361 #[stable(feature = "rust1", since = "1.0.0")]
362 impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, C>> for Cow<'a, B>
364 B: PartialEq<C> + ToOwned,
368 fn eq(&self, other: &Cow<'b, C>) -> bool {
369 PartialEq::eq(&**self, &**other)
373 #[stable(feature = "rust1", since = "1.0.0")]
374 impl<'a, B: ?Sized> PartialOrd for Cow<'a, B>
376 B: PartialOrd + ToOwned,
379 fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering> {
380 PartialOrd::partial_cmp(&**self, &**other)
384 #[stable(feature = "rust1", since = "1.0.0")]
385 impl<B: ?Sized> fmt::Debug for Cow<'_, B>
387 B: fmt::Debug + ToOwned<Owned: fmt::Debug>,
389 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
391 Borrowed(ref b) => fmt::Debug::fmt(b, f),
392 Owned(ref o) => fmt::Debug::fmt(o, f),
397 #[stable(feature = "rust1", since = "1.0.0")]
398 impl<B: ?Sized> fmt::Display for Cow<'_, B>
400 B: fmt::Display + ToOwned<Owned: fmt::Display>,
402 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
404 Borrowed(ref b) => fmt::Display::fmt(b, f),
405 Owned(ref o) => fmt::Display::fmt(o, f),
410 #[stable(feature = "default", since = "1.11.0")]
411 impl<B: ?Sized> Default for Cow<'_, B>
413 B: ToOwned<Owned: Default>,
415 /// Creates an owned Cow<'a, B> with the default value for the contained owned value.
416 fn default() -> Self {
417 Owned(<B as ToOwned>::Owned::default())
421 #[stable(feature = "rust1", since = "1.0.0")]
422 impl<B: ?Sized> Hash for Cow<'_, B>
427 fn hash<H: Hasher>(&self, state: &mut H) {
428 Hash::hash(&**self, state)
432 #[stable(feature = "rust1", since = "1.0.0")]
433 impl<T: ?Sized + ToOwned> AsRef<T> for Cow<'_, T> {
434 fn as_ref(&self) -> &T {
439 #[cfg(not(no_global_oom_handling))]
440 #[stable(feature = "cow_add", since = "1.14.0")]
441 impl<'a> Add<&'a str> for Cow<'a, str> {
442 type Output = Cow<'a, str>;
445 fn add(mut self, rhs: &'a str) -> Self::Output {
451 #[cfg(not(no_global_oom_handling))]
452 #[stable(feature = "cow_add", since = "1.14.0")]
453 impl<'a> Add<Cow<'a, str>> for Cow<'a, str> {
454 type Output = Cow<'a, str>;
457 fn add(mut self, rhs: Cow<'a, str>) -> Self::Output {
463 #[cfg(not(no_global_oom_handling))]
464 #[stable(feature = "cow_add", since = "1.14.0")]
465 impl<'a> AddAssign<&'a str> for Cow<'a, str> {
466 fn add_assign(&mut self, rhs: &'a str) {
468 *self = Cow::Borrowed(rhs)
469 } else if !rhs.is_empty() {
470 if let Cow::Borrowed(lhs) = *self {
471 let mut s = String::with_capacity(lhs.len() + rhs.len());
473 *self = Cow::Owned(s);
475 self.to_mut().push_str(rhs);
480 #[cfg(not(no_global_oom_handling))]
481 #[stable(feature = "cow_add", since = "1.14.0")]
482 impl<'a> AddAssign<Cow<'a, str>> for Cow<'a, str> {
483 fn add_assign(&mut self, rhs: Cow<'a, str>) {
486 } else if !rhs.is_empty() {
487 if let Cow::Borrowed(lhs) = *self {
488 let mut s = String::with_capacity(lhs.len() + rhs.len());
490 *self = Cow::Owned(s);
492 self.to_mut().push_str(&rhs);