]> git.lizzy.rs Git - rust.git/blob - src/liballoc/borrow.rs
rustc_span: return an impl Iterator instead of a Vec from macro_backtrace.
[rust.git] / src / liballoc / 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 /// # Examples
107 ///
108 /// ```
109 /// use std::borrow::Cow;
110 ///
111 /// fn abs_all(input: &mut Cow<[i32]>) {
112 ///     for i in 0..input.len() {
113 ///         let v = input[i];
114 ///         if v < 0 {
115 ///             // Clones into a vector if not already owned.
116 ///             input.to_mut()[i] = -v;
117 ///         }
118 ///     }
119 /// }
120 ///
121 /// // No clone occurs because `input` doesn't need to be mutated.
122 /// let slice = [0, 1, 2];
123 /// let mut input = Cow::from(&slice[..]);
124 /// abs_all(&mut input);
125 ///
126 /// // Clone occurs because `input` needs to be mutated.
127 /// let slice = [-1, 0, 1];
128 /// let mut input = Cow::from(&slice[..]);
129 /// abs_all(&mut input);
130 ///
131 /// // No clone occurs because `input` is already owned.
132 /// let mut input = Cow::from(vec![-1, 0, 1]);
133 /// abs_all(&mut input);
134 /// ```
135 ///
136 /// Another example showing how to keep `Cow` in a struct:
137 ///
138 /// ```
139 /// use std::borrow::Cow;
140 ///
141 /// struct Items<'a, X: 'a> where [X]: ToOwned<Owned = Vec<X>> {
142 ///     values: Cow<'a, [X]>,
143 /// }
144 ///
145 /// impl<'a, X: Clone + 'a> Items<'a, X> where [X]: ToOwned<Owned = Vec<X>> {
146 ///     fn new(v: Cow<'a, [X]>) -> Self {
147 ///         Items { values: v }
148 ///     }
149 /// }
150 ///
151 /// // Creates a container from borrowed values of a slice
152 /// let readonly = [1, 2];
153 /// let borrowed = Items::new((&readonly[..]).into());
154 /// match borrowed {
155 ///     Items { values: Cow::Borrowed(b) } => println!("borrowed {:?}", b),
156 ///     _ => panic!("expect borrowed value"),
157 /// }
158 ///
159 /// let mut clone_on_write = borrowed;
160 /// // Mutates the data from slice into owned vec and pushes a new value on top
161 /// clone_on_write.values.to_mut().push(3);
162 /// println!("clone_on_write = {:?}", clone_on_write.values);
163 ///
164 /// // The data was mutated. Let check it out.
165 /// match clone_on_write {
166 ///     Items { values: Cow::Owned(_) } => println!("clone_on_write contains owned data"),
167 ///     _ => panic!("expect owned data"),
168 /// }
169 /// ```
170 #[stable(feature = "rust1", since = "1.0.0")]
171 pub enum Cow<'a, B: ?Sized + 'a>
172 where
173     B: ToOwned,
174 {
175     /// Borrowed data.
176     #[stable(feature = "rust1", since = "1.0.0")]
177     Borrowed(#[stable(feature = "rust1", since = "1.0.0")] &'a B),
178
179     /// Owned data.
180     #[stable(feature = "rust1", since = "1.0.0")]
181     Owned(#[stable(feature = "rust1", since = "1.0.0")] <B as ToOwned>::Owned),
182 }
183
184 #[stable(feature = "rust1", since = "1.0.0")]
185 impl<B: ?Sized + ToOwned> Clone for Cow<'_, B> {
186     fn clone(&self) -> Self {
187         match *self {
188             Borrowed(b) => Borrowed(b),
189             Owned(ref o) => {
190                 let b: &B = o.borrow();
191                 Owned(b.to_owned())
192             }
193         }
194     }
195
196     fn clone_from(&mut self, source: &Self) {
197         match (self, source) {
198             (&mut Owned(ref mut dest), &Owned(ref o)) => o.borrow().clone_into(dest),
199             (t, s) => *t = s.clone(),
200         }
201     }
202 }
203
204 impl<B: ?Sized + ToOwned> Cow<'_, B> {
205     /// Returns true if the data is borrowed, i.e. if `to_mut` would require additional work.
206     ///
207     /// # Examples
208     ///
209     /// ```
210     /// #![feature(cow_is_borrowed)]
211     /// use std::borrow::Cow;
212     ///
213     /// let cow = Cow::Borrowed("moo");
214     /// assert!(cow.is_borrowed());
215     ///
216     /// let bull: Cow<'_, str> = Cow::Owned("...moo?".to_string());
217     /// assert!(!bull.is_borrowed());
218     /// ```
219     #[unstable(feature = "cow_is_borrowed", issue = "65143")]
220     pub fn is_borrowed(&self) -> bool {
221         match *self {
222             Borrowed(_) => true,
223             Owned(_) => false,
224         }
225     }
226
227     /// Returns true if the data is owned, i.e. if `to_mut` would be a no-op.
228     ///
229     /// # Examples
230     ///
231     /// ```
232     /// #![feature(cow_is_borrowed)]
233     /// use std::borrow::Cow;
234     ///
235     /// let cow: Cow<'_, str> = Cow::Owned("moo".to_string());
236     /// assert!(cow.is_owned());
237     ///
238     /// let bull = Cow::Borrowed("...moo?");
239     /// assert!(!bull.is_owned());
240     /// ```
241     #[unstable(feature = "cow_is_borrowed", issue = "65143")]
242     pub fn is_owned(&self) -> bool {
243         !self.is_borrowed()
244     }
245
246     /// Acquires a mutable reference to the owned form of the data.
247     ///
248     /// Clones the data if it is not already owned.
249     ///
250     /// # Examples
251     ///
252     /// ```
253     /// use std::borrow::Cow;
254     ///
255     /// let mut cow = Cow::Borrowed("foo");
256     /// cow.to_mut().make_ascii_uppercase();
257     ///
258     /// assert_eq!(
259     ///   cow,
260     ///   Cow::Owned(String::from("FOO")) as Cow<str>
261     /// );
262     /// ```
263     #[stable(feature = "rust1", since = "1.0.0")]
264     pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned {
265         match *self {
266             Borrowed(borrowed) => {
267                 *self = Owned(borrowed.to_owned());
268                 match *self {
269                     Borrowed(..) => unreachable!(),
270                     Owned(ref mut owned) => owned,
271                 }
272             }
273             Owned(ref mut owned) => owned,
274         }
275     }
276
277     /// Extracts the owned data.
278     ///
279     /// Clones the data if it is not already owned.
280     ///
281     /// # Examples
282     ///
283     /// Calling `into_owned` on a `Cow::Borrowed` clones the underlying data
284     /// and becomes a `Cow::Owned`:
285     ///
286     /// ```
287     /// use std::borrow::Cow;
288     ///
289     /// let s = "Hello world!";
290     /// let cow = Cow::Borrowed(s);
291     ///
292     /// assert_eq!(
293     ///   cow.into_owned(),
294     ///   String::from(s)
295     /// );
296     /// ```
297     ///
298     /// Calling `into_owned` on a `Cow::Owned` is a no-op:
299     ///
300     /// ```
301     /// use std::borrow::Cow;
302     ///
303     /// let s = "Hello world!";
304     /// let cow: Cow<str> = Cow::Owned(String::from(s));
305     ///
306     /// assert_eq!(
307     ///   cow.into_owned(),
308     ///   String::from(s)
309     /// );
310     /// ```
311     #[stable(feature = "rust1", since = "1.0.0")]
312     pub fn into_owned(self) -> <B as ToOwned>::Owned {
313         match self {
314             Borrowed(borrowed) => borrowed.to_owned(),
315             Owned(owned) => owned,
316         }
317     }
318 }
319
320 #[stable(feature = "rust1", since = "1.0.0")]
321 impl<B: ?Sized + ToOwned> Deref for Cow<'_, B> {
322     type Target = B;
323
324     fn deref(&self) -> &B {
325         match *self {
326             Borrowed(borrowed) => borrowed,
327             Owned(ref owned) => owned.borrow(),
328         }
329     }
330 }
331
332 #[stable(feature = "rust1", since = "1.0.0")]
333 impl<B: ?Sized> Eq for Cow<'_, B> where B: Eq + ToOwned {}
334
335 #[stable(feature = "rust1", since = "1.0.0")]
336 impl<B: ?Sized> Ord for Cow<'_, B>
337 where
338     B: Ord + ToOwned,
339 {
340     #[inline]
341     fn cmp(&self, other: &Self) -> Ordering {
342         Ord::cmp(&**self, &**other)
343     }
344 }
345
346 #[stable(feature = "rust1", since = "1.0.0")]
347 impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, C>> for Cow<'a, B>
348 where
349     B: PartialEq<C> + ToOwned,
350     C: ToOwned,
351 {
352     #[inline]
353     fn eq(&self, other: &Cow<'b, C>) -> bool {
354         PartialEq::eq(&**self, &**other)
355     }
356 }
357
358 #[stable(feature = "rust1", since = "1.0.0")]
359 impl<'a, B: ?Sized> PartialOrd for Cow<'a, B>
360 where
361     B: PartialOrd + ToOwned,
362 {
363     #[inline]
364     fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering> {
365         PartialOrd::partial_cmp(&**self, &**other)
366     }
367 }
368
369 #[stable(feature = "rust1", since = "1.0.0")]
370 impl<B: ?Sized> fmt::Debug for Cow<'_, B>
371 where
372     B: fmt::Debug + ToOwned<Owned: fmt::Debug>,
373 {
374     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
375         match *self {
376             Borrowed(ref b) => fmt::Debug::fmt(b, f),
377             Owned(ref o) => fmt::Debug::fmt(o, f),
378         }
379     }
380 }
381
382 #[stable(feature = "rust1", since = "1.0.0")]
383 impl<B: ?Sized> fmt::Display for Cow<'_, B>
384 where
385     B: fmt::Display + ToOwned<Owned: fmt::Display>,
386 {
387     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
388         match *self {
389             Borrowed(ref b) => fmt::Display::fmt(b, f),
390             Owned(ref o) => fmt::Display::fmt(o, f),
391         }
392     }
393 }
394
395 #[stable(feature = "default", since = "1.11.0")]
396 impl<B: ?Sized> Default for Cow<'_, B>
397 where
398     B: ToOwned<Owned: Default>,
399 {
400     /// Creates an owned Cow<'a, B> with the default value for the contained owned value.
401     fn default() -> Self {
402         Owned(<B as ToOwned>::Owned::default())
403     }
404 }
405
406 #[stable(feature = "rust1", since = "1.0.0")]
407 impl<B: ?Sized> Hash for Cow<'_, B>
408 where
409     B: Hash + ToOwned,
410 {
411     #[inline]
412     fn hash<H: Hasher>(&self, state: &mut H) {
413         Hash::hash(&**self, state)
414     }
415 }
416
417 #[stable(feature = "rust1", since = "1.0.0")]
418 impl<T: ?Sized + ToOwned> AsRef<T> for Cow<'_, T> {
419     fn as_ref(&self) -> &T {
420         self
421     }
422 }
423
424 #[stable(feature = "cow_add", since = "1.14.0")]
425 impl<'a> Add<&'a str> for Cow<'a, str> {
426     type Output = Cow<'a, str>;
427
428     #[inline]
429     fn add(mut self, rhs: &'a str) -> Self::Output {
430         self += rhs;
431         self
432     }
433 }
434
435 #[stable(feature = "cow_add", since = "1.14.0")]
436 impl<'a> Add<Cow<'a, str>> for Cow<'a, str> {
437     type Output = Cow<'a, str>;
438
439     #[inline]
440     fn add(mut self, rhs: Cow<'a, str>) -> Self::Output {
441         self += rhs;
442         self
443     }
444 }
445
446 #[stable(feature = "cow_add", since = "1.14.0")]
447 impl<'a> AddAssign<&'a str> for Cow<'a, str> {
448     fn add_assign(&mut self, rhs: &'a str) {
449         if self.is_empty() {
450             *self = Cow::Borrowed(rhs)
451         } else if !rhs.is_empty() {
452             if let Cow::Borrowed(lhs) = *self {
453                 let mut s = String::with_capacity(lhs.len() + rhs.len());
454                 s.push_str(lhs);
455                 *self = Cow::Owned(s);
456             }
457             self.to_mut().push_str(rhs);
458         }
459     }
460 }
461
462 #[stable(feature = "cow_add", since = "1.14.0")]
463 impl<'a> AddAssign<Cow<'a, str>> for Cow<'a, str> {
464     fn add_assign(&mut self, rhs: Cow<'a, str>) {
465         if self.is_empty() {
466             *self = rhs
467         } else if !rhs.is_empty() {
468             if let Cow::Borrowed(lhs) = *self {
469                 let mut s = String::with_capacity(lhs.len() + rhs.len());
470                 s.push_str(lhs);
471                 *self = Cow::Owned(s);
472             }
473             self.to_mut().push_str(&rhs);
474         }
475     }
476 }