]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/borrow.rs
Auto merge of #81238 - RalfJung:copy-intrinsics, r=m-ou-se
[rust.git] / library / alloc / src / borrow.rs
1 //! A module for working with borrowed data.
2
3 #![stable(feature = "rust1", since = "1.0.0")]
4
5 use core::cmp::Ordering;
6 use core::hash::{Hash, Hasher};
7 use core::ops::{Add, AddAssign, Deref};
8
9 #[stable(feature = "rust1", since = "1.0.0")]
10 pub use core::borrow::{Borrow, BorrowMut};
11
12 use crate::fmt;
13 use crate::string::String;
14
15 use Cow::*;
16
17 #[stable(feature = "rust1", since = "1.0.0")]
18 impl<'a, B: ?Sized> Borrow<B> for Cow<'a, B>
19 where
20     B: ToOwned,
21     <B as ToOwned>::Owned: 'a,
22 {
23     fn borrow(&self) -> &B {
24         &**self
25     }
26 }
27
28 /// A generalization of `Clone` to borrowed data.
29 ///
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")]
35 pub trait ToOwned {
36     /// The resulting type after obtaining ownership.
37     #[stable(feature = "rust1", since = "1.0.0")]
38     type Owned: Borrow<Self>;
39
40     /// Creates owned data from borrowed data, usually by cloning.
41     ///
42     /// # Examples
43     ///
44     /// Basic usage:
45     ///
46     /// ```
47     /// let s: &str = "a";
48     /// let ss: String = s.to_owned();
49     ///
50     /// let v: &[i32] = &[1, 2];
51     /// let vv: Vec<i32> = v.to_owned();
52     /// ```
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;
56
57     /// Uses borrowed data to replace owned data, usually by cloning.
58     ///
59     /// This is borrow-generalized version of `Clone::clone_from`.
60     ///
61     /// # Examples
62     ///
63     /// Basic usage:
64     ///
65     /// ```
66     /// # #![feature(toowned_clone_into)]
67     /// let mut s: String = String::new();
68     /// "hello".clone_into(&mut s);
69     ///
70     /// let mut v: Vec<i32> = Vec::new();
71     /// [1, 2][..].clone_into(&mut v);
72     /// ```
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();
76     }
77 }
78
79 #[stable(feature = "rust1", since = "1.0.0")]
80 impl<T> ToOwned for T
81 where
82     T: Clone,
83 {
84     type Owned = T;
85     fn to_owned(&self) -> T {
86         self.clone()
87     }
88
89     fn clone_into(&self, target: &mut T) {
90         target.clone_from(self);
91     }
92 }
93
94 /// A clone-on-write smart pointer.
95 ///
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.
100 ///
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.
105 ///
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.
110 ///
111 /// # Examples
112 ///
113 /// ```
114 /// use std::borrow::Cow;
115 ///
116 /// fn abs_all(input: &mut Cow<[i32]>) {
117 ///     for i in 0..input.len() {
118 ///         let v = input[i];
119 ///         if v < 0 {
120 ///             // Clones into a vector if not already owned.
121 ///             input.to_mut()[i] = -v;
122 ///         }
123 ///     }
124 /// }
125 ///
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);
130 ///
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);
135 ///
136 /// // No clone occurs because `input` is already owned.
137 /// let mut input = Cow::from(vec![-1, 0, 1]);
138 /// abs_all(&mut input);
139 /// ```
140 ///
141 /// Another example showing how to keep `Cow` in a struct:
142 ///
143 /// ```
144 /// use std::borrow::Cow;
145 ///
146 /// struct Items<'a, X: 'a> where [X]: ToOwned<Owned = Vec<X>> {
147 ///     values: Cow<'a, [X]>,
148 /// }
149 ///
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 }
153 ///     }
154 /// }
155 ///
156 /// // Creates a container from borrowed values of a slice
157 /// let readonly = [1, 2];
158 /// let borrowed = Items::new((&readonly[..]).into());
159 /// match borrowed {
160 ///     Items { values: Cow::Borrowed(b) } => println!("borrowed {:?}", b),
161 ///     _ => panic!("expect borrowed value"),
162 /// }
163 ///
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);
168 ///
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"),
173 /// }
174 /// ```
175 #[stable(feature = "rust1", since = "1.0.0")]
176 pub enum Cow<'a, B: ?Sized + 'a>
177 where
178     B: ToOwned,
179 {
180     /// Borrowed data.
181     #[stable(feature = "rust1", since = "1.0.0")]
182     Borrowed(#[stable(feature = "rust1", since = "1.0.0")] &'a B),
183
184     /// Owned data.
185     #[stable(feature = "rust1", since = "1.0.0")]
186     Owned(#[stable(feature = "rust1", since = "1.0.0")] <B as ToOwned>::Owned),
187 }
188
189 #[stable(feature = "rust1", since = "1.0.0")]
190 impl<B: ?Sized + ToOwned> Clone for Cow<'_, B> {
191     fn clone(&self) -> Self {
192         match *self {
193             Borrowed(b) => Borrowed(b),
194             Owned(ref o) => {
195                 let b: &B = o.borrow();
196                 Owned(b.to_owned())
197             }
198         }
199     }
200
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(),
205         }
206     }
207 }
208
209 impl<B: ?Sized + ToOwned> Cow<'_, B> {
210     /// Returns true if the data is borrowed, i.e. if `to_mut` would require additional work.
211     ///
212     /// # Examples
213     ///
214     /// ```
215     /// #![feature(cow_is_borrowed)]
216     /// use std::borrow::Cow;
217     ///
218     /// let cow = Cow::Borrowed("moo");
219     /// assert!(cow.is_borrowed());
220     ///
221     /// let bull: Cow<'_, str> = Cow::Owned("...moo?".to_string());
222     /// assert!(!bull.is_borrowed());
223     /// ```
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 {
227         match *self {
228             Borrowed(_) => true,
229             Owned(_) => false,
230         }
231     }
232
233     /// Returns true if the data is owned, i.e. if `to_mut` would be a no-op.
234     ///
235     /// # Examples
236     ///
237     /// ```
238     /// #![feature(cow_is_borrowed)]
239     /// use std::borrow::Cow;
240     ///
241     /// let cow: Cow<'_, str> = Cow::Owned("moo".to_string());
242     /// assert!(cow.is_owned());
243     ///
244     /// let bull = Cow::Borrowed("...moo?");
245     /// assert!(!bull.is_owned());
246     /// ```
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 {
250         !self.is_borrowed()
251     }
252
253     /// Acquires a mutable reference to the owned form of the data.
254     ///
255     /// Clones the data if it is not already owned.
256     ///
257     /// # Examples
258     ///
259     /// ```
260     /// use std::borrow::Cow;
261     ///
262     /// let mut cow = Cow::Borrowed("foo");
263     /// cow.to_mut().make_ascii_uppercase();
264     ///
265     /// assert_eq!(
266     ///   cow,
267     ///   Cow::Owned(String::from("FOO")) as Cow<str>
268     /// );
269     /// ```
270     #[stable(feature = "rust1", since = "1.0.0")]
271     pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned {
272         match *self {
273             Borrowed(borrowed) => {
274                 *self = Owned(borrowed.to_owned());
275                 match *self {
276                     Borrowed(..) => unreachable!(),
277                     Owned(ref mut owned) => owned,
278                 }
279             }
280             Owned(ref mut owned) => owned,
281         }
282     }
283
284     /// Extracts the owned data.
285     ///
286     /// Clones the data if it is not already owned.
287     ///
288     /// # Examples
289     ///
290     /// Calling `into_owned` on a `Cow::Borrowed` clones the underlying data
291     /// and becomes a `Cow::Owned`:
292     ///
293     /// ```
294     /// use std::borrow::Cow;
295     ///
296     /// let s = "Hello world!";
297     /// let cow = Cow::Borrowed(s);
298     ///
299     /// assert_eq!(
300     ///   cow.into_owned(),
301     ///   String::from(s)
302     /// );
303     /// ```
304     ///
305     /// Calling `into_owned` on a `Cow::Owned` is a no-op:
306     ///
307     /// ```
308     /// use std::borrow::Cow;
309     ///
310     /// let s = "Hello world!";
311     /// let cow: Cow<str> = Cow::Owned(String::from(s));
312     ///
313     /// assert_eq!(
314     ///   cow.into_owned(),
315     ///   String::from(s)
316     /// );
317     /// ```
318     #[stable(feature = "rust1", since = "1.0.0")]
319     pub fn into_owned(self) -> <B as ToOwned>::Owned {
320         match self {
321             Borrowed(borrowed) => borrowed.to_owned(),
322             Owned(owned) => owned,
323         }
324     }
325 }
326
327 #[stable(feature = "rust1", since = "1.0.0")]
328 impl<B: ?Sized + ToOwned> Deref for Cow<'_, B> {
329     type Target = B;
330
331     fn deref(&self) -> &B {
332         match *self {
333             Borrowed(borrowed) => borrowed,
334             Owned(ref owned) => owned.borrow(),
335         }
336     }
337 }
338
339 #[stable(feature = "rust1", since = "1.0.0")]
340 impl<B: ?Sized> Eq for Cow<'_, B> where B: Eq + ToOwned {}
341
342 #[stable(feature = "rust1", since = "1.0.0")]
343 impl<B: ?Sized> Ord for Cow<'_, B>
344 where
345     B: Ord + ToOwned,
346 {
347     #[inline]
348     fn cmp(&self, other: &Self) -> Ordering {
349         Ord::cmp(&**self, &**other)
350     }
351 }
352
353 #[stable(feature = "rust1", since = "1.0.0")]
354 impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, C>> for Cow<'a, B>
355 where
356     B: PartialEq<C> + ToOwned,
357     C: ToOwned,
358 {
359     #[inline]
360     fn eq(&self, other: &Cow<'b, C>) -> bool {
361         PartialEq::eq(&**self, &**other)
362     }
363 }
364
365 #[stable(feature = "rust1", since = "1.0.0")]
366 impl<'a, B: ?Sized> PartialOrd for Cow<'a, B>
367 where
368     B: PartialOrd + ToOwned,
369 {
370     #[inline]
371     fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering> {
372         PartialOrd::partial_cmp(&**self, &**other)
373     }
374 }
375
376 #[stable(feature = "rust1", since = "1.0.0")]
377 impl<B: ?Sized> fmt::Debug for Cow<'_, B>
378 where
379     B: fmt::Debug + ToOwned<Owned: fmt::Debug>,
380 {
381     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
382         match *self {
383             Borrowed(ref b) => fmt::Debug::fmt(b, f),
384             Owned(ref o) => fmt::Debug::fmt(o, f),
385         }
386     }
387 }
388
389 #[stable(feature = "rust1", since = "1.0.0")]
390 impl<B: ?Sized> fmt::Display for Cow<'_, B>
391 where
392     B: fmt::Display + ToOwned<Owned: fmt::Display>,
393 {
394     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
395         match *self {
396             Borrowed(ref b) => fmt::Display::fmt(b, f),
397             Owned(ref o) => fmt::Display::fmt(o, f),
398         }
399     }
400 }
401
402 #[stable(feature = "default", since = "1.11.0")]
403 impl<B: ?Sized> Default for Cow<'_, B>
404 where
405     B: ToOwned<Owned: Default>,
406 {
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())
410     }
411 }
412
413 #[stable(feature = "rust1", since = "1.0.0")]
414 impl<B: ?Sized> Hash for Cow<'_, B>
415 where
416     B: Hash + ToOwned,
417 {
418     #[inline]
419     fn hash<H: Hasher>(&self, state: &mut H) {
420         Hash::hash(&**self, state)
421     }
422 }
423
424 #[stable(feature = "rust1", since = "1.0.0")]
425 impl<T: ?Sized + ToOwned> AsRef<T> for Cow<'_, T> {
426     fn as_ref(&self) -> &T {
427         self
428     }
429 }
430
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>;
434
435     #[inline]
436     fn add(mut self, rhs: &'a str) -> Self::Output {
437         self += rhs;
438         self
439     }
440 }
441
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>;
445
446     #[inline]
447     fn add(mut self, rhs: Cow<'a, str>) -> Self::Output {
448         self += rhs;
449         self
450     }
451 }
452
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) {
456         if self.is_empty() {
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());
461                 s.push_str(lhs);
462                 *self = Cow::Owned(s);
463             }
464             self.to_mut().push_str(rhs);
465         }
466     }
467 }
468
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>) {
472         if self.is_empty() {
473             *self = rhs
474         } else if !rhs.is_empty() {
475             if let Cow::Borrowed(lhs) = *self {
476                 let mut s = String::with_capacity(lhs.len() + rhs.len());
477                 s.push_str(lhs);
478                 *self = Cow::Owned(s);
479             }
480             self.to_mut().push_str(&rhs);
481         }
482     }
483 }