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