alloc/
borrow.rs

1//! A module for working with borrowed data.
2
3#![stable(feature = "rust1", since = "1.0.0")]
4
5#[stable(feature = "rust1", since = "1.0.0")]
6pub use core::borrow::{Borrow, BorrowMut};
7use core::cmp::Ordering;
8use core::hash::{Hash, Hasher};
9#[cfg(not(no_global_oom_handling))]
10use core::ops::{Add, AddAssign};
11use core::ops::{Deref, DerefPure};
12
13use Cow::*;
14
15use crate::fmt;
16#[cfg(not(no_global_oom_handling))]
17use crate::string::String;
18
19#[stable(feature = "rust1", since = "1.0.0")]
20#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
21impl<'a, B: ?Sized> const Borrow<B> for Cow<'a, B>
22where
23    B: ToOwned,
24    B::Owned: [const] Borrow<B>,
25{
26    fn borrow(&self) -> &B {
27        &**self
28    }
29}
30
31/// A generalization of `Clone` to borrowed data.
32///
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#[rustc_diagnostic_item = "ToOwned"]
38#[stable(feature = "rust1", since = "1.0.0")]
39pub trait ToOwned {
40    /// The resulting type after obtaining ownership.
41    #[stable(feature = "rust1", since = "1.0.0")]
42    type Owned: Borrow<Self>;
43
44    /// Creates owned data from borrowed data, usually by cloning.
45    ///
46    /// # Examples
47    ///
48    /// Basic usage:
49    ///
50    /// ```
51    /// let s: &str = "a";
52    /// let ss: String = s.to_owned();
53    ///
54    /// let v: &[i32] = &[1, 2];
55    /// let vv: Vec<i32> = v.to_owned();
56    /// ```
57    #[stable(feature = "rust1", since = "1.0.0")]
58    #[must_use = "cloning is often expensive and is not expected to have side effects"]
59    #[rustc_diagnostic_item = "to_owned_method"]
60    fn to_owned(&self) -> Self::Owned;
61
62    /// Uses borrowed data to replace owned data, usually by cloning.
63    ///
64    /// This is borrow-generalized version of [`Clone::clone_from`].
65    ///
66    /// # Examples
67    ///
68    /// Basic usage:
69    ///
70    /// ```
71    /// let mut s: String = String::new();
72    /// "hello".clone_into(&mut s);
73    ///
74    /// let mut v: Vec<i32> = Vec::new();
75    /// [1, 2][..].clone_into(&mut v);
76    /// ```
77    #[stable(feature = "toowned_clone_into", since = "1.63.0")]
78    fn clone_into(&self, target: &mut Self::Owned) {
79        *target = self.to_owned();
80    }
81}
82
83#[stable(feature = "rust1", since = "1.0.0")]
84impl<T> ToOwned for T
85where
86    T: Clone,
87{
88    type Owned = T;
89    fn to_owned(&self) -> T {
90        self.clone()
91    }
92
93    fn clone_into(&self, target: &mut T) {
94        target.clone_from(self);
95    }
96}
97
98/// A clone-on-write smart pointer.
99///
100/// The type `Cow` is a smart pointer providing clone-on-write functionality: it
101/// can enclose and provide immutable access to borrowed data, and clone the
102/// data lazily when mutation or ownership is required. The type is designed to
103/// work with general borrowed data via the `Borrow` trait.
104///
105/// `Cow` implements `Deref`, which means that you can call
106/// non-mutating methods directly on the data it encloses. If mutation
107/// is desired, `to_mut` will obtain a mutable reference to an owned
108/// value, cloning if necessary.
109///
110/// If you need reference-counting pointers, note that
111/// [`Rc::make_mut`][crate::rc::Rc::make_mut] and
112/// [`Arc::make_mut`][crate::sync::Arc::make_mut] can provide clone-on-write
113/// functionality as well.
114///
115/// # Examples
116///
117/// ```
118/// use std::borrow::Cow;
119///
120/// fn abs_all(input: &mut Cow<'_, [i32]>) {
121///     for i in 0..input.len() {
122///         let v = input[i];
123///         if v < 0 {
124///             // Clones into a vector if not already owned.
125///             input.to_mut()[i] = -v;
126///         }
127///     }
128/// }
129///
130/// // No clone occurs because `input` doesn't need to be mutated.
131/// let slice = [0, 1, 2];
132/// let mut input = Cow::from(&slice[..]);
133/// abs_all(&mut input);
134///
135/// // Clone occurs because `input` needs to be mutated.
136/// let slice = [-1, 0, 1];
137/// let mut input = Cow::from(&slice[..]);
138/// abs_all(&mut input);
139///
140/// // No clone occurs because `input` is already owned.
141/// let mut input = Cow::from(vec![-1, 0, 1]);
142/// abs_all(&mut input);
143/// ```
144///
145/// Another example showing how to keep `Cow` in a struct:
146///
147/// ```
148/// use std::borrow::Cow;
149///
150/// struct Items<'a, X> where [X]: ToOwned<Owned = Vec<X>> {
151///     values: Cow<'a, [X]>,
152/// }
153///
154/// impl<'a, X: Clone + 'a> Items<'a, X> where [X]: ToOwned<Owned = Vec<X>> {
155///     fn new(v: Cow<'a, [X]>) -> Self {
156///         Items { values: v }
157///     }
158/// }
159///
160/// // Creates a container from borrowed values of a slice
161/// let readonly = [1, 2];
162/// let borrowed = Items::new((&readonly[..]).into());
163/// match borrowed {
164///     Items { values: Cow::Borrowed(b) } => println!("borrowed {b:?}"),
165///     _ => panic!("expect borrowed value"),
166/// }
167///
168/// let mut clone_on_write = borrowed;
169/// // Mutates the data from slice into owned vec and pushes a new value on top
170/// clone_on_write.values.to_mut().push(3);
171/// println!("clone_on_write = {:?}", clone_on_write.values);
172///
173/// // The data was mutated. Let's check it out.
174/// match clone_on_write {
175///     Items { values: Cow::Owned(_) } => println!("clone_on_write contains owned data"),
176///     _ => panic!("expect owned data"),
177/// }
178/// ```
179#[stable(feature = "rust1", since = "1.0.0")]
180#[rustc_diagnostic_item = "Cow"]
181pub enum Cow<'a, B: ?Sized + 'a>
182where
183    B: ToOwned,
184{
185    /// Borrowed data.
186    #[stable(feature = "rust1", since = "1.0.0")]
187    Borrowed(#[stable(feature = "rust1", since = "1.0.0")] &'a B),
188
189    /// Owned data.
190    #[stable(feature = "rust1", since = "1.0.0")]
191    Owned(#[stable(feature = "rust1", since = "1.0.0")] <B as ToOwned>::Owned),
192}
193
194#[stable(feature = "rust1", since = "1.0.0")]
195impl<B: ?Sized + ToOwned> Clone for Cow<'_, B> {
196    fn clone(&self) -> Self {
197        match *self {
198            Borrowed(b) => Borrowed(b),
199            Owned(ref o) => {
200                let b: &B = o.borrow();
201                Owned(b.to_owned())
202            }
203        }
204    }
205
206    fn clone_from(&mut self, source: &Self) {
207        match (self, source) {
208            (&mut Owned(ref mut dest), &Owned(ref o)) => o.borrow().clone_into(dest),
209            (t, s) => *t = s.clone(),
210        }
211    }
212}
213
214impl<B: ?Sized + ToOwned> Cow<'_, B> {
215    /// Returns true if the data is borrowed, i.e. if `to_mut` would require additional work.
216    ///
217    /// # Examples
218    ///
219    /// ```
220    /// #![feature(cow_is_borrowed)]
221    /// use std::borrow::Cow;
222    ///
223    /// let cow = Cow::Borrowed("moo");
224    /// assert!(cow.is_borrowed());
225    ///
226    /// let bull: Cow<'_, str> = Cow::Owned("...moo?".to_string());
227    /// assert!(!bull.is_borrowed());
228    /// ```
229    #[unstable(feature = "cow_is_borrowed", issue = "65143")]
230    pub const fn is_borrowed(&self) -> bool {
231        match *self {
232            Borrowed(_) => true,
233            Owned(_) => false,
234        }
235    }
236
237    /// Returns true if the data is owned, i.e. if `to_mut` would be a no-op.
238    ///
239    /// # Examples
240    ///
241    /// ```
242    /// #![feature(cow_is_borrowed)]
243    /// use std::borrow::Cow;
244    ///
245    /// let cow: Cow<'_, str> = Cow::Owned("moo".to_string());
246    /// assert!(cow.is_owned());
247    ///
248    /// let bull = Cow::Borrowed("...moo?");
249    /// assert!(!bull.is_owned());
250    /// ```
251    #[unstable(feature = "cow_is_borrowed", issue = "65143")]
252    pub const fn is_owned(&self) -> bool {
253        !self.is_borrowed()
254    }
255
256    /// Acquires a mutable reference to the owned form of the data.
257    ///
258    /// Clones the data if it is not already owned.
259    ///
260    /// # Examples
261    ///
262    /// ```
263    /// use std::borrow::Cow;
264    ///
265    /// let mut cow = Cow::Borrowed("foo");
266    /// cow.to_mut().make_ascii_uppercase();
267    ///
268    /// assert_eq!(
269    ///   cow,
270    ///   Cow::Owned(String::from("FOO")) as Cow<'_, str>
271    /// );
272    /// ```
273    #[stable(feature = "rust1", since = "1.0.0")]
274    pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned {
275        match *self {
276            Borrowed(borrowed) => {
277                *self = Owned(borrowed.to_owned());
278                match *self {
279                    Borrowed(..) => unreachable!(),
280                    Owned(ref mut owned) => owned,
281                }
282            }
283            Owned(ref mut owned) => owned,
284        }
285    }
286
287    /// Extracts the owned data.
288    ///
289    /// Clones the data if it is not already owned.
290    ///
291    /// # Examples
292    ///
293    /// Calling `into_owned` on a `Cow::Borrowed` returns a clone of the borrowed data:
294    ///
295    /// ```
296    /// use std::borrow::Cow;
297    ///
298    /// let s = "Hello world!";
299    /// let cow = Cow::Borrowed(s);
300    ///
301    /// assert_eq!(
302    ///   cow.into_owned(),
303    ///   String::from(s)
304    /// );
305    /// ```
306    ///
307    /// Calling `into_owned` on a `Cow::Owned` returns the owned data. The data is moved out of the
308    /// `Cow` without being cloned.
309    ///
310    /// ```
311    /// use std::borrow::Cow;
312    ///
313    /// let s = "Hello world!";
314    /// let cow: Cow<'_, str> = Cow::Owned(String::from(s));
315    ///
316    /// assert_eq!(
317    ///   cow.into_owned(),
318    ///   String::from(s)
319    /// );
320    /// ```
321    #[stable(feature = "rust1", since = "1.0.0")]
322    pub fn into_owned(self) -> <B as ToOwned>::Owned {
323        match self {
324            Borrowed(borrowed) => borrowed.to_owned(),
325            Owned(owned) => owned,
326        }
327    }
328}
329
330#[stable(feature = "rust1", since = "1.0.0")]
331#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
332impl<B: ?Sized + ToOwned> const Deref for Cow<'_, B>
333where
334    B::Owned: [const] Borrow<B>,
335{
336    type Target = B;
337
338    fn deref(&self) -> &B {
339        match *self {
340            Borrowed(borrowed) => borrowed,
341            Owned(ref owned) => owned.borrow(),
342        }
343    }
344}
345
346// `Cow<'_, T>` can only implement `DerefPure` if `<T::Owned as Borrow<T>>` (and `BorrowMut<T>`) is trusted.
347// For now, we restrict `DerefPure for Cow<T>` to `T: Sized` (`T as Borrow<T>` is trusted),
348// `str` (`String as Borrow<str>` is trusted) and `[T]` (`Vec<T> as Borrow<[T]>` is trusted).
349// In the future, a `BorrowPure<T>` trait analogous to `DerefPure` might generalize this.
350#[unstable(feature = "deref_pure_trait", issue = "87121")]
351unsafe impl<T: Clone> DerefPure for Cow<'_, T> {}
352#[cfg(not(no_global_oom_handling))]
353#[unstable(feature = "deref_pure_trait", issue = "87121")]
354unsafe impl DerefPure for Cow<'_, str> {}
355#[cfg(not(no_global_oom_handling))]
356#[unstable(feature = "deref_pure_trait", issue = "87121")]
357unsafe impl<T: Clone> DerefPure for Cow<'_, [T]> {}
358
359#[stable(feature = "rust1", since = "1.0.0")]
360impl<B: ?Sized> Eq for Cow<'_, B> where B: Eq + ToOwned {}
361
362#[stable(feature = "rust1", since = "1.0.0")]
363impl<B: ?Sized> Ord for Cow<'_, B>
364where
365    B: Ord + ToOwned,
366{
367    #[inline]
368    fn cmp(&self, other: &Self) -> Ordering {
369        Ord::cmp(&**self, &**other)
370    }
371}
372
373#[stable(feature = "rust1", since = "1.0.0")]
374impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, C>> for Cow<'a, B>
375where
376    B: PartialEq<C> + ToOwned,
377    C: ToOwned,
378{
379    #[inline]
380    fn eq(&self, other: &Cow<'b, C>) -> bool {
381        PartialEq::eq(&**self, &**other)
382    }
383}
384
385#[stable(feature = "rust1", since = "1.0.0")]
386impl<'a, B: ?Sized> PartialOrd for Cow<'a, B>
387where
388    B: PartialOrd + ToOwned,
389{
390    #[inline]
391    fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering> {
392        PartialOrd::partial_cmp(&**self, &**other)
393    }
394}
395
396#[stable(feature = "rust1", since = "1.0.0")]
397impl<B: ?Sized> fmt::Debug for Cow<'_, B>
398where
399    B: fmt::Debug + ToOwned<Owned: fmt::Debug>,
400{
401    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402        match *self {
403            Borrowed(ref b) => fmt::Debug::fmt(b, f),
404            Owned(ref o) => fmt::Debug::fmt(o, f),
405        }
406    }
407}
408
409#[stable(feature = "rust1", since = "1.0.0")]
410impl<B: ?Sized> fmt::Display for Cow<'_, B>
411where
412    B: fmt::Display + ToOwned<Owned: fmt::Display>,
413{
414    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
415        match *self {
416            Borrowed(ref b) => fmt::Display::fmt(b, f),
417            Owned(ref o) => fmt::Display::fmt(o, f),
418        }
419    }
420}
421
422#[stable(feature = "default", since = "1.11.0")]
423impl<B: ?Sized> Default for Cow<'_, B>
424where
425    B: ToOwned<Owned: Default>,
426{
427    /// Creates an owned Cow<'a, B> with the default value for the contained owned value.
428    fn default() -> Self {
429        Owned(<B as ToOwned>::Owned::default())
430    }
431}
432
433#[stable(feature = "rust1", since = "1.0.0")]
434impl<B: ?Sized> Hash for Cow<'_, B>
435where
436    B: Hash + ToOwned,
437{
438    #[inline]
439    fn hash<H: Hasher>(&self, state: &mut H) {
440        Hash::hash(&**self, state)
441    }
442}
443
444#[stable(feature = "rust1", since = "1.0.0")]
445#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
446impl<T: ?Sized + ToOwned> const AsRef<T> for Cow<'_, T>
447where
448    T::Owned: [const] Borrow<T>,
449{
450    fn as_ref(&self) -> &T {
451        self
452    }
453}
454
455#[cfg(not(no_global_oom_handling))]
456#[stable(feature = "cow_add", since = "1.14.0")]
457impl<'a> Add<&'a str> for Cow<'a, str> {
458    type Output = Cow<'a, str>;
459
460    #[inline]
461    fn add(mut self, rhs: &'a str) -> Self::Output {
462        self += rhs;
463        self
464    }
465}
466
467#[cfg(not(no_global_oom_handling))]
468#[stable(feature = "cow_add", since = "1.14.0")]
469impl<'a> Add<Cow<'a, str>> for Cow<'a, str> {
470    type Output = Cow<'a, str>;
471
472    #[inline]
473    fn add(mut self, rhs: Cow<'a, str>) -> Self::Output {
474        self += rhs;
475        self
476    }
477}
478
479#[cfg(not(no_global_oom_handling))]
480#[stable(feature = "cow_add", since = "1.14.0")]
481impl<'a> AddAssign<&'a str> for Cow<'a, str> {
482    fn add_assign(&mut self, rhs: &'a str) {
483        if self.is_empty() {
484            *self = Cow::Borrowed(rhs)
485        } else if !rhs.is_empty() {
486            if let Cow::Borrowed(lhs) = *self {
487                let mut s = String::with_capacity(lhs.len() + rhs.len());
488                s.push_str(lhs);
489                *self = Cow::Owned(s);
490            }
491            self.to_mut().push_str(rhs);
492        }
493    }
494}
495
496#[cfg(not(no_global_oom_handling))]
497#[stable(feature = "cow_add", since = "1.14.0")]
498impl<'a> AddAssign<Cow<'a, str>> for Cow<'a, str> {
499    fn add_assign(&mut self, rhs: Cow<'a, str>) {
500        if self.is_empty() {
501            *self = rhs
502        } else if !rhs.is_empty() {
503            if let Cow::Borrowed(lhs) = *self {
504                let mut s = String::with_capacity(lhs.len() + rhs.len());
505                s.push_str(lhs);
506                *self = Cow::Owned(s);
507            }
508            self.to_mut().push_str(&rhs);
509        }
510    }
511}