]> git.lizzy.rs Git - rust.git/blob - src/liballoc/borrow.rs
Separate codepaths for fat and thin LTO in write.rs
[rust.git] / src / liballoc / borrow.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! A module for working with borrowed data.
12
13 #![stable(feature = "rust1", since = "1.0.0")]
14
15 use core::cmp::Ordering;
16 use core::hash::{Hash, Hasher};
17 use core::ops::{Add, AddAssign, Deref};
18
19 use fmt;
20 use string::String;
21
22 use self::Cow::*;
23
24 #[stable(feature = "rust1", since = "1.0.0")]
25 pub use core::borrow::{Borrow, BorrowMut};
26
27 #[stable(feature = "rust1", since = "1.0.0")]
28 impl<'a, B: ?Sized> Borrow<B> for Cow<'a, B>
29     where B: ToOwned,
30           <B as ToOwned>::Owned: 'a
31 {
32     fn borrow(&self) -> &B {
33         &**self
34     }
35 }
36
37 /// A generalization of `Clone` to borrowed data.
38 ///
39 /// Some types make it possible to go from borrowed to owned, usually by
40 /// implementing the `Clone` trait. But `Clone` works only for going from `&T`
41 /// to `T`. The `ToOwned` trait generalizes `Clone` to construct owned data
42 /// from any borrow of a given type.
43 #[stable(feature = "rust1", since = "1.0.0")]
44 pub trait ToOwned {
45     #[stable(feature = "rust1", since = "1.0.0")]
46     type Owned: Borrow<Self>;
47
48     /// Creates owned data from borrowed data, usually by cloning.
49     ///
50     /// # Examples
51     ///
52     /// Basic usage:
53     ///
54     /// ```
55     /// let s: &str = "a";
56     /// let ss: String = s.to_owned();
57     ///
58     /// let v: &[i32] = &[1, 2];
59     /// let vv: Vec<i32> = v.to_owned();
60     /// ```
61     #[stable(feature = "rust1", since = "1.0.0")]
62     #[must_use = "cloning is often expensive and is not expected to have side effects"]
63     fn to_owned(&self) -> Self::Owned;
64
65     /// Uses borrowed data to replace owned data, usually by cloning.
66     ///
67     /// This is borrow-generalized version of `Clone::clone_from`.
68     ///
69     /// # Examples
70     ///
71     /// Basic usage:
72     ///
73     /// ```
74     /// # #![feature(toowned_clone_into)]
75     /// let mut s: String = String::new();
76     /// "hello".clone_into(&mut s);
77     ///
78     /// let mut v: Vec<i32> = Vec::new();
79     /// [1, 2][..].clone_into(&mut v);
80     /// ```
81     #[unstable(feature = "toowned_clone_into",
82                reason = "recently added",
83                issue = "41263")]
84     fn clone_into(&self, target: &mut Self::Owned) {
85         *target = self.to_owned();
86     }
87 }
88
89 #[stable(feature = "rust1", since = "1.0.0")]
90 impl<T> ToOwned for T
91     where T: Clone
92 {
93     type Owned = T;
94     fn to_owned(&self) -> T {
95         self.clone()
96     }
97
98     fn clone_into(&self, target: &mut T) {
99         target.clone_from(self);
100     }
101 }
102
103 /// A clone-on-write smart pointer.
104 ///
105 /// The type `Cow` is a smart pointer providing clone-on-write functionality: it
106 /// can enclose and provide immutable access to borrowed data, and clone the
107 /// data lazily when mutation or ownership is required. The type is designed to
108 /// work with general borrowed data via the `Borrow` trait.
109 ///
110 /// `Cow` implements `Deref`, which means that you can call
111 /// non-mutating methods directly on the data it encloses. If mutation
112 /// is desired, `to_mut` will obtain a mutable reference to an owned
113 /// value, cloning if necessary.
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, ToOwned};
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 B: ToOwned
182 {
183     /// Borrowed data.
184     #[stable(feature = "rust1", since = "1.0.0")]
185     Borrowed(#[stable(feature = "rust1", since = "1.0.0")]
186              &'a B),
187
188     /// Owned data.
189     #[stable(feature = "rust1", since = "1.0.0")]
190     Owned(#[stable(feature = "rust1", since = "1.0.0")]
191           <B as ToOwned>::Owned),
192 }
193
194 #[stable(feature = "rust1", since = "1.0.0")]
195 impl<'a, B: ?Sized> Clone for Cow<'a, B>
196     where B: ToOwned
197 {
198     fn clone(&self) -> Cow<'a, B> {
199         match *self {
200             Borrowed(b) => Borrowed(b),
201             Owned(ref o) => {
202                 let b: &B = o.borrow();
203                 Owned(b.to_owned())
204             }
205         }
206     }
207
208     fn clone_from(&mut self, source: &Cow<'a, B>) {
209         if let Owned(ref mut dest) = *self {
210             if let Owned(ref o) = *source {
211                 o.borrow().clone_into(dest);
212                 return;
213             }
214         }
215
216         *self = source.clone();
217     }
218 }
219
220 impl<'a, B: ?Sized> Cow<'a, B>
221     where B: ToOwned
222 {
223     /// Acquires a mutable reference to the owned form of the data.
224     ///
225     /// Clones the data if it is not already owned.
226     ///
227     /// # Examples
228     ///
229     /// ```
230     /// use std::borrow::Cow;
231     ///
232     /// let mut cow = Cow::Borrowed("foo");
233     /// cow.to_mut().make_ascii_uppercase();
234     ///
235     /// assert_eq!(
236     ///   cow,
237     ///   Cow::Owned(String::from("FOO")) as Cow<str>
238     /// );
239     /// ```
240     #[stable(feature = "rust1", since = "1.0.0")]
241     pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned {
242         match *self {
243             Borrowed(borrowed) => {
244                 *self = Owned(borrowed.to_owned());
245                 match *self {
246                     Borrowed(..) => unreachable!(),
247                     Owned(ref mut owned) => owned,
248                 }
249             }
250             Owned(ref mut owned) => owned,
251         }
252     }
253
254     /// Extracts the owned data.
255     ///
256     /// Clones the data if it is not already owned.
257     ///
258     /// # Examples
259     ///
260     /// Calling `into_owned` on a `Cow::Borrowed` clones the underlying data
261     /// and becomes a `Cow::Owned`:
262     ///
263     /// ```
264     /// use std::borrow::Cow;
265     ///
266     /// let s = "Hello world!";
267     /// let cow = Cow::Borrowed(s);
268     ///
269     /// assert_eq!(
270     ///   cow.into_owned(),
271     ///   String::from(s)
272     /// );
273     /// ```
274     ///
275     /// Calling `into_owned` on a `Cow::Owned` is a no-op:
276     ///
277     /// ```
278     /// use std::borrow::Cow;
279     ///
280     /// let s = "Hello world!";
281     /// let cow: Cow<str> = Cow::Owned(String::from(s));
282     ///
283     /// assert_eq!(
284     ///   cow.into_owned(),
285     ///   String::from(s)
286     /// );
287     /// ```
288     #[stable(feature = "rust1", since = "1.0.0")]
289     pub fn into_owned(self) -> <B as ToOwned>::Owned {
290         match self {
291             Borrowed(borrowed) => borrowed.to_owned(),
292             Owned(owned) => owned,
293         }
294     }
295 }
296
297 #[stable(feature = "rust1", since = "1.0.0")]
298 impl<'a, B: ?Sized> Deref for Cow<'a, B>
299     where B: ToOwned
300 {
301     type Target = B;
302
303     fn deref(&self) -> &B {
304         match *self {
305             Borrowed(borrowed) => borrowed,
306             Owned(ref owned) => owned.borrow(),
307         }
308     }
309 }
310
311 #[stable(feature = "rust1", since = "1.0.0")]
312 impl<'a, B: ?Sized> Eq for Cow<'a, B> where B: Eq + ToOwned {}
313
314 #[stable(feature = "rust1", since = "1.0.0")]
315 impl<'a, B: ?Sized> Ord for Cow<'a, B>
316     where B: Ord + ToOwned
317 {
318     #[inline]
319     fn cmp(&self, other: &Cow<'a, B>) -> Ordering {
320         Ord::cmp(&**self, &**other)
321     }
322 }
323
324 #[stable(feature = "rust1", since = "1.0.0")]
325 impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, C>> for Cow<'a, B>
326     where B: PartialEq<C> + ToOwned,
327           C: ToOwned
328 {
329     #[inline]
330     fn eq(&self, other: &Cow<'b, C>) -> bool {
331         PartialEq::eq(&**self, &**other)
332     }
333 }
334
335 #[stable(feature = "rust1", since = "1.0.0")]
336 impl<'a, B: ?Sized> PartialOrd for Cow<'a, B>
337     where B: PartialOrd + ToOwned
338 {
339     #[inline]
340     fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering> {
341         PartialOrd::partial_cmp(&**self, &**other)
342     }
343 }
344
345 #[stable(feature = "rust1", since = "1.0.0")]
346 impl<'a, B: ?Sized> fmt::Debug for Cow<'a, B>
347     where B: fmt::Debug + ToOwned,
348           <B as ToOwned>::Owned: fmt::Debug
349 {
350     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
351         match *self {
352             Borrowed(ref b) => fmt::Debug::fmt(b, f),
353             Owned(ref o) => fmt::Debug::fmt(o, f),
354         }
355     }
356 }
357
358 #[stable(feature = "rust1", since = "1.0.0")]
359 impl<'a, B: ?Sized> fmt::Display for Cow<'a, B>
360     where B: fmt::Display + ToOwned,
361           <B as ToOwned>::Owned: fmt::Display
362 {
363     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
364         match *self {
365             Borrowed(ref b) => fmt::Display::fmt(b, f),
366             Owned(ref o) => fmt::Display::fmt(o, f),
367         }
368     }
369 }
370
371 #[stable(feature = "default", since = "1.11.0")]
372 impl<'a, B: ?Sized> Default for Cow<'a, B>
373     where B: ToOwned,
374           <B as ToOwned>::Owned: Default
375 {
376     /// Creates an owned Cow<'a, B> with the default value for the contained owned value.
377     fn default() -> Cow<'a, B> {
378         Owned(<B as ToOwned>::Owned::default())
379     }
380 }
381
382 #[stable(feature = "rust1", since = "1.0.0")]
383 impl<'a, B: ?Sized> Hash for Cow<'a, B>
384     where B: Hash + ToOwned
385 {
386     #[inline]
387     fn hash<H: Hasher>(&self, state: &mut H) {
388         Hash::hash(&**self, state)
389     }
390 }
391
392 #[stable(feature = "rust1", since = "1.0.0")]
393 #[allow(deprecated)]
394 impl<'a, T: ?Sized + ToOwned> AsRef<T> for Cow<'a, T> {
395     fn as_ref(&self) -> &T {
396         self
397     }
398 }
399
400 #[stable(feature = "cow_add", since = "1.14.0")]
401 impl<'a> Add<&'a str> for Cow<'a, str> {
402     type Output = Cow<'a, str>;
403
404     #[inline]
405     fn add(mut self, rhs: &'a str) -> Self::Output {
406         self += rhs;
407         self
408     }
409 }
410
411 #[stable(feature = "cow_add", since = "1.14.0")]
412 impl<'a> Add<Cow<'a, str>> for Cow<'a, str> {
413     type Output = Cow<'a, str>;
414
415     #[inline]
416     fn add(mut self, rhs: Cow<'a, str>) -> Self::Output {
417         self += rhs;
418         self
419     }
420 }
421
422 #[stable(feature = "cow_add", since = "1.14.0")]
423 impl<'a> AddAssign<&'a str> for Cow<'a, str> {
424     fn add_assign(&mut self, rhs: &'a str) {
425         if self.is_empty() {
426             *self = Cow::Borrowed(rhs)
427         } else if rhs.is_empty() {
428             return;
429         } else {
430             if let Cow::Borrowed(lhs) = *self {
431                 let mut s = String::with_capacity(lhs.len() + rhs.len());
432                 s.push_str(lhs);
433                 *self = Cow::Owned(s);
434             }
435             self.to_mut().push_str(rhs);
436         }
437     }
438 }
439
440 #[stable(feature = "cow_add", since = "1.14.0")]
441 impl<'a> AddAssign<Cow<'a, str>> for Cow<'a, str> {
442     fn add_assign(&mut self, rhs: Cow<'a, str>) {
443         if self.is_empty() {
444             *self = rhs
445         } else if rhs.is_empty() {
446             return;
447         } else {
448             if let Cow::Borrowed(lhs) = *self {
449                 let mut s = String::with_capacity(lhs.len() + rhs.len());
450                 s.push_str(lhs);
451                 *self = Cow::Owned(s);
452             }
453             self.to_mut().push_str(&rhs);
454         }
455     }
456 }