]> git.lizzy.rs Git - rust.git/blob - src/liballoc/borrow.rs
ee1799fad8e15c4ae09b31623b5ebb8670a82d13
[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 B: ToOwned,
20           <B as ToOwned>::Owned: 'a
21 {
22     fn borrow(&self) -> &B {
23         &**self
24     }
25 }
26
27 /// A generalization of `Clone` to borrowed data.
28 ///
29 /// Some types make it possible to go from borrowed to owned, usually by
30 /// implementing the `Clone` trait. But `Clone` works only for going from `&T`
31 /// to `T`. The `ToOwned` trait generalizes `Clone` to construct owned data
32 /// from any borrow of a given type.
33 #[stable(feature = "rust1", since = "1.0.0")]
34 pub trait ToOwned {
35     #[stable(feature = "rust1", since = "1.0.0")]
36     type Owned: Borrow<Self>;
37
38     /// Creates owned data from borrowed data, usually by cloning.
39     ///
40     /// # Examples
41     ///
42     /// Basic usage:
43     ///
44     /// ```
45     /// let s: &str = "a";
46     /// let ss: String = s.to_owned();
47     ///
48     /// let v: &[i32] = &[1, 2];
49     /// let vv: Vec<i32> = v.to_owned();
50     /// ```
51     #[stable(feature = "rust1", since = "1.0.0")]
52     #[must_use = "cloning is often expensive and is not expected to have side effects"]
53     fn to_owned(&self) -> Self::Owned;
54
55     /// Uses borrowed data to replace owned data, usually by cloning.
56     ///
57     /// This is borrow-generalized version of `Clone::clone_from`.
58     ///
59     /// # Examples
60     ///
61     /// Basic usage:
62     ///
63     /// ```
64     /// # #![feature(toowned_clone_into)]
65     /// let mut s: String = String::new();
66     /// "hello".clone_into(&mut s);
67     ///
68     /// let mut v: Vec<i32> = Vec::new();
69     /// [1, 2][..].clone_into(&mut v);
70     /// ```
71     #[unstable(feature = "toowned_clone_into",
72                reason = "recently added",
73                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 T: Clone
82 {
83     type Owned = T;
84     fn to_owned(&self) -> T {
85         self.clone()
86     }
87
88     fn clone_into(&self, target: &mut T) {
89         target.clone_from(self);
90     }
91 }
92
93 /// A clone-on-write smart pointer.
94 ///
95 /// The type `Cow` is a smart pointer providing clone-on-write functionality: it
96 /// can enclose and provide immutable access to borrowed data, and clone the
97 /// data lazily when mutation or ownership is required. The type is designed to
98 /// work with general borrowed data via the `Borrow` trait.
99 ///
100 /// `Cow` implements `Deref`, which means that you can call
101 /// non-mutating methods directly on the data it encloses. If mutation
102 /// is desired, `to_mut` will obtain a mutable reference to an owned
103 /// value, cloning if necessary.
104 ///
105 /// # Examples
106 ///
107 /// ```
108 /// use std::borrow::Cow;
109 ///
110 /// fn abs_all(input: &mut Cow<[i32]>) {
111 ///     for i in 0..input.len() {
112 ///         let v = input[i];
113 ///         if v < 0 {
114 ///             // Clones into a vector if not already owned.
115 ///             input.to_mut()[i] = -v;
116 ///         }
117 ///     }
118 /// }
119 ///
120 /// // No clone occurs because `input` doesn't need to be mutated.
121 /// let slice = [0, 1, 2];
122 /// let mut input = Cow::from(&slice[..]);
123 /// abs_all(&mut input);
124 ///
125 /// // Clone occurs because `input` needs to be mutated.
126 /// let slice = [-1, 0, 1];
127 /// let mut input = Cow::from(&slice[..]);
128 /// abs_all(&mut input);
129 ///
130 /// // No clone occurs because `input` is already owned.
131 /// let mut input = Cow::from(vec![-1, 0, 1]);
132 /// abs_all(&mut input);
133 /// ```
134 ///
135 /// Another example showing how to keep `Cow` in a struct:
136 ///
137 /// ```
138 /// use std::borrow::Cow;
139 ///
140 /// struct Items<'a, X: 'a> where [X]: ToOwned<Owned = Vec<X>> {
141 ///     values: Cow<'a, [X]>,
142 /// }
143 ///
144 /// impl<'a, X: Clone + 'a> Items<'a, X> where [X]: ToOwned<Owned = Vec<X>> {
145 ///     fn new(v: Cow<'a, [X]>) -> Self {
146 ///         Items { values: v }
147 ///     }
148 /// }
149 ///
150 /// // Creates a container from borrowed values of a slice
151 /// let readonly = [1, 2];
152 /// let borrowed = Items::new((&readonly[..]).into());
153 /// match borrowed {
154 ///     Items { values: Cow::Borrowed(b) } => println!("borrowed {:?}", b),
155 ///     _ => panic!("expect borrowed value"),
156 /// }
157 ///
158 /// let mut clone_on_write = borrowed;
159 /// // Mutates the data from slice into owned vec and pushes a new value on top
160 /// clone_on_write.values.to_mut().push(3);
161 /// println!("clone_on_write = {:?}", clone_on_write.values);
162 ///
163 /// // The data was mutated. Let check it out.
164 /// match clone_on_write {
165 ///     Items { values: Cow::Owned(_) } => println!("clone_on_write contains owned data"),
166 ///     _ => panic!("expect owned data"),
167 /// }
168 /// ```
169 #[stable(feature = "rust1", since = "1.0.0")]
170 pub enum Cow<'a, B: ?Sized + 'a>
171     where B: ToOwned
172 {
173     /// Borrowed data.
174     #[stable(feature = "rust1", since = "1.0.0")]
175     Borrowed(#[stable(feature = "rust1", since = "1.0.0")]
176              &'a B),
177
178     /// Owned data.
179     #[stable(feature = "rust1", since = "1.0.0")]
180     Owned(#[stable(feature = "rust1", since = "1.0.0")]
181           <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         if let Owned(ref mut dest) = *self {
198             if let Owned(ref o) = *source {
199                 o.borrow().clone_into(dest);
200                 return;
201             }
202         }
203
204         *self = source.clone();
205     }
206 }
207
208 impl<B: ?Sized + ToOwned> Cow<'_, B> {
209     /// Acquires a mutable reference to the owned form of the data.
210     ///
211     /// Clones the data if it is not already owned.
212     ///
213     /// # Examples
214     ///
215     /// ```
216     /// use std::borrow::Cow;
217     ///
218     /// let mut cow = Cow::Borrowed("foo");
219     /// cow.to_mut().make_ascii_uppercase();
220     ///
221     /// assert_eq!(
222     ///   cow,
223     ///   Cow::Owned(String::from("FOO")) as Cow<str>
224     /// );
225     /// ```
226     #[stable(feature = "rust1", since = "1.0.0")]
227     pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned {
228         match *self {
229             Borrowed(borrowed) => {
230                 *self = Owned(borrowed.to_owned());
231                 match *self {
232                     Borrowed(..) => unreachable!(),
233                     Owned(ref mut owned) => owned,
234                 }
235             }
236             Owned(ref mut owned) => owned,
237         }
238     }
239
240     /// Extracts the owned data.
241     ///
242     /// Clones the data if it is not already owned.
243     ///
244     /// # Examples
245     ///
246     /// Calling `into_owned` on a `Cow::Borrowed` clones the underlying data
247     /// and becomes a `Cow::Owned`:
248     ///
249     /// ```
250     /// use std::borrow::Cow;
251     ///
252     /// let s = "Hello world!";
253     /// let cow = Cow::Borrowed(s);
254     ///
255     /// assert_eq!(
256     ///   cow.into_owned(),
257     ///   String::from(s)
258     /// );
259     /// ```
260     ///
261     /// Calling `into_owned` on a `Cow::Owned` is a no-op:
262     ///
263     /// ```
264     /// use std::borrow::Cow;
265     ///
266     /// let s = "Hello world!";
267     /// let cow: Cow<str> = Cow::Owned(String::from(s));
268     ///
269     /// assert_eq!(
270     ///   cow.into_owned(),
271     ///   String::from(s)
272     /// );
273     /// ```
274     #[stable(feature = "rust1", since = "1.0.0")]
275     pub fn into_owned(self) -> <B as ToOwned>::Owned {
276         match self {
277             Borrowed(borrowed) => borrowed.to_owned(),
278             Owned(owned) => owned,
279         }
280     }
281 }
282
283 #[stable(feature = "rust1", since = "1.0.0")]
284 impl<B: ?Sized + ToOwned> Deref for Cow<'_, B> {
285     type Target = B;
286
287     fn deref(&self) -> &B {
288         match *self {
289             Borrowed(borrowed) => borrowed,
290             Owned(ref owned) => owned.borrow(),
291         }
292     }
293 }
294
295 #[stable(feature = "rust1", since = "1.0.0")]
296 impl<B: ?Sized> Eq for Cow<'_, B> where B: Eq + ToOwned {}
297
298 #[stable(feature = "rust1", since = "1.0.0")]
299 impl<B: ?Sized> Ord for Cow<'_, B>
300     where B: Ord + ToOwned
301 {
302     #[inline]
303     fn cmp(&self, other: &Self) -> Ordering {
304         Ord::cmp(&**self, &**other)
305     }
306 }
307
308 #[stable(feature = "rust1", since = "1.0.0")]
309 impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, C>> for Cow<'a, B>
310     where B: PartialEq<C> + ToOwned,
311           C: ToOwned
312 {
313     #[inline]
314     fn eq(&self, other: &Cow<'b, C>) -> bool {
315         PartialEq::eq(&**self, &**other)
316     }
317 }
318
319 #[stable(feature = "rust1", since = "1.0.0")]
320 impl<'a, B: ?Sized> PartialOrd for Cow<'a, B>
321     where B: PartialOrd + ToOwned
322 {
323     #[inline]
324     fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering> {
325         PartialOrd::partial_cmp(&**self, &**other)
326     }
327 }
328
329 #[stable(feature = "rust1", since = "1.0.0")]
330 impl<B: ?Sized> fmt::Debug for Cow<'_, B>
331     where B: fmt::Debug + ToOwned,
332           <B as ToOwned>::Owned: fmt::Debug
333 {
334     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335         match *self {
336             Borrowed(ref b) => fmt::Debug::fmt(b, f),
337             Owned(ref o) => fmt::Debug::fmt(o, f),
338         }
339     }
340 }
341
342 #[stable(feature = "rust1", since = "1.0.0")]
343 impl<B: ?Sized> fmt::Display for Cow<'_, B>
344     where B: fmt::Display + ToOwned,
345           <B as ToOwned>::Owned: fmt::Display
346 {
347     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348         match *self {
349             Borrowed(ref b) => fmt::Display::fmt(b, f),
350             Owned(ref o) => fmt::Display::fmt(o, f),
351         }
352     }
353 }
354
355 #[stable(feature = "default", since = "1.11.0")]
356 impl<B: ?Sized> Default for Cow<'_, B>
357     where B: ToOwned,
358           <B as ToOwned>::Owned: Default
359 {
360     /// Creates an owned Cow<'a, B> with the default value for the contained owned value.
361     fn default() -> Self {
362         Owned(<B as ToOwned>::Owned::default())
363     }
364 }
365
366 #[stable(feature = "rust1", since = "1.0.0")]
367 impl<B: ?Sized> Hash for Cow<'_, B>
368     where B: Hash + ToOwned
369 {
370     #[inline]
371     fn hash<H: Hasher>(&self, state: &mut H) {
372         Hash::hash(&**self, state)
373     }
374 }
375
376 #[stable(feature = "rust1", since = "1.0.0")]
377 impl<T: ?Sized + ToOwned> AsRef<T> for Cow<'_, T> {
378     fn as_ref(&self) -> &T {
379         self
380     }
381 }
382
383 #[stable(feature = "cow_add", since = "1.14.0")]
384 impl<'a> Add<&'a str> for Cow<'a, str> {
385     type Output = Cow<'a, str>;
386
387     #[inline]
388     fn add(mut self, rhs: &'a str) -> Self::Output {
389         self += rhs;
390         self
391     }
392 }
393
394 #[stable(feature = "cow_add", since = "1.14.0")]
395 impl<'a> Add<Cow<'a, str>> for Cow<'a, str> {
396     type Output = Cow<'a, str>;
397
398     #[inline]
399     fn add(mut self, rhs: Cow<'a, str>) -> Self::Output {
400         self += rhs;
401         self
402     }
403 }
404
405 #[stable(feature = "cow_add", since = "1.14.0")]
406 impl<'a> AddAssign<&'a str> for Cow<'a, str> {
407     fn add_assign(&mut self, rhs: &'a str) {
408         if self.is_empty() {
409             *self = Cow::Borrowed(rhs)
410         } else if rhs.is_empty() {
411             return;
412         } else {
413             if let Cow::Borrowed(lhs) = *self {
414                 let mut s = String::with_capacity(lhs.len() + rhs.len());
415                 s.push_str(lhs);
416                 *self = Cow::Owned(s);
417             }
418             self.to_mut().push_str(rhs);
419         }
420     }
421 }
422
423 #[stable(feature = "cow_add", since = "1.14.0")]
424 impl<'a> AddAssign<Cow<'a, str>> for Cow<'a, str> {
425     fn add_assign(&mut self, rhs: Cow<'a, str>) {
426         if self.is_empty() {
427             *self = rhs
428         } else if rhs.is_empty() {
429             return;
430         } else {
431             if let Cow::Borrowed(lhs) = *self {
432                 let mut s = String::with_capacity(lhs.len() + rhs.len());
433                 s.push_str(lhs);
434                 *self = Cow::Owned(s);
435             }
436             self.to_mut().push_str(&rhs);
437         }
438     }
439 }