1 // SPDX-License-Identifier: Apache-2.0 OR MIT
3 //! A module for working with borrowed data.
5 #![stable(feature = "rust1", since = "1.0.0")]
7 use core::cmp::Ordering;
8 use core::hash::{Hash, Hasher};
10 #[cfg(not(no_global_oom_handling))]
11 use core::ops::{Add, AddAssign};
13 #[stable(feature = "rust1", since = "1.0.0")]
14 pub use core::borrow::{Borrow, BorrowMut};
17 #[cfg(not(no_global_oom_handling))]
18 use crate::string::String;
22 #[stable(feature = "rust1", since = "1.0.0")]
23 impl<'a, B: ?Sized> Borrow<B> for Cow<'a, B>
26 <B as ToOwned>::Owned: 'a,
28 fn borrow(&self) -> &B {
33 /// A generalization of `Clone` to borrowed data.
35 /// Some types make it possible to go from borrowed to owned, usually by
36 /// implementing the `Clone` trait. But `Clone` works only for going from `&T`
37 /// to `T`. The `ToOwned` trait generalizes `Clone` to construct owned data
38 /// from any borrow of a given type.
39 #[cfg_attr(not(test), rustc_diagnostic_item = "ToOwned")]
40 #[stable(feature = "rust1", since = "1.0.0")]
42 /// The resulting type after obtaining ownership.
43 #[stable(feature = "rust1", since = "1.0.0")]
44 type Owned: Borrow<Self>;
46 /// Creates owned data from borrowed data, usually by cloning.
53 /// let s: &str = "a";
54 /// let ss: String = s.to_owned();
56 /// let v: &[i32] = &[1, 2];
57 /// let vv: Vec<i32> = v.to_owned();
59 #[stable(feature = "rust1", since = "1.0.0")]
60 #[must_use = "cloning is often expensive and is not expected to have side effects"]
61 fn to_owned(&self) -> Self::Owned;
63 /// Uses borrowed data to replace owned data, usually by cloning.
65 /// This is borrow-generalized version of `Clone::clone_from`.
72 /// # #![feature(toowned_clone_into)]
73 /// let mut s: String = String::new();
74 /// "hello".clone_into(&mut s);
76 /// let mut v: Vec<i32> = Vec::new();
77 /// [1, 2][..].clone_into(&mut v);
79 #[unstable(feature = "toowned_clone_into", reason = "recently added", issue = "41263")]
80 fn clone_into(&self, target: &mut Self::Owned) {
81 *target = self.to_owned();
85 #[stable(feature = "rust1", since = "1.0.0")]
91 fn to_owned(&self) -> T {
95 fn clone_into(&self, target: &mut T) {
96 target.clone_from(self);
100 /// A clone-on-write smart pointer.
102 /// The type `Cow` is a smart pointer providing clone-on-write functionality: it
103 /// can enclose and provide immutable access to borrowed data, and clone the
104 /// data lazily when mutation or ownership is required. The type is designed to
105 /// work with general borrowed data via the `Borrow` trait.
107 /// `Cow` implements `Deref`, which means that you can call
108 /// non-mutating methods directly on the data it encloses. If mutation
109 /// is desired, `to_mut` will obtain a mutable reference to an owned
110 /// value, cloning if necessary.
112 /// If you need reference-counting pointers, note that
113 /// [`Rc::make_mut`][crate::rc::Rc::make_mut] and
114 /// [`Arc::make_mut`][crate::sync::Arc::make_mut] can provide clone-on-write
115 /// functionality as well.
120 /// use std::borrow::Cow;
122 /// fn abs_all(input: &mut Cow<[i32]>) {
123 /// for i in 0..input.len() {
124 /// let v = input[i];
126 /// // Clones into a vector if not already owned.
127 /// input.to_mut()[i] = -v;
132 /// // No clone occurs because `input` doesn't need to be mutated.
133 /// let slice = [0, 1, 2];
134 /// let mut input = Cow::from(&slice[..]);
135 /// abs_all(&mut input);
137 /// // Clone occurs because `input` needs to be mutated.
138 /// let slice = [-1, 0, 1];
139 /// let mut input = Cow::from(&slice[..]);
140 /// abs_all(&mut input);
142 /// // No clone occurs because `input` is already owned.
143 /// let mut input = Cow::from(vec![-1, 0, 1]);
144 /// abs_all(&mut input);
147 /// Another example showing how to keep `Cow` in a struct:
150 /// use std::borrow::Cow;
152 /// struct Items<'a, X: 'a> where [X]: ToOwned<Owned = Vec<X>> {
153 /// values: Cow<'a, [X]>,
156 /// impl<'a, X: Clone + 'a> Items<'a, X> where [X]: ToOwned<Owned = Vec<X>> {
157 /// fn new(v: Cow<'a, [X]>) -> Self {
158 /// Items { values: v }
162 /// // Creates a container from borrowed values of a slice
163 /// let readonly = [1, 2];
164 /// let borrowed = Items::new((&readonly[..]).into());
166 /// Items { values: Cow::Borrowed(b) } => println!("borrowed {b:?}"),
167 /// _ => panic!("expect borrowed value"),
170 /// let mut clone_on_write = borrowed;
171 /// // Mutates the data from slice into owned vec and pushes a new value on top
172 /// clone_on_write.values.to_mut().push(3);
173 /// println!("clone_on_write = {:?}", clone_on_write.values);
175 /// // The data was mutated. Let's check it out.
176 /// match clone_on_write {
177 /// Items { values: Cow::Owned(_) } => println!("clone_on_write contains owned data"),
178 /// _ => panic!("expect owned data"),
181 #[stable(feature = "rust1", since = "1.0.0")]
182 #[cfg_attr(not(test), rustc_diagnostic_item = "Cow")]
183 pub enum Cow<'a, B: ?Sized + 'a>
188 #[stable(feature = "rust1", since = "1.0.0")]
189 Borrowed(#[stable(feature = "rust1", since = "1.0.0")] &'a B),
192 #[stable(feature = "rust1", since = "1.0.0")]
193 Owned(#[stable(feature = "rust1", since = "1.0.0")] <B as ToOwned>::Owned),
196 #[stable(feature = "rust1", since = "1.0.0")]
197 impl<B: ?Sized + ToOwned> Clone for Cow<'_, B> {
198 fn clone(&self) -> Self {
200 Borrowed(b) => Borrowed(b),
202 let b: &B = o.borrow();
208 fn clone_from(&mut self, source: &Self) {
209 match (self, source) {
210 (&mut Owned(ref mut dest), &Owned(ref o)) => o.borrow().clone_into(dest),
211 (t, s) => *t = s.clone(),
216 impl<B: ?Sized + ToOwned> Cow<'_, B> {
217 /// Returns true if the data is borrowed, i.e. if `to_mut` would require additional work.
222 /// #![feature(cow_is_borrowed)]
223 /// use std::borrow::Cow;
225 /// let cow = Cow::Borrowed("moo");
226 /// assert!(cow.is_borrowed());
228 /// let bull: Cow<'_, str> = Cow::Owned("...moo?".to_string());
229 /// assert!(!bull.is_borrowed());
231 #[unstable(feature = "cow_is_borrowed", issue = "65143")]
232 #[rustc_const_unstable(feature = "const_cow_is_borrowed", issue = "65143")]
233 pub const fn is_borrowed(&self) -> bool {
240 /// Returns true if the data is owned, i.e. if `to_mut` would be a no-op.
245 /// #![feature(cow_is_borrowed)]
246 /// use std::borrow::Cow;
248 /// let cow: Cow<'_, str> = Cow::Owned("moo".to_string());
249 /// assert!(cow.is_owned());
251 /// let bull = Cow::Borrowed("...moo?");
252 /// assert!(!bull.is_owned());
254 #[unstable(feature = "cow_is_borrowed", issue = "65143")]
255 #[rustc_const_unstable(feature = "const_cow_is_borrowed", issue = "65143")]
256 pub const fn is_owned(&self) -> bool {
260 /// Acquires a mutable reference to the owned form of the data.
262 /// Clones the data if it is not already owned.
267 /// use std::borrow::Cow;
269 /// let mut cow = Cow::Borrowed("foo");
270 /// cow.to_mut().make_ascii_uppercase();
274 /// Cow::Owned(String::from("FOO")) as Cow<str>
277 #[stable(feature = "rust1", since = "1.0.0")]
278 pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned {
280 Borrowed(borrowed) => {
281 *self = Owned(borrowed.to_owned());
283 Borrowed(..) => unreachable!(),
284 Owned(ref mut owned) => owned,
287 Owned(ref mut owned) => owned,
291 /// Extracts the owned data.
293 /// Clones the data if it is not already owned.
297 /// Calling `into_owned` on a `Cow::Borrowed` returns a clone of the borrowed data:
300 /// use std::borrow::Cow;
302 /// let s = "Hello world!";
303 /// let cow = Cow::Borrowed(s);
306 /// cow.into_owned(),
311 /// Calling `into_owned` on a `Cow::Owned` returns the owned data. The data is moved out of the
312 /// `Cow` without being cloned.
315 /// use std::borrow::Cow;
317 /// let s = "Hello world!";
318 /// let cow: Cow<str> = Cow::Owned(String::from(s));
321 /// cow.into_owned(),
325 #[stable(feature = "rust1", since = "1.0.0")]
326 pub fn into_owned(self) -> <B as ToOwned>::Owned {
328 Borrowed(borrowed) => borrowed.to_owned(),
329 Owned(owned) => owned,
334 #[stable(feature = "rust1", since = "1.0.0")]
335 #[rustc_const_unstable(feature = "const_deref", issue = "88955")]
336 impl<B: ?Sized + ToOwned> const Deref for Cow<'_, B>
338 B::Owned: ~const Borrow<B>,
342 fn deref(&self) -> &B {
344 Borrowed(borrowed) => borrowed,
345 Owned(ref owned) => owned.borrow(),
350 #[stable(feature = "rust1", since = "1.0.0")]
351 impl<B: ?Sized> Eq for Cow<'_, B> where B: Eq + ToOwned {}
353 #[stable(feature = "rust1", since = "1.0.0")]
354 impl<B: ?Sized> Ord for Cow<'_, B>
359 fn cmp(&self, other: &Self) -> Ordering {
360 Ord::cmp(&**self, &**other)
364 #[stable(feature = "rust1", since = "1.0.0")]
365 impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, C>> for Cow<'a, B>
367 B: PartialEq<C> + ToOwned,
371 fn eq(&self, other: &Cow<'b, C>) -> bool {
372 PartialEq::eq(&**self, &**other)
376 #[stable(feature = "rust1", since = "1.0.0")]
377 impl<'a, B: ?Sized> PartialOrd for Cow<'a, B>
379 B: PartialOrd + ToOwned,
382 fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering> {
383 PartialOrd::partial_cmp(&**self, &**other)
387 #[stable(feature = "rust1", since = "1.0.0")]
388 impl<B: ?Sized> fmt::Debug for Cow<'_, B>
390 B: fmt::Debug + ToOwned<Owned: fmt::Debug>,
392 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394 Borrowed(ref b) => fmt::Debug::fmt(b, f),
395 Owned(ref o) => fmt::Debug::fmt(o, f),
400 #[stable(feature = "rust1", since = "1.0.0")]
401 impl<B: ?Sized> fmt::Display for Cow<'_, B>
403 B: fmt::Display + ToOwned<Owned: fmt::Display>,
405 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
407 Borrowed(ref b) => fmt::Display::fmt(b, f),
408 Owned(ref o) => fmt::Display::fmt(o, f),
413 #[stable(feature = "default", since = "1.11.0")]
414 impl<B: ?Sized> Default for Cow<'_, B>
416 B: ToOwned<Owned: Default>,
418 /// Creates an owned Cow<'a, B> with the default value for the contained owned value.
419 fn default() -> Self {
420 Owned(<B as ToOwned>::Owned::default())
424 #[stable(feature = "rust1", since = "1.0.0")]
425 impl<B: ?Sized> Hash for Cow<'_, B>
430 fn hash<H: Hasher>(&self, state: &mut H) {
431 Hash::hash(&**self, state)
435 #[stable(feature = "rust1", since = "1.0.0")]
436 impl<T: ?Sized + ToOwned> AsRef<T> for Cow<'_, T> {
437 fn as_ref(&self) -> &T {
442 #[cfg(not(no_global_oom_handling))]
443 #[stable(feature = "cow_add", since = "1.14.0")]
444 impl<'a> Add<&'a str> for Cow<'a, str> {
445 type Output = Cow<'a, str>;
448 fn add(mut self, rhs: &'a str) -> Self::Output {
454 #[cfg(not(no_global_oom_handling))]
455 #[stable(feature = "cow_add", since = "1.14.0")]
456 impl<'a> Add<Cow<'a, str>> for Cow<'a, str> {
457 type Output = Cow<'a, str>;
460 fn add(mut self, rhs: Cow<'a, str>) -> Self::Output {
466 #[cfg(not(no_global_oom_handling))]
467 #[stable(feature = "cow_add", since = "1.14.0")]
468 impl<'a> AddAssign<&'a str> for Cow<'a, str> {
469 fn add_assign(&mut self, rhs: &'a str) {
471 *self = Cow::Borrowed(rhs)
472 } else if !rhs.is_empty() {
473 if let Cow::Borrowed(lhs) = *self {
474 let mut s = String::with_capacity(lhs.len() + rhs.len());
476 *self = Cow::Owned(s);
478 self.to_mut().push_str(rhs);
483 #[cfg(not(no_global_oom_handling))]
484 #[stable(feature = "cow_add", since = "1.14.0")]
485 impl<'a> AddAssign<Cow<'a, str>> for Cow<'a, str> {
486 fn add_assign(&mut self, rhs: Cow<'a, str>) {
489 } else if !rhs.is_empty() {
490 if let Cow::Borrowed(lhs) = *self {
491 let mut s = String::with_capacity(lhs.len() + rhs.len());
493 *self = Cow::Owned(s);
495 self.to_mut().push_str(&rhs);