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};
7 use core::ops::{Add, AddAssign, Deref};
9 #[stable(feature = "rust1", since = "1.0.0")]
10 pub use core::borrow::{Borrow, BorrowMut};
13 use crate::string::String;
17 #[stable(feature = "rust1", since = "1.0.0")]
18 impl<'a, B: ?Sized> Borrow<B> for Cow<'a, B>
21 <B as ToOwned>::Owned: 'a,
23 fn borrow(&self) -> &B {
28 /// A generalization of `Clone` to borrowed data.
30 /// Some types make it possible to go from borrowed to owned, usually by
31 /// implementing the `Clone` trait. But `Clone` works only for going from `&T`
32 /// to `T`. The `ToOwned` trait generalizes `Clone` to construct owned data
33 /// from any borrow of a given type.
34 #[stable(feature = "rust1", since = "1.0.0")]
36 /// The resulting type after obtaining ownership.
37 #[stable(feature = "rust1", since = "1.0.0")]
38 type Owned: Borrow<Self>;
40 /// Creates owned data from borrowed data, usually by cloning.
47 /// let s: &str = "a";
48 /// let ss: String = s.to_owned();
50 /// let v: &[i32] = &[1, 2];
51 /// let vv: Vec<i32> = v.to_owned();
53 #[stable(feature = "rust1", since = "1.0.0")]
54 #[must_use = "cloning is often expensive and is not expected to have side effects"]
55 fn to_owned(&self) -> Self::Owned;
57 /// Uses borrowed data to replace owned data, usually by cloning.
59 /// This is borrow-generalized version of `Clone::clone_from`.
66 /// # #![feature(toowned_clone_into)]
67 /// let mut s: String = String::new();
68 /// "hello".clone_into(&mut s);
70 /// let mut v: Vec<i32> = Vec::new();
71 /// [1, 2][..].clone_into(&mut v);
73 #[unstable(feature = "toowned_clone_into", reason = "recently added", issue = "41263")]
74 fn clone_into(&self, target: &mut Self::Owned) {
75 *target = self.to_owned();
79 #[stable(feature = "rust1", since = "1.0.0")]
85 fn to_owned(&self) -> T {
89 fn clone_into(&self, target: &mut T) {
90 target.clone_from(self);
94 /// A clone-on-write smart pointer.
96 /// The type `Cow` is a smart pointer providing clone-on-write functionality: it
97 /// can enclose and provide immutable access to borrowed data, and clone the
98 /// data lazily when mutation or ownership is required. The type is designed to
99 /// work with general borrowed data via the `Borrow` trait.
101 /// `Cow` implements `Deref`, which means that you can call
102 /// non-mutating methods directly on the data it encloses. If mutation
103 /// is desired, `to_mut` will obtain a mutable reference to an owned
104 /// value, cloning if necessary.
106 /// If you need reference-counting pointers, note that
107 /// [`Rc::make_mut`][crate::rc::Rc::make_mut] and
108 /// [`Arc::make_mut`][crate::sync::Arc::make_mut] can provide clone-on-write
109 /// functionality as well.
114 /// use std::borrow::Cow;
116 /// fn abs_all(input: &mut Cow<[i32]>) {
117 /// for i in 0..input.len() {
118 /// let v = input[i];
120 /// // Clones into a vector if not already owned.
121 /// input.to_mut()[i] = -v;
126 /// // No clone occurs because `input` doesn't need to be mutated.
127 /// let slice = [0, 1, 2];
128 /// let mut input = Cow::from(&slice[..]);
129 /// abs_all(&mut input);
131 /// // Clone occurs because `input` needs to be mutated.
132 /// let slice = [-1, 0, 1];
133 /// let mut input = Cow::from(&slice[..]);
134 /// abs_all(&mut input);
136 /// // No clone occurs because `input` is already owned.
137 /// let mut input = Cow::from(vec![-1, 0, 1]);
138 /// abs_all(&mut input);
141 /// Another example showing how to keep `Cow` in a struct:
144 /// use std::borrow::Cow;
146 /// struct Items<'a, X: 'a> where [X]: ToOwned<Owned = Vec<X>> {
147 /// values: Cow<'a, [X]>,
150 /// impl<'a, X: Clone + 'a> Items<'a, X> where [X]: ToOwned<Owned = Vec<X>> {
151 /// fn new(v: Cow<'a, [X]>) -> Self {
152 /// Items { values: v }
156 /// // Creates a container from borrowed values of a slice
157 /// let readonly = [1, 2];
158 /// let borrowed = Items::new((&readonly[..]).into());
160 /// Items { values: Cow::Borrowed(b) } => println!("borrowed {:?}", b),
161 /// _ => panic!("expect borrowed value"),
164 /// let mut clone_on_write = borrowed;
165 /// // Mutates the data from slice into owned vec and pushes a new value on top
166 /// clone_on_write.values.to_mut().push(3);
167 /// println!("clone_on_write = {:?}", clone_on_write.values);
169 /// // The data was mutated. Let check it out.
170 /// match clone_on_write {
171 /// Items { values: Cow::Owned(_) } => println!("clone_on_write contains owned data"),
172 /// _ => panic!("expect owned data"),
175 #[stable(feature = "rust1", since = "1.0.0")]
176 pub enum Cow<'a, B: ?Sized + 'a>
181 #[stable(feature = "rust1", since = "1.0.0")]
182 Borrowed(#[stable(feature = "rust1", since = "1.0.0")] &'a B),
185 #[stable(feature = "rust1", since = "1.0.0")]
186 Owned(#[stable(feature = "rust1", since = "1.0.0")] <B as ToOwned>::Owned),
189 #[stable(feature = "rust1", since = "1.0.0")]
190 impl<B: ?Sized + ToOwned> Clone for Cow<'_, B> {
191 fn clone(&self) -> Self {
193 Borrowed(b) => Borrowed(b),
195 let b: &B = o.borrow();
201 fn clone_from(&mut self, source: &Self) {
202 match (self, source) {
203 (&mut Owned(ref mut dest), &Owned(ref o)) => o.borrow().clone_into(dest),
204 (t, s) => *t = s.clone(),
209 impl<B: ?Sized + ToOwned> Cow<'_, B> {
210 /// Returns true if the data is borrowed, i.e. if `to_mut` would require additional work.
215 /// #![feature(cow_is_borrowed)]
216 /// use std::borrow::Cow;
218 /// let cow = Cow::Borrowed("moo");
219 /// assert!(cow.is_borrowed());
221 /// let bull: Cow<'_, str> = Cow::Owned("...moo?".to_string());
222 /// assert!(!bull.is_borrowed());
224 #[unstable(feature = "cow_is_borrowed", issue = "65143")]
225 #[rustc_const_unstable(feature = "const_cow_is_borrowed", issue = "65143")]
226 pub const fn is_borrowed(&self) -> bool {
233 /// Returns true if the data is owned, i.e. if `to_mut` would be a no-op.
238 /// #![feature(cow_is_borrowed)]
239 /// use std::borrow::Cow;
241 /// let cow: Cow<'_, str> = Cow::Owned("moo".to_string());
242 /// assert!(cow.is_owned());
244 /// let bull = Cow::Borrowed("...moo?");
245 /// assert!(!bull.is_owned());
247 #[unstable(feature = "cow_is_borrowed", issue = "65143")]
248 #[rustc_const_unstable(feature = "const_cow_is_borrowed", issue = "65143")]
249 pub const fn is_owned(&self) -> bool {
253 /// Acquires a mutable reference to the owned form of the data.
255 /// Clones the data if it is not already owned.
260 /// use std::borrow::Cow;
262 /// let mut cow = Cow::Borrowed("foo");
263 /// cow.to_mut().make_ascii_uppercase();
267 /// Cow::Owned(String::from("FOO")) as Cow<str>
270 #[stable(feature = "rust1", since = "1.0.0")]
271 pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned {
273 Borrowed(borrowed) => {
274 *self = Owned(borrowed.to_owned());
276 Borrowed(..) => unreachable!(),
277 Owned(ref mut owned) => owned,
280 Owned(ref mut owned) => owned,
284 /// Extracts the owned data.
286 /// Clones the data if it is not already owned.
290 /// Calling `into_owned` on a `Cow::Borrowed` clones the underlying data
291 /// and becomes a `Cow::Owned`:
294 /// use std::borrow::Cow;
296 /// let s = "Hello world!";
297 /// let cow = Cow::Borrowed(s);
300 /// cow.into_owned(),
305 /// Calling `into_owned` on a `Cow::Owned` is a no-op:
308 /// use std::borrow::Cow;
310 /// let s = "Hello world!";
311 /// let cow: Cow<str> = Cow::Owned(String::from(s));
314 /// cow.into_owned(),
318 #[stable(feature = "rust1", since = "1.0.0")]
319 pub fn into_owned(self) -> <B as ToOwned>::Owned {
321 Borrowed(borrowed) => borrowed.to_owned(),
322 Owned(owned) => owned,
327 #[stable(feature = "rust1", since = "1.0.0")]
328 impl<B: ?Sized + ToOwned> Deref for Cow<'_, B> {
331 fn deref(&self) -> &B {
333 Borrowed(borrowed) => borrowed,
334 Owned(ref owned) => owned.borrow(),
339 #[stable(feature = "rust1", since = "1.0.0")]
340 impl<B: ?Sized> Eq for Cow<'_, B> where B: Eq + ToOwned {}
342 #[stable(feature = "rust1", since = "1.0.0")]
343 impl<B: ?Sized> Ord for Cow<'_, B>
348 fn cmp(&self, other: &Self) -> Ordering {
349 Ord::cmp(&**self, &**other)
353 #[stable(feature = "rust1", since = "1.0.0")]
354 impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, C>> for Cow<'a, B>
356 B: PartialEq<C> + ToOwned,
360 fn eq(&self, other: &Cow<'b, C>) -> bool {
361 PartialEq::eq(&**self, &**other)
365 #[stable(feature = "rust1", since = "1.0.0")]
366 impl<'a, B: ?Sized> PartialOrd for Cow<'a, B>
368 B: PartialOrd + ToOwned,
371 fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering> {
372 PartialOrd::partial_cmp(&**self, &**other)
376 #[stable(feature = "rust1", since = "1.0.0")]
377 impl<B: ?Sized> fmt::Debug for Cow<'_, B>
379 B: fmt::Debug + ToOwned<Owned: fmt::Debug>,
381 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383 Borrowed(ref b) => fmt::Debug::fmt(b, f),
384 Owned(ref o) => fmt::Debug::fmt(o, f),
389 #[stable(feature = "rust1", since = "1.0.0")]
390 impl<B: ?Sized> fmt::Display for Cow<'_, B>
392 B: fmt::Display + ToOwned<Owned: fmt::Display>,
394 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
396 Borrowed(ref b) => fmt::Display::fmt(b, f),
397 Owned(ref o) => fmt::Display::fmt(o, f),
402 #[stable(feature = "default", since = "1.11.0")]
403 impl<B: ?Sized> Default for Cow<'_, B>
405 B: ToOwned<Owned: Default>,
407 /// Creates an owned Cow<'a, B> with the default value for the contained owned value.
408 fn default() -> Self {
409 Owned(<B as ToOwned>::Owned::default())
413 #[stable(feature = "rust1", since = "1.0.0")]
414 impl<B: ?Sized> Hash for Cow<'_, B>
419 fn hash<H: Hasher>(&self, state: &mut H) {
420 Hash::hash(&**self, state)
424 #[stable(feature = "rust1", since = "1.0.0")]
425 impl<T: ?Sized + ToOwned> AsRef<T> for Cow<'_, T> {
426 fn as_ref(&self) -> &T {
431 #[stable(feature = "cow_add", since = "1.14.0")]
432 impl<'a> Add<&'a str> for Cow<'a, str> {
433 type Output = Cow<'a, str>;
436 fn add(mut self, rhs: &'a str) -> Self::Output {
442 #[stable(feature = "cow_add", since = "1.14.0")]
443 impl<'a> Add<Cow<'a, str>> for Cow<'a, str> {
444 type Output = Cow<'a, str>;
447 fn add(mut self, rhs: Cow<'a, str>) -> Self::Output {
453 #[stable(feature = "cow_add", since = "1.14.0")]
454 impl<'a> AddAssign<&'a str> for Cow<'a, str> {
455 fn add_assign(&mut self, rhs: &'a str) {
457 *self = Cow::Borrowed(rhs)
458 } else if !rhs.is_empty() {
459 if let Cow::Borrowed(lhs) = *self {
460 let mut s = String::with_capacity(lhs.len() + rhs.len());
462 *self = Cow::Owned(s);
464 self.to_mut().push_str(rhs);
469 #[stable(feature = "cow_add", since = "1.14.0")]
470 impl<'a> AddAssign<Cow<'a, str>> for Cow<'a, str> {
471 fn add_assign(&mut self, rhs: Cow<'a, str>) {
474 } else if !rhs.is_empty() {
475 if let Cow::Borrowed(lhs) = *self {
476 let mut s = String::with_capacity(lhs.len() + rhs.len());
478 *self = Cow::Owned(s);
480 self.to_mut().push_str(&rhs);