1 // SPDX-License-Identifier: Apache-2.0 OR MIT
2 
3 //! A module for working with borrowed data.
4 
5 #![stable(feature = "rust1", since = "1.0.0")]
6 
7 use core::cmp::Ordering;
8 use core::hash::{Hash, Hasher};
9 use core::ops::Deref;
10 #[cfg(not(no_global_oom_handling))]
11 use core::ops::{Add, AddAssign};
12 
13 #[stable(feature = "rust1", since = "1.0.0")]
14 pub use core::borrow::{Borrow, BorrowMut};
15 
16 use core::fmt;
17 #[cfg(not(no_global_oom_handling))]
18 use crate::string::String;
19 
20 use Cow::*;
21 
22 #[stable(feature = "rust1", since = "1.0.0")]
23 impl<'a, B: ?Sized> Borrow<B> for Cow<'a, B>
24 where
25     B: ToOwned,
26     <B as ToOwned>::Owned: 'a,
27 {
borrow(&self) -> &B28     fn borrow(&self) -> &B {
29         &**self
30     }
31 }
32 
33 /// A generalization of `Clone` to borrowed data.
34 ///
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")]
41 pub trait ToOwned {
42     /// The resulting type after obtaining ownership.
43     #[stable(feature = "rust1", since = "1.0.0")]
44     type Owned: Borrow<Self>;
45 
46     /// Creates owned data from borrowed data, usually by cloning.
47     ///
48     /// # Examples
49     ///
50     /// Basic usage:
51     ///
52     /// ```
53     /// let s: &str = "a";
54     /// let ss: String = s.to_owned();
55     ///
56     /// let v: &[i32] = &[1, 2];
57     /// let vv: Vec<i32> = v.to_owned();
58     /// ```
59     #[stable(feature = "rust1", since = "1.0.0")]
60     #[must_use = "cloning is often expensive and is not expected to have side effects"]
to_owned(&self) -> Self::Owned61     fn to_owned(&self) -> Self::Owned;
62 
63     /// Uses borrowed data to replace owned data, usually by cloning.
64     ///
65     /// This is borrow-generalized version of `Clone::clone_from`.
66     ///
67     /// # Examples
68     ///
69     /// Basic usage:
70     ///
71     /// ```
72     /// # #![feature(toowned_clone_into)]
73     /// let mut s: String = String::new();
74     /// "hello".clone_into(&mut s);
75     ///
76     /// let mut v: Vec<i32> = Vec::new();
77     /// [1, 2][..].clone_into(&mut v);
78     /// ```
79     #[unstable(feature = "toowned_clone_into", reason = "recently added", issue = "41263")]
clone_into(&self, target: &mut Self::Owned)80     fn clone_into(&self, target: &mut Self::Owned) {
81         *target = self.to_owned();
82     }
83 }
84 
85 #[stable(feature = "rust1", since = "1.0.0")]
86 impl<T> ToOwned for T
87 where
88     T: Clone,
89 {
90     type Owned = T;
to_owned(&self) -> T91     fn to_owned(&self) -> T {
92         self.clone()
93     }
94 
clone_into(&self, target: &mut T)95     fn clone_into(&self, target: &mut T) {
96         target.clone_from(self);
97     }
98 }
99 
100 /// A clone-on-write smart pointer.
101 ///
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.
106 ///
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.
111 ///
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.
116 ///
117 /// # Examples
118 ///
119 /// ```
120 /// use std::borrow::Cow;
121 ///
122 /// fn abs_all(input: &mut Cow<[i32]>) {
123 ///     for i in 0..input.len() {
124 ///         let v = input[i];
125 ///         if v < 0 {
126 ///             // Clones into a vector if not already owned.
127 ///             input.to_mut()[i] = -v;
128 ///         }
129 ///     }
130 /// }
131 ///
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);
136 ///
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);
141 ///
142 /// // No clone occurs because `input` is already owned.
143 /// let mut input = Cow::from(vec![-1, 0, 1]);
144 /// abs_all(&mut input);
145 /// ```
146 ///
147 /// Another example showing how to keep `Cow` in a struct:
148 ///
149 /// ```
150 /// use std::borrow::Cow;
151 ///
152 /// struct Items<'a, X: 'a> where [X]: ToOwned<Owned = Vec<X>> {
153 ///     values: Cow<'a, [X]>,
154 /// }
155 ///
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 }
159 ///     }
160 /// }
161 ///
162 /// // Creates a container from borrowed values of a slice
163 /// let readonly = [1, 2];
164 /// let borrowed = Items::new((&readonly[..]).into());
165 /// match borrowed {
166 ///     Items { values: Cow::Borrowed(b) } => println!("borrowed {b:?}"),
167 ///     _ => panic!("expect borrowed value"),
168 /// }
169 ///
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);
174 ///
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"),
179 /// }
180 /// ```
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>
184 where
185     B: ToOwned,
186 {
187     /// Borrowed data.
188     #[stable(feature = "rust1", since = "1.0.0")]
189     Borrowed(#[stable(feature = "rust1", since = "1.0.0")] &'a B),
190 
191     /// Owned data.
192     #[stable(feature = "rust1", since = "1.0.0")]
193     Owned(#[stable(feature = "rust1", since = "1.0.0")] <B as ToOwned>::Owned),
194 }
195 
196 #[stable(feature = "rust1", since = "1.0.0")]
197 impl<B: ?Sized + ToOwned> Clone for Cow<'_, B> {
clone(&self) -> Self198     fn clone(&self) -> Self {
199         match *self {
200             Borrowed(b) => Borrowed(b),
201             Owned(ref o) => {
202                 let b: &B = o.borrow();
203                 Owned(b.to_owned())
204             }
205         }
206     }
207 
clone_from(&mut self, source: &Self)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(),
212         }
213     }
214 }
215 
216 impl<B: ?Sized + ToOwned> Cow<'_, B> {
217     /// Returns true if the data is borrowed, i.e. if `to_mut` would require additional work.
218     ///
219     /// # Examples
220     ///
221     /// ```
222     /// #![feature(cow_is_borrowed)]
223     /// use std::borrow::Cow;
224     ///
225     /// let cow = Cow::Borrowed("moo");
226     /// assert!(cow.is_borrowed());
227     ///
228     /// let bull: Cow<'_, str> = Cow::Owned("...moo?".to_string());
229     /// assert!(!bull.is_borrowed());
230     /// ```
231     #[unstable(feature = "cow_is_borrowed", issue = "65143")]
232     #[rustc_const_unstable(feature = "const_cow_is_borrowed", issue = "65143")]
is_borrowed(&self) -> bool233     pub const fn is_borrowed(&self) -> bool {
234         match *self {
235             Borrowed(_) => true,
236             Owned(_) => false,
237         }
238     }
239 
240     /// Returns true if the data is owned, i.e. if `to_mut` would be a no-op.
241     ///
242     /// # Examples
243     ///
244     /// ```
245     /// #![feature(cow_is_borrowed)]
246     /// use std::borrow::Cow;
247     ///
248     /// let cow: Cow<'_, str> = Cow::Owned("moo".to_string());
249     /// assert!(cow.is_owned());
250     ///
251     /// let bull = Cow::Borrowed("...moo?");
252     /// assert!(!bull.is_owned());
253     /// ```
254     #[unstable(feature = "cow_is_borrowed", issue = "65143")]
255     #[rustc_const_unstable(feature = "const_cow_is_borrowed", issue = "65143")]
is_owned(&self) -> bool256     pub const fn is_owned(&self) -> bool {
257         !self.is_borrowed()
258     }
259 
260     /// Acquires a mutable reference to the owned form of the data.
261     ///
262     /// Clones the data if it is not already owned.
263     ///
264     /// # Examples
265     ///
266     /// ```
267     /// use std::borrow::Cow;
268     ///
269     /// let mut cow = Cow::Borrowed("foo");
270     /// cow.to_mut().make_ascii_uppercase();
271     ///
272     /// assert_eq!(
273     ///   cow,
274     ///   Cow::Owned(String::from("FOO")) as Cow<str>
275     /// );
276     /// ```
277     #[stable(feature = "rust1", since = "1.0.0")]
to_mut(&mut self) -> &mut <B as ToOwned>::Owned278     pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned {
279         match *self {
280             Borrowed(borrowed) => {
281                 *self = Owned(borrowed.to_owned());
282                 match *self {
283                     Borrowed(..) => unreachable!(),
284                     Owned(ref mut owned) => owned,
285                 }
286             }
287             Owned(ref mut owned) => owned,
288         }
289     }
290 
291     /// Extracts the owned data.
292     ///
293     /// Clones the data if it is not already owned.
294     ///
295     /// # Examples
296     ///
297     /// Calling `into_owned` on a `Cow::Borrowed` returns a clone of the borrowed data:
298     ///
299     /// ```
300     /// use std::borrow::Cow;
301     ///
302     /// let s = "Hello world!";
303     /// let cow = Cow::Borrowed(s);
304     ///
305     /// assert_eq!(
306     ///   cow.into_owned(),
307     ///   String::from(s)
308     /// );
309     /// ```
310     ///
311     /// Calling `into_owned` on a `Cow::Owned` returns the owned data. The data is moved out of the
312     /// `Cow` without being cloned.
313     ///
314     /// ```
315     /// use std::borrow::Cow;
316     ///
317     /// let s = "Hello world!";
318     /// let cow: Cow<str> = Cow::Owned(String::from(s));
319     ///
320     /// assert_eq!(
321     ///   cow.into_owned(),
322     ///   String::from(s)
323     /// );
324     /// ```
325     #[stable(feature = "rust1", since = "1.0.0")]
into_owned(self) -> <B as ToOwned>::Owned326     pub fn into_owned(self) -> <B as ToOwned>::Owned {
327         match self {
328             Borrowed(borrowed) => borrowed.to_owned(),
329             Owned(owned) => owned,
330         }
331     }
332 }
333 
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>
337 where
338     B::Owned: ~const Borrow<B>,
339 {
340     type Target = B;
341 
deref(&self) -> &B342     fn deref(&self) -> &B {
343         match *self {
344             Borrowed(borrowed) => borrowed,
345             Owned(ref owned) => owned.borrow(),
346         }
347     }
348 }
349 
350 #[stable(feature = "rust1", since = "1.0.0")]
351 impl<B: ?Sized> Eq for Cow<'_, B> where B: Eq + ToOwned {}
352 
353 #[stable(feature = "rust1", since = "1.0.0")]
354 impl<B: ?Sized> Ord for Cow<'_, B>
355 where
356     B: Ord + ToOwned,
357 {
358     #[inline]
cmp(&self, other: &Self) -> Ordering359     fn cmp(&self, other: &Self) -> Ordering {
360         Ord::cmp(&**self, &**other)
361     }
362 }
363 
364 #[stable(feature = "rust1", since = "1.0.0")]
365 impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, C>> for Cow<'a, B>
366 where
367     B: PartialEq<C> + ToOwned,
368     C: ToOwned,
369 {
370     #[inline]
eq(&self, other: &Cow<'b, C>) -> bool371     fn eq(&self, other: &Cow<'b, C>) -> bool {
372         PartialEq::eq(&**self, &**other)
373     }
374 }
375 
376 #[stable(feature = "rust1", since = "1.0.0")]
377 impl<'a, B: ?Sized> PartialOrd for Cow<'a, B>
378 where
379     B: PartialOrd + ToOwned,
380 {
381     #[inline]
partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering>382     fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering> {
383         PartialOrd::partial_cmp(&**self, &**other)
384     }
385 }
386 
387 #[stable(feature = "rust1", since = "1.0.0")]
388 impl<B: ?Sized> fmt::Debug for Cow<'_, B>
389 where
390     B: fmt::Debug + ToOwned<Owned: fmt::Debug>,
391 {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result392     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393         match *self {
394             Borrowed(ref b) => fmt::Debug::fmt(b, f),
395             Owned(ref o) => fmt::Debug::fmt(o, f),
396         }
397     }
398 }
399 
400 #[stable(feature = "rust1", since = "1.0.0")]
401 impl<B: ?Sized> fmt::Display for Cow<'_, B>
402 where
403     B: fmt::Display + ToOwned<Owned: fmt::Display>,
404 {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result405     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406         match *self {
407             Borrowed(ref b) => fmt::Display::fmt(b, f),
408             Owned(ref o) => fmt::Display::fmt(o, f),
409         }
410     }
411 }
412 
413 #[stable(feature = "default", since = "1.11.0")]
414 impl<B: ?Sized> Default for Cow<'_, B>
415 where
416     B: ToOwned<Owned: Default>,
417 {
418     /// Creates an owned Cow<'a, B> with the default value for the contained owned value.
default() -> Self419     fn default() -> Self {
420         Owned(<B as ToOwned>::Owned::default())
421     }
422 }
423 
424 #[stable(feature = "rust1", since = "1.0.0")]
425 impl<B: ?Sized> Hash for Cow<'_, B>
426 where
427     B: Hash + ToOwned,
428 {
429     #[inline]
hash<H: Hasher>(&self, state: &mut H)430     fn hash<H: Hasher>(&self, state: &mut H) {
431         Hash::hash(&**self, state)
432     }
433 }
434 
435 #[stable(feature = "rust1", since = "1.0.0")]
436 impl<T: ?Sized + ToOwned> AsRef<T> for Cow<'_, T> {
as_ref(&self) -> &T437     fn as_ref(&self) -> &T {
438         self
439     }
440 }
441 
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>;
446 
447     #[inline]
add(mut self, rhs: &'a str) -> Self::Output448     fn add(mut self, rhs: &'a str) -> Self::Output {
449         self += rhs;
450         self
451     }
452 }
453 
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>;
458 
459     #[inline]
add(mut self, rhs: Cow<'a, str>) -> Self::Output460     fn add(mut self, rhs: Cow<'a, str>) -> Self::Output {
461         self += rhs;
462         self
463     }
464 }
465 
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> {
add_assign(&mut self, rhs: &'a str)469     fn add_assign(&mut self, rhs: &'a str) {
470         if self.is_empty() {
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());
475                 s.push_str(lhs);
476                 *self = Cow::Owned(s);
477             }
478             self.to_mut().push_str(rhs);
479         }
480     }
481 }
482 
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> {
add_assign(&mut self, rhs: Cow<'a, str>)486     fn add_assign(&mut self, rhs: Cow<'a, str>) {
487         if self.is_empty() {
488             *self = rhs
489         } else if !rhs.is_empty() {
490             if let Cow::Borrowed(lhs) = *self {
491                 let mut s = String::with_capacity(lhs.len() + rhs.len());
492                 s.push_str(lhs);
493                 *self = Cow::Owned(s);
494             }
495             self.to_mut().push_str(&rhs);
496         }
497     }
498 }
499