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>
25 fn borrow(&self) -> &B {
30 /// A generalization of `Clone` to borrowed data.
32 /// Some types make it possible to go from borrowed to owned, usually by
33 /// implementing the `Clone` trait. But `Clone` works only for going from `&T`
34 /// to `T`. The `ToOwned` trait generalizes `Clone` to construct owned data
35 /// from any borrow of a given type.
36 #[cfg_attr(not(test), rustc_diagnostic_item = "ToOwned")]
37 #[stable(feature = "rust1", since = "1.0.0")]
39 /// The resulting type after obtaining ownership.
40 #[stable(feature = "rust1", since = "1.0.0")]
41 type Owned: Borrow<Self>;
43 /// Creates owned data from borrowed data, usually by cloning.
50 /// let s: &str = "a";
51 /// let ss: String = s.to_owned();
53 /// let v: &[i32] = &[1, 2];
54 /// let vv: Vec<i32> = v.to_owned();
56 #[stable(feature = "rust1", since = "1.0.0")]
57 #[must_use = "cloning is often expensive and is not expected to have side effects"]
58 fn to_owned(&self) -> Self::Owned;
60 /// Uses borrowed data to replace owned data, usually by cloning.
62 /// This is borrow-generalized version of [`Clone::clone_from`].
69 /// let mut s: String = String::new();
70 /// "hello".clone_into(&mut s);
72 /// let mut v: Vec<i32> = Vec::new();
73 /// [1, 2][..].clone_into(&mut v);
75 #[stable(feature = "toowned_clone_into", since = "1.63.0")]
76 fn clone_into(&self, target: &mut Self::Owned) {
77 *target = self.to_owned();
81 #[stable(feature = "rust1", since = "1.0.0")]
87 fn to_owned(&self) -> T {
91 fn clone_into(&self, target: &mut T) {
92 target.clone_from(self);
96 /// A clone-on-write smart pointer.
98 /// The type `Cow` is a smart pointer providing clone-on-write functionality: it
99 /// can enclose and provide immutable access to borrowed data, and clone the
100 /// data lazily when mutation or ownership is required. The type is designed to
101 /// work with general borrowed data via the `Borrow` trait.
103 /// `Cow` implements `Deref`, which means that you can call
104 /// non-mutating methods directly on the data it encloses. If mutation
105 /// is desired, `to_mut` will obtain a mutable reference to an owned
106 /// value, cloning if necessary.
108 /// If you need reference-counting pointers, note that
109 /// [`Rc::make_mut`][crate::rc::Rc::make_mut] and
110 /// [`Arc::make_mut`][crate::sync::Arc::make_mut] can provide clone-on-write
111 /// functionality as well.
116 /// use std::borrow::Cow;
118 /// fn abs_all(input: &mut Cow<[i32]>) {
119 /// for i in 0..input.len() {
120 /// let v = input[i];
122 /// // Clones into a vector if not already owned.
123 /// input.to_mut()[i] = -v;
128 /// // No clone occurs because `input` doesn't need to be mutated.
129 /// let slice = [0, 1, 2];
130 /// let mut input = Cow::from(&slice[..]);
131 /// abs_all(&mut input);
133 /// // Clone occurs because `input` needs to be mutated.
134 /// let slice = [-1, 0, 1];
135 /// let mut input = Cow::from(&slice[..]);
136 /// abs_all(&mut input);
138 /// // No clone occurs because `input` is already owned.
139 /// let mut input = Cow::from(vec![-1, 0, 1]);
140 /// abs_all(&mut input);
143 /// Another example showing how to keep `Cow` in a struct:
146 /// use std::borrow::Cow;
148 /// struct Items<'a, X: 'a> where [X]: ToOwned<Owned = Vec<X>> {
149 /// values: Cow<'a, [X]>,
152 /// impl<'a, X: Clone + 'a> Items<'a, X> where [X]: ToOwned<Owned = Vec<X>> {
153 /// fn new(v: Cow<'a, [X]>) -> Self {
154 /// Items { values: v }
158 /// // Creates a container from borrowed values of a slice
159 /// let readonly = [1, 2];
160 /// let borrowed = Items::new((&readonly[..]).into());
162 /// Items { values: Cow::Borrowed(b) } => println!("borrowed {b:?}"),
163 /// _ => panic!("expect borrowed value"),
166 /// let mut clone_on_write = borrowed;
167 /// // Mutates the data from slice into owned vec and pushes a new value on top
168 /// clone_on_write.values.to_mut().push(3);
169 /// println!("clone_on_write = {:?}", clone_on_write.values);
171 /// // The data was mutated. Let's check it out.
172 /// match clone_on_write {
173 /// Items { values: Cow::Owned(_) } => println!("clone_on_write contains owned data"),
174 /// _ => panic!("expect owned data"),
177 #[stable(feature = "rust1", since = "1.0.0")]
178 #[cfg_attr(not(test), rustc_diagnostic_item = "Cow")]
179 pub enum Cow<'a, B: ?Sized + 'a>
184 #[stable(feature = "rust1", since = "1.0.0")]
185 Borrowed(#[stable(feature = "rust1", since = "1.0.0")] &'a B),
188 #[stable(feature = "rust1", since = "1.0.0")]
189 Owned(#[stable(feature = "rust1", since = "1.0.0")] <B as ToOwned>::Owned),
192 #[stable(feature = "rust1", since = "1.0.0")]
193 impl<B: ?Sized + ToOwned> Clone for Cow<'_, B> {
194 fn clone(&self) -> Self {
196 Borrowed(b) => Borrowed(b),
198 let b: &B = o.borrow();
204 fn clone_from(&mut self, source: &Self) {
205 match (self, source) {
206 (&mut Owned(ref mut dest), &Owned(ref o)) => o.borrow().clone_into(dest),
207 (t, s) => *t = s.clone(),
212 impl<B: ?Sized + ToOwned> Cow<'_, B> {
213 /// Returns true if the data is borrowed, i.e. if `to_mut` would require additional work.
218 /// #![feature(cow_is_borrowed)]
219 /// use std::borrow::Cow;
221 /// let cow = Cow::Borrowed("moo");
222 /// assert!(cow.is_borrowed());
224 /// let bull: Cow<'_, str> = Cow::Owned("...moo?".to_string());
225 /// assert!(!bull.is_borrowed());
227 #[unstable(feature = "cow_is_borrowed", issue = "65143")]
228 #[rustc_const_unstable(feature = "const_cow_is_borrowed", issue = "65143")]
229 pub const fn is_borrowed(&self) -> bool {
236 /// Returns true if the data is owned, i.e. if `to_mut` would be a no-op.
241 /// #![feature(cow_is_borrowed)]
242 /// use std::borrow::Cow;
244 /// let cow: Cow<'_, str> = Cow::Owned("moo".to_string());
245 /// assert!(cow.is_owned());
247 /// let bull = Cow::Borrowed("...moo?");
248 /// assert!(!bull.is_owned());
250 #[unstable(feature = "cow_is_borrowed", issue = "65143")]
251 #[rustc_const_unstable(feature = "const_cow_is_borrowed", issue = "65143")]
252 pub const fn is_owned(&self) -> bool {
256 /// Acquires a mutable reference to the owned form of the data.
258 /// Clones the data if it is not already owned.
263 /// use std::borrow::Cow;
265 /// let mut cow = Cow::Borrowed("foo");
266 /// cow.to_mut().make_ascii_uppercase();
270 /// Cow::Owned(String::from("FOO")) as Cow<str>
273 #[stable(feature = "rust1", since = "1.0.0")]
274 pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned {
276 Borrowed(borrowed) => {
277 *self = Owned(borrowed.to_owned());
279 Borrowed(..) => unreachable!(),
280 Owned(ref mut owned) => owned,
283 Owned(ref mut owned) => owned,
287 /// Extracts the owned data.
289 /// Clones the data if it is not already owned.
293 /// Calling `into_owned` on a `Cow::Borrowed` returns a clone of the borrowed data:
296 /// use std::borrow::Cow;
298 /// let s = "Hello world!";
299 /// let cow = Cow::Borrowed(s);
302 /// cow.into_owned(),
307 /// Calling `into_owned` on a `Cow::Owned` returns the owned data. The data is moved out of the
308 /// `Cow` without being cloned.
311 /// use std::borrow::Cow;
313 /// let s = "Hello world!";
314 /// let cow: Cow<str> = Cow::Owned(String::from(s));
317 /// cow.into_owned(),
321 #[stable(feature = "rust1", since = "1.0.0")]
322 pub fn into_owned(self) -> <B as ToOwned>::Owned {
324 Borrowed(borrowed) => borrowed.to_owned(),
325 Owned(owned) => owned,
330 #[stable(feature = "rust1", since = "1.0.0")]
331 #[rustc_const_unstable(feature = "const_deref", issue = "88955")]
332 impl<B: ?Sized + ToOwned> const Deref for Cow<'_, B>
334 B::Owned: ~const Borrow<B>,
338 fn deref(&self) -> &B {
340 Borrowed(borrowed) => borrowed,
341 Owned(ref owned) => owned.borrow(),
346 #[stable(feature = "rust1", since = "1.0.0")]
347 impl<B: ?Sized> Eq for Cow<'_, B> where B: Eq + ToOwned {}
349 #[stable(feature = "rust1", since = "1.0.0")]
350 impl<B: ?Sized> Ord for Cow<'_, B>
355 fn cmp(&self, other: &Self) -> Ordering {
356 Ord::cmp(&**self, &**other)
360 #[stable(feature = "rust1", since = "1.0.0")]
361 impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, C>> for Cow<'a, B>
363 B: PartialEq<C> + ToOwned,
367 fn eq(&self, other: &Cow<'b, C>) -> bool {
368 PartialEq::eq(&**self, &**other)
372 #[stable(feature = "rust1", since = "1.0.0")]
373 impl<'a, B: ?Sized> PartialOrd for Cow<'a, B>
375 B: PartialOrd + ToOwned,
378 fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering> {
379 PartialOrd::partial_cmp(&**self, &**other)
383 #[stable(feature = "rust1", since = "1.0.0")]
384 impl<B: ?Sized> fmt::Debug for Cow<'_, B>
386 B: fmt::Debug + ToOwned<Owned: fmt::Debug>,
388 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
390 Borrowed(ref b) => fmt::Debug::fmt(b, f),
391 Owned(ref o) => fmt::Debug::fmt(o, f),
396 #[stable(feature = "rust1", since = "1.0.0")]
397 impl<B: ?Sized> fmt::Display for Cow<'_, B>
399 B: fmt::Display + ToOwned<Owned: fmt::Display>,
401 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
403 Borrowed(ref b) => fmt::Display::fmt(b, f),
404 Owned(ref o) => fmt::Display::fmt(o, f),
409 #[stable(feature = "default", since = "1.11.0")]
410 impl<B: ?Sized> Default for Cow<'_, B>
412 B: ToOwned<Owned: Default>,
414 /// Creates an owned Cow<'a, B> with the default value for the contained owned value.
415 fn default() -> Self {
416 Owned(<B as ToOwned>::Owned::default())
420 #[stable(feature = "rust1", since = "1.0.0")]
421 impl<B: ?Sized> Hash for Cow<'_, B>
426 fn hash<H: Hasher>(&self, state: &mut H) {
427 Hash::hash(&**self, state)
431 #[stable(feature = "rust1", since = "1.0.0")]
432 impl<T: ?Sized + ToOwned> AsRef<T> for Cow<'_, T> {
433 fn as_ref(&self) -> &T {
438 #[cfg(not(no_global_oom_handling))]
439 #[stable(feature = "cow_add", since = "1.14.0")]
440 impl<'a> Add<&'a str> for Cow<'a, str> {
441 type Output = Cow<'a, str>;
444 fn add(mut self, rhs: &'a str) -> Self::Output {
450 #[cfg(not(no_global_oom_handling))]
451 #[stable(feature = "cow_add", since = "1.14.0")]
452 impl<'a> Add<Cow<'a, str>> for Cow<'a, str> {
453 type Output = Cow<'a, str>;
456 fn add(mut self, rhs: Cow<'a, str>) -> Self::Output {
462 #[cfg(not(no_global_oom_handling))]
463 #[stable(feature = "cow_add", since = "1.14.0")]
464 impl<'a> AddAssign<&'a str> for Cow<'a, str> {
465 fn add_assign(&mut self, rhs: &'a str) {
467 *self = Cow::Borrowed(rhs)
468 } else if !rhs.is_empty() {
469 if let Cow::Borrowed(lhs) = *self {
470 let mut s = String::with_capacity(lhs.len() + rhs.len());
472 *self = Cow::Owned(s);
474 self.to_mut().push_str(rhs);
479 #[cfg(not(no_global_oom_handling))]
480 #[stable(feature = "cow_add", since = "1.14.0")]
481 impl<'a> AddAssign<Cow<'a, str>> for Cow<'a, str> {
482 fn add_assign(&mut self, rhs: Cow<'a, str>) {
485 } else if !rhs.is_empty() {
486 if let Cow::Borrowed(lhs) = *self {
487 let mut s = String::with_capacity(lhs.len() + rhs.len());
489 *self = Cow::Owned(s);
491 self.to_mut().push_str(&rhs);