]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/borrow.rs
Rollup merge of #86152 - the8472:lazify-npm-queries, r=Mark-Simulacrum
[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::Deref;
8 #[cfg(not(no_global_oom_handling))]
9 use core::ops::{Add, AddAssign};
10
11 #[stable(feature = "rust1", since = "1.0.0")]
12 pub use core::borrow::{Borrow, BorrowMut};
13
14 use crate::fmt;
15 #[cfg(not(no_global_oom_handling))]
16 use crate::string::String;
17
18 use Cow::*;
19
20 #[stable(feature = "rust1", since = "1.0.0")]
21 impl<'a, B: ?Sized> Borrow<B> for Cow<'a, B>
22 where
23     B: ToOwned,
24     <B as ToOwned>::Owned: 'a,
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 #[cfg_attr(not(test), rustc_diagnostic_item = "ToOwned")]
38 #[stable(feature = "rust1", since = "1.0.0")]
39 pub 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     fn to_owned(&self) -> Self::Owned;
60
61     /// Uses borrowed data to replace owned data, usually by cloning.
62     ///
63     /// This is borrow-generalized version of `Clone::clone_from`.
64     ///
65     /// # Examples
66     ///
67     /// Basic usage:
68     ///
69     /// ```
70     /// # #![feature(toowned_clone_into)]
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     #[unstable(feature = "toowned_clone_into", reason = "recently added", issue = "41263")]
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")]
84 impl<T> ToOwned for T
85 where
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: 'a> 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 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 pub enum Cow<'a, B: ?Sized + 'a>
181 where
182     B: ToOwned,
183 {
184     /// Borrowed data.
185     #[stable(feature = "rust1", since = "1.0.0")]
186     Borrowed(#[stable(feature = "rust1", since = "1.0.0")] &'a B),
187
188     /// Owned data.
189     #[stable(feature = "rust1", since = "1.0.0")]
190     Owned(#[stable(feature = "rust1", since = "1.0.0")] <B as ToOwned>::Owned),
191 }
192
193 #[stable(feature = "rust1", since = "1.0.0")]
194 impl<B: ?Sized + ToOwned> Clone for Cow<'_, B> {
195     fn clone(&self) -> Self {
196         match *self {
197             Borrowed(b) => Borrowed(b),
198             Owned(ref o) => {
199                 let b: &B = o.borrow();
200                 Owned(b.to_owned())
201             }
202         }
203     }
204
205     fn clone_from(&mut self, source: &Self) {
206         match (self, source) {
207             (&mut Owned(ref mut dest), &Owned(ref o)) => o.borrow().clone_into(dest),
208             (t, s) => *t = s.clone(),
209         }
210     }
211 }
212
213 impl<B: ?Sized + ToOwned> Cow<'_, B> {
214     /// Returns true if the data is borrowed, i.e. if `to_mut` would require additional work.
215     ///
216     /// # Examples
217     ///
218     /// ```
219     /// #![feature(cow_is_borrowed)]
220     /// use std::borrow::Cow;
221     ///
222     /// let cow = Cow::Borrowed("moo");
223     /// assert!(cow.is_borrowed());
224     ///
225     /// let bull: Cow<'_, str> = Cow::Owned("...moo?".to_string());
226     /// assert!(!bull.is_borrowed());
227     /// ```
228     #[unstable(feature = "cow_is_borrowed", issue = "65143")]
229     #[rustc_const_unstable(feature = "const_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     #[rustc_const_unstable(feature = "const_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` clones the underlying data
295     /// and becomes a `Cow::Owned`:
296     ///
297     /// ```
298     /// use std::borrow::Cow;
299     ///
300     /// let s = "Hello world!";
301     /// let cow = Cow::Borrowed(s);
302     ///
303     /// assert_eq!(
304     ///   cow.into_owned(),
305     ///   String::from(s)
306     /// );
307     /// ```
308     ///
309     /// Calling `into_owned` on a `Cow::Owned` is a no-op:
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 #[stable(feature = "rust1", since = "1.0.0")]
332 impl<B: ?Sized + ToOwned> Deref for Cow<'_, B> {
333     type Target = B;
334
335     fn deref(&self) -> &B {
336         match *self {
337             Borrowed(borrowed) => borrowed,
338             Owned(ref owned) => owned.borrow(),
339         }
340     }
341 }
342
343 #[stable(feature = "rust1", since = "1.0.0")]
344 impl<B: ?Sized> Eq for Cow<'_, B> where B: Eq + ToOwned {}
345
346 #[stable(feature = "rust1", since = "1.0.0")]
347 impl<B: ?Sized> Ord for Cow<'_, B>
348 where
349     B: Ord + ToOwned,
350 {
351     #[inline]
352     fn cmp(&self, other: &Self) -> Ordering {
353         Ord::cmp(&**self, &**other)
354     }
355 }
356
357 #[stable(feature = "rust1", since = "1.0.0")]
358 impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, C>> for Cow<'a, B>
359 where
360     B: PartialEq<C> + ToOwned,
361     C: ToOwned,
362 {
363     #[inline]
364     fn eq(&self, other: &Cow<'b, C>) -> bool {
365         PartialEq::eq(&**self, &**other)
366     }
367 }
368
369 #[stable(feature = "rust1", since = "1.0.0")]
370 impl<'a, B: ?Sized> PartialOrd for Cow<'a, B>
371 where
372     B: PartialOrd + ToOwned,
373 {
374     #[inline]
375     fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering> {
376         PartialOrd::partial_cmp(&**self, &**other)
377     }
378 }
379
380 #[stable(feature = "rust1", since = "1.0.0")]
381 impl<B: ?Sized> fmt::Debug for Cow<'_, B>
382 where
383     B: fmt::Debug + ToOwned<Owned: fmt::Debug>,
384 {
385     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
386         match *self {
387             Borrowed(ref b) => fmt::Debug::fmt(b, f),
388             Owned(ref o) => fmt::Debug::fmt(o, f),
389         }
390     }
391 }
392
393 #[stable(feature = "rust1", since = "1.0.0")]
394 impl<B: ?Sized> fmt::Display for Cow<'_, B>
395 where
396     B: fmt::Display + ToOwned<Owned: fmt::Display>,
397 {
398     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
399         match *self {
400             Borrowed(ref b) => fmt::Display::fmt(b, f),
401             Owned(ref o) => fmt::Display::fmt(o, f),
402         }
403     }
404 }
405
406 #[stable(feature = "default", since = "1.11.0")]
407 impl<B: ?Sized> Default for Cow<'_, B>
408 where
409     B: ToOwned<Owned: Default>,
410 {
411     /// Creates an owned Cow<'a, B> with the default value for the contained owned value.
412     fn default() -> Self {
413         Owned(<B as ToOwned>::Owned::default())
414     }
415 }
416
417 #[stable(feature = "rust1", since = "1.0.0")]
418 impl<B: ?Sized> Hash for Cow<'_, B>
419 where
420     B: Hash + ToOwned,
421 {
422     #[inline]
423     fn hash<H: Hasher>(&self, state: &mut H) {
424         Hash::hash(&**self, state)
425     }
426 }
427
428 #[stable(feature = "rust1", since = "1.0.0")]
429 impl<T: ?Sized + ToOwned> AsRef<T> for Cow<'_, T> {
430     fn as_ref(&self) -> &T {
431         self
432     }
433 }
434
435 #[cfg(not(no_global_oom_handling))]
436 #[stable(feature = "cow_add", since = "1.14.0")]
437 impl<'a> Add<&'a str> for Cow<'a, str> {
438     type Output = Cow<'a, str>;
439
440     #[inline]
441     fn add(mut self, rhs: &'a str) -> Self::Output {
442         self += rhs;
443         self
444     }
445 }
446
447 #[cfg(not(no_global_oom_handling))]
448 #[stable(feature = "cow_add", since = "1.14.0")]
449 impl<'a> Add<Cow<'a, str>> for Cow<'a, str> {
450     type Output = Cow<'a, str>;
451
452     #[inline]
453     fn add(mut self, rhs: Cow<'a, str>) -> Self::Output {
454         self += rhs;
455         self
456     }
457 }
458
459 #[cfg(not(no_global_oom_handling))]
460 #[stable(feature = "cow_add", since = "1.14.0")]
461 impl<'a> AddAssign<&'a str> for Cow<'a, str> {
462     fn add_assign(&mut self, rhs: &'a str) {
463         if self.is_empty() {
464             *self = Cow::Borrowed(rhs)
465         } else if !rhs.is_empty() {
466             if let Cow::Borrowed(lhs) = *self {
467                 let mut s = String::with_capacity(lhs.len() + rhs.len());
468                 s.push_str(lhs);
469                 *self = Cow::Owned(s);
470             }
471             self.to_mut().push_str(rhs);
472         }
473     }
474 }
475
476 #[cfg(not(no_global_oom_handling))]
477 #[stable(feature = "cow_add", since = "1.14.0")]
478 impl<'a> AddAssign<Cow<'a, str>> for Cow<'a, str> {
479     fn add_assign(&mut self, rhs: Cow<'a, str>) {
480         if self.is_empty() {
481             *self = rhs
482         } else if !rhs.is_empty() {
483             if let Cow::Borrowed(lhs) = *self {
484                 let mut s = String::with_capacity(lhs.len() + rhs.len());
485                 s.push_str(lhs);
486                 *self = Cow::Owned(s);
487             }
488             self.to_mut().push_str(&rhs);
489         }
490     }
491 }