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