]> git.lizzy.rs Git - rust.git/blob - src/libcollections/borrow.rs
8f9c35783379133e98a31bc58c9d1c086d0e936e
[rust.git] / src / libcollections / 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
21 use self::Cow::*;
22
23 #[stable(feature = "rust1", since = "1.0.0")]
24 pub use core::borrow::{Borrow, BorrowMut};
25
26 #[stable(feature = "rust1", since = "1.0.0")]
27 impl<'a, B: ?Sized> Borrow<B> for Cow<'a, B>
28     where B: ToOwned,
29           <B as ToOwned>::Owned: 'a
30 {
31     fn borrow(&self) -> &B {
32         &**self
33     }
34 }
35
36 /// A generalization of `Clone` to borrowed data.
37 ///
38 /// Some types make it possible to go from borrowed to owned, usually by
39 /// implementing the `Clone` trait. But `Clone` works only for going from `&T`
40 /// to `T`. The `ToOwned` trait generalizes `Clone` to construct owned data
41 /// from any borrow of a given type.
42 #[stable(feature = "rust1", since = "1.0.0")]
43 pub trait ToOwned {
44     #[stable(feature = "rust1", since = "1.0.0")]
45     type Owned: Borrow<Self>;
46
47     /// Creates owned data from borrowed data, usually by cloning.
48     ///
49     /// # Examples
50     ///
51     /// Basic usage:
52     ///
53     /// ```
54     /// let s = "a"; // &str
55     /// let ss = s.to_owned(); // String
56     ///
57     /// let v = &[1, 2]; // slice
58     /// let vv = v.to_owned(); // Vec
59     /// ```
60     #[stable(feature = "rust1", since = "1.0.0")]
61     fn to_owned(&self) -> Self::Owned;
62 }
63
64 #[stable(feature = "rust1", since = "1.0.0")]
65 impl<T> ToOwned for T where T: Clone {
66     type Owned = T;
67     fn to_owned(&self) -> T {
68         self.clone()
69     }
70 }
71
72 /// A clone-on-write smart pointer.
73 ///
74 /// The type `Cow` is a smart pointer providing clone-on-write functionality: it
75 /// can enclose and provide immutable access to borrowed data, and clone the
76 /// data lazily when mutation or ownership is required. The type is designed to
77 /// work with general borrowed data via the `Borrow` trait.
78 ///
79 /// `Cow` implements `Deref`, which means that you can call
80 /// non-mutating methods directly on the data it encloses. If mutation
81 /// is desired, `to_mut` will obtain a mutable reference to an owned
82 /// value, cloning if necessary.
83 ///
84 /// # Examples
85 ///
86 /// ```
87 /// use std::borrow::Cow;
88 ///
89 /// fn abs_all(input: &mut Cow<[i32]>) {
90 ///     for i in 0..input.len() {
91 ///         let v = input[i];
92 ///         if v < 0 {
93 ///             // Clones into a vector if not already owned.
94 ///             input.to_mut()[i] = -v;
95 ///         }
96 ///     }
97 /// }
98 ///
99 /// // No clone occurs because `input` doesn't need to be mutated.
100 /// let slice = [0, 1, 2];
101 /// let mut input = Cow::from(&slice[..]);
102 /// abs_all(&mut input);
103 ///
104 /// // Clone occurs because `input` needs to be mutated.
105 /// let slice = [-1, 0, 1];
106 /// let mut input = Cow::from(&slice[..]);
107 /// abs_all(&mut input);
108 ///
109 /// // No clone occurs because `input` is already owned.
110 /// let mut input = Cow::from(vec![-1, 0, 1]);
111 /// abs_all(&mut input);
112 /// ```
113 #[stable(feature = "rust1", since = "1.0.0")]
114 pub enum Cow<'a, B: ?Sized + 'a>
115     where B: ToOwned
116 {
117     /// Borrowed data.
118     #[stable(feature = "rust1", since = "1.0.0")]
119     Borrowed(#[stable(feature = "rust1", since = "1.0.0")] &'a B),
120
121     /// Owned data.
122     #[stable(feature = "rust1", since = "1.0.0")]
123     Owned(
124         #[stable(feature = "rust1", since = "1.0.0")] <B as ToOwned>::Owned
125     ),
126 }
127
128 #[stable(feature = "rust1", since = "1.0.0")]
129 impl<'a, B: ?Sized> Clone for Cow<'a, B> where B: ToOwned {
130     fn clone(&self) -> Cow<'a, B> {
131         match *self {
132             Borrowed(b) => Borrowed(b),
133             Owned(ref o) => {
134                 let b: &B = o.borrow();
135                 Owned(b.to_owned())
136             }
137         }
138     }
139 }
140
141 impl<'a, B: ?Sized> Cow<'a, B> where B: ToOwned {
142     /// Acquires a mutable reference to the owned form of the data.
143     ///
144     /// Clones the data if it is not already owned.
145     ///
146     /// # Examples
147     ///
148     /// ```
149     /// use std::borrow::Cow;
150     ///
151     /// let mut cow: Cow<[_]> = Cow::Owned(vec![1, 2, 3]);
152     ///
153     /// let hello = cow.to_mut();
154     ///
155     /// assert_eq!(hello, &[1, 2, 3]);
156     /// ```
157     #[stable(feature = "rust1", since = "1.0.0")]
158     pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned {
159         match *self {
160             Borrowed(borrowed) => {
161                 *self = Owned(borrowed.to_owned());
162                 self.to_mut()
163             }
164             Owned(ref mut owned) => owned,
165         }
166     }
167
168     /// Extracts the owned data.
169     ///
170     /// Clones the data if it is not already owned.
171     ///
172     /// # Examples
173     ///
174     /// ```
175     /// use std::borrow::Cow;
176     ///
177     /// let cow: Cow<[_]> = Cow::Owned(vec![1, 2, 3]);
178     ///
179     /// let hello = cow.into_owned();
180     ///
181     /// assert_eq!(vec![1, 2, 3], hello);
182     /// ```
183     #[stable(feature = "rust1", since = "1.0.0")]
184     pub fn into_owned(self) -> <B as ToOwned>::Owned {
185         match self {
186             Borrowed(borrowed) => borrowed.to_owned(),
187             Owned(owned) => owned,
188         }
189     }
190 }
191
192 #[stable(feature = "rust1", since = "1.0.0")]
193 impl<'a, B: ?Sized> Deref for Cow<'a, B> where B: ToOwned {
194     type Target = B;
195
196     fn deref(&self) -> &B {
197         match *self {
198             Borrowed(borrowed) => borrowed,
199             Owned(ref owned) => owned.borrow(),
200         }
201     }
202 }
203
204 #[stable(feature = "rust1", since = "1.0.0")]
205 impl<'a, B: ?Sized> Eq for Cow<'a, B> where B: Eq + ToOwned {}
206
207 #[stable(feature = "rust1", since = "1.0.0")]
208 impl<'a, B: ?Sized> Ord for Cow<'a, B> where B: Ord + ToOwned {
209     #[inline]
210     fn cmp(&self, other: &Cow<'a, B>) -> Ordering {
211         Ord::cmp(&**self, &**other)
212     }
213 }
214
215 #[stable(feature = "rust1", since = "1.0.0")]
216 impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, C>> for Cow<'a, B>
217     where B: PartialEq<C> + ToOwned,
218           C: ToOwned
219 {
220     #[inline]
221     fn eq(&self, other: &Cow<'b, C>) -> bool {
222         PartialEq::eq(&**self, &**other)
223     }
224 }
225
226 #[stable(feature = "rust1", since = "1.0.0")]
227 impl<'a, B: ?Sized> PartialOrd for Cow<'a, B> where B: PartialOrd + ToOwned {
228     #[inline]
229     fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering> {
230         PartialOrd::partial_cmp(&**self, &**other)
231     }
232 }
233
234 #[stable(feature = "rust1", since = "1.0.0")]
235 impl<'a, B: ?Sized> fmt::Debug for Cow<'a, B>
236     where B: fmt::Debug + ToOwned,
237           <B as ToOwned>::Owned: fmt::Debug
238 {
239     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
240         match *self {
241             Borrowed(ref b) => fmt::Debug::fmt(b, f),
242             Owned(ref o) => fmt::Debug::fmt(o, f),
243         }
244     }
245 }
246
247 #[stable(feature = "rust1", since = "1.0.0")]
248 impl<'a, B: ?Sized> fmt::Display for Cow<'a, B>
249     where B: fmt::Display + ToOwned,
250           <B as ToOwned>::Owned: fmt::Display
251 {
252     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
253         match *self {
254             Borrowed(ref b) => fmt::Display::fmt(b, f),
255             Owned(ref o) => fmt::Display::fmt(o, f),
256         }
257     }
258 }
259
260 #[stable(feature = "default", since = "1.11.0")]
261 impl<'a, B: ?Sized> Default for Cow<'a, B>
262     where B: ToOwned,
263           <B as ToOwned>::Owned: Default
264 {
265     /// Creates an owned Cow<'a, B> with the default value for the contained owned value.
266     fn default() -> Cow<'a, B> {
267         Owned(<B as ToOwned>::Owned::default())
268     }
269 }
270
271 #[stable(feature = "rust1", since = "1.0.0")]
272 impl<'a, B: ?Sized> Hash for Cow<'a, B> where B: Hash + ToOwned {
273     #[inline]
274     fn hash<H: Hasher>(&self, state: &mut H) {
275         Hash::hash(&**self, state)
276     }
277 }
278
279 #[stable(feature = "rust1", since = "1.0.0")]
280 #[allow(deprecated)]
281 impl<'a, T: ?Sized + ToOwned> AsRef<T> for Cow<'a, T> {
282     fn as_ref(&self) -> &T {
283         self
284     }
285 }
286
287 #[stable(feature = "cow_add", since = "1.13.0")]
288 impl<'a> Add<&'a str> for Cow<'a, str> {
289     type Output = Cow<'a, str>;
290
291     fn add(self, rhs: &'a str) -> Self {
292         if self == "" {
293             Cow::Borrowed(rhs)
294         } else if rhs == "" {
295             self
296         } else {
297             Cow::Owned(self.into_owned() + rhs)
298         }
299     }
300 }
301
302 #[stable(feature = "cow_add", since = "1.13.0")]
303 impl<'a> Add<Cow<'a, str>> for Cow<'a, str> {
304     type Output = Cow<'a, str>;
305
306     fn add(self, rhs: Cow<'a, str>) -> Self {
307         if self == "" {
308             rhs
309         } else if rhs == "" {
310             self
311         } else {
312             Cow::Owned(self.into_owned() + rhs.borrow())
313         }
314     }
315 }
316
317 #[stable(feature = "cow_add", since = "1.13.0")]
318 impl<'a> AddAssign<&'a str> for Cow<'a, str> {
319     fn add_assign(&mut self, rhs: &'a str) {
320         if rhs == "" { return; }
321         self.to_mut().push_str(rhs);
322     }
323 }
324
325 #[stable(feature = "cow_add", since = "1.13.0")]
326 impl<'a> AddAssign<Cow<'a, str>> for Cow<'a, str> {
327     fn add_assign(&mut self, rhs: Cow<'a, str>) {
328         if rhs == "" { return; }
329         self.to_mut().push_str(rhs.borrow());
330     }
331 }