[go: up one dir, main page]

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