]> git.lizzy.rs Git - rust.git/blob - src/liballoc/borrow.rs
Add #[must_use] to a few standard library methods
[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 #[stable(feature = "rust1", since = "1.0.0")]
145 pub enum Cow<'a, B: ?Sized + 'a>
146     where B: ToOwned
147 {
148     /// Borrowed data.
149     #[stable(feature = "rust1", since = "1.0.0")]
150     Borrowed(#[stable(feature = "rust1", since = "1.0.0")]
151              &'a B),
152
153     /// Owned data.
154     #[stable(feature = "rust1", since = "1.0.0")]
155     Owned(#[stable(feature = "rust1", since = "1.0.0")]
156           <B as ToOwned>::Owned),
157 }
158
159 #[stable(feature = "rust1", since = "1.0.0")]
160 impl<'a, B: ?Sized> Clone for Cow<'a, B>
161     where B: ToOwned
162 {
163     fn clone(&self) -> Cow<'a, B> {
164         match *self {
165             Borrowed(b) => Borrowed(b),
166             Owned(ref o) => {
167                 let b: &B = o.borrow();
168                 Owned(b.to_owned())
169             }
170         }
171     }
172
173     fn clone_from(&mut self, source: &Cow<'a, B>) {
174         if let Owned(ref mut dest) = *self {
175             if let Owned(ref o) = *source {
176                 o.borrow().clone_into(dest);
177                 return;
178             }
179         }
180
181         *self = source.clone();
182     }
183 }
184
185 impl<'a, B: ?Sized> Cow<'a, B>
186     where B: ToOwned
187 {
188     /// Acquires a mutable reference to the owned form of the data.
189     ///
190     /// Clones the data if it is not already owned.
191     ///
192     /// # Examples
193     ///
194     /// ```
195     /// use std::borrow::Cow;
196     ///
197     /// let mut cow = Cow::Borrowed("foo");
198     /// cow.to_mut().make_ascii_uppercase();
199     ///
200     /// assert_eq!(
201     ///   cow,
202     ///   Cow::Owned(String::from("FOO")) as Cow<str>
203     /// );
204     /// ```
205     #[stable(feature = "rust1", since = "1.0.0")]
206     pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned {
207         match *self {
208             Borrowed(borrowed) => {
209                 *self = Owned(borrowed.to_owned());
210                 match *self {
211                     Borrowed(..) => unreachable!(),
212                     Owned(ref mut owned) => owned,
213                 }
214             }
215             Owned(ref mut owned) => owned,
216         }
217     }
218
219     /// Extracts the owned data.
220     ///
221     /// Clones the data if it is not already owned.
222     ///
223     /// # Examples
224     ///
225     /// Calling `into_owned` on a `Cow::Borrowed` clones the underlying data
226     /// and becomes a `Cow::Owned`:
227     ///
228     /// ```
229     /// use std::borrow::Cow;
230     ///
231     /// let s = "Hello world!";
232     /// let cow = Cow::Borrowed(s);
233     ///
234     /// assert_eq!(
235     ///   cow.into_owned(),
236     ///   String::from(s)
237     /// );
238     /// ```
239     ///
240     /// Calling `into_owned` on a `Cow::Owned` is a no-op:
241     ///
242     /// ```
243     /// use std::borrow::Cow;
244     ///
245     /// let s = "Hello world!";
246     /// let cow: Cow<str> = Cow::Owned(String::from(s));
247     ///
248     /// assert_eq!(
249     ///   cow.into_owned(),
250     ///   String::from(s)
251     /// );
252     /// ```
253     #[stable(feature = "rust1", since = "1.0.0")]
254     pub fn into_owned(self) -> <B as ToOwned>::Owned {
255         match self {
256             Borrowed(borrowed) => borrowed.to_owned(),
257             Owned(owned) => owned,
258         }
259     }
260 }
261
262 #[stable(feature = "rust1", since = "1.0.0")]
263 impl<'a, B: ?Sized> Deref for Cow<'a, B>
264     where B: ToOwned
265 {
266     type Target = B;
267
268     fn deref(&self) -> &B {
269         match *self {
270             Borrowed(borrowed) => borrowed,
271             Owned(ref owned) => owned.borrow(),
272         }
273     }
274 }
275
276 #[stable(feature = "rust1", since = "1.0.0")]
277 impl<'a, B: ?Sized> Eq for Cow<'a, B> where B: Eq + ToOwned {}
278
279 #[stable(feature = "rust1", since = "1.0.0")]
280 impl<'a, B: ?Sized> Ord for Cow<'a, B>
281     where B: Ord + ToOwned
282 {
283     #[inline]
284     fn cmp(&self, other: &Cow<'a, B>) -> Ordering {
285         Ord::cmp(&**self, &**other)
286     }
287 }
288
289 #[stable(feature = "rust1", since = "1.0.0")]
290 impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, C>> for Cow<'a, B>
291     where B: PartialEq<C> + ToOwned,
292           C: ToOwned
293 {
294     #[inline]
295     fn eq(&self, other: &Cow<'b, C>) -> bool {
296         PartialEq::eq(&**self, &**other)
297     }
298 }
299
300 #[stable(feature = "rust1", since = "1.0.0")]
301 impl<'a, B: ?Sized> PartialOrd for Cow<'a, B>
302     where B: PartialOrd + ToOwned
303 {
304     #[inline]
305     fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering> {
306         PartialOrd::partial_cmp(&**self, &**other)
307     }
308 }
309
310 #[stable(feature = "rust1", since = "1.0.0")]
311 impl<'a, B: ?Sized> fmt::Debug for Cow<'a, B>
312     where B: fmt::Debug + ToOwned,
313           <B as ToOwned>::Owned: fmt::Debug
314 {
315     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
316         match *self {
317             Borrowed(ref b) => fmt::Debug::fmt(b, f),
318             Owned(ref o) => fmt::Debug::fmt(o, f),
319         }
320     }
321 }
322
323 #[stable(feature = "rust1", since = "1.0.0")]
324 impl<'a, B: ?Sized> fmt::Display for Cow<'a, B>
325     where B: fmt::Display + ToOwned,
326           <B as ToOwned>::Owned: fmt::Display
327 {
328     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
329         match *self {
330             Borrowed(ref b) => fmt::Display::fmt(b, f),
331             Owned(ref o) => fmt::Display::fmt(o, f),
332         }
333     }
334 }
335
336 #[stable(feature = "default", since = "1.11.0")]
337 impl<'a, B: ?Sized> Default for Cow<'a, B>
338     where B: ToOwned,
339           <B as ToOwned>::Owned: Default
340 {
341     /// Creates an owned Cow<'a, B> with the default value for the contained owned value.
342     fn default() -> Cow<'a, B> {
343         Owned(<B as ToOwned>::Owned::default())
344     }
345 }
346
347 #[stable(feature = "rust1", since = "1.0.0")]
348 impl<'a, B: ?Sized> Hash for Cow<'a, B>
349     where B: Hash + ToOwned
350 {
351     #[inline]
352     fn hash<H: Hasher>(&self, state: &mut H) {
353         Hash::hash(&**self, state)
354     }
355 }
356
357 #[stable(feature = "rust1", since = "1.0.0")]
358 #[allow(deprecated)]
359 impl<'a, T: ?Sized + ToOwned> AsRef<T> for Cow<'a, T> {
360     fn as_ref(&self) -> &T {
361         self
362     }
363 }
364
365 #[stable(feature = "cow_add", since = "1.14.0")]
366 impl<'a> Add<&'a str> for Cow<'a, str> {
367     type Output = Cow<'a, str>;
368
369     #[inline]
370     fn add(mut self, rhs: &'a str) -> Self::Output {
371         self += rhs;
372         self
373     }
374 }
375
376 #[stable(feature = "cow_add", since = "1.14.0")]
377 impl<'a> Add<Cow<'a, str>> for Cow<'a, str> {
378     type Output = Cow<'a, str>;
379
380     #[inline]
381     fn add(mut self, rhs: Cow<'a, str>) -> Self::Output {
382         self += rhs;
383         self
384     }
385 }
386
387 #[stable(feature = "cow_add", since = "1.14.0")]
388 impl<'a> AddAssign<&'a str> for Cow<'a, str> {
389     fn add_assign(&mut self, rhs: &'a str) {
390         if self.is_empty() {
391             *self = Cow::Borrowed(rhs)
392         } else if rhs.is_empty() {
393             return;
394         } else {
395             if let Cow::Borrowed(lhs) = *self {
396                 let mut s = String::with_capacity(lhs.len() + rhs.len());
397                 s.push_str(lhs);
398                 *self = Cow::Owned(s);
399             }
400             self.to_mut().push_str(rhs);
401         }
402     }
403 }
404
405 #[stable(feature = "cow_add", since = "1.14.0")]
406 impl<'a> AddAssign<Cow<'a, str>> for Cow<'a, str> {
407     fn add_assign(&mut self, rhs: Cow<'a, str>) {
408         if self.is_empty() {
409             *self = 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 }