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.
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.
11 //! A module for working with borrowed data.
13 #![stable(feature = "rust1", since = "1.0.0")]
15 use core::cmp::Ordering;
16 use core::hash::{Hash, Hasher};
17 use core::ops::{Add, AddAssign, Deref};
23 #[stable(feature = "rust1", since = "1.0.0")]
24 pub use core::borrow::{Borrow, BorrowMut};
26 #[stable(feature = "rust1", since = "1.0.0")]
27 impl<'a, B: ?Sized> Borrow<B> for Cow<'a, B>
29 <B as ToOwned>::Owned: 'a
31 fn borrow(&self) -> &B {
36 /// A generalization of `Clone` to borrowed data.
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")]
44 #[stable(feature = "rust1", since = "1.0.0")]
45 type Owned: Borrow<Self>;
47 /// Creates owned data from borrowed data, usually by cloning.
54 /// let s = "a"; // &str
55 /// let ss = s.to_owned(); // String
57 /// let v = &[1, 2]; // slice
58 /// let vv = v.to_owned(); // Vec
60 #[stable(feature = "rust1", since = "1.0.0")]
61 fn to_owned(&self) -> Self::Owned;
64 #[stable(feature = "rust1", since = "1.0.0")]
65 impl<T> ToOwned for T where T: Clone {
67 fn to_owned(&self) -> T {
72 /// A clone-on-write smart pointer.
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.
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.
87 /// use std::borrow::Cow;
89 /// fn abs_all(input: &mut Cow<[i32]>) {
90 /// for i in 0..input.len() {
93 /// // Clones into a vector if not already owned.
94 /// input.to_mut()[i] = -v;
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);
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);
109 /// // No clone occurs because `input` is already owned.
110 /// let mut input = Cow::from(vec![-1, 0, 1]);
111 /// abs_all(&mut input);
113 #[stable(feature = "rust1", since = "1.0.0")]
114 pub enum Cow<'a, B: ?Sized + 'a>
118 #[stable(feature = "rust1", since = "1.0.0")]
119 Borrowed(#[stable(feature = "rust1", since = "1.0.0")] &'a B),
122 #[stable(feature = "rust1", since = "1.0.0")]
124 #[stable(feature = "rust1", since = "1.0.0")] <B as ToOwned>::Owned
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> {
132 Borrowed(b) => Borrowed(b),
134 let b: &B = o.borrow();
141 impl<'a, B: ?Sized> Cow<'a, B> where B: ToOwned {
142 /// Acquires a mutable reference to the owned form of the data.
144 /// Clones the data if it is not already owned.
149 /// use std::borrow::Cow;
151 /// let mut cow: Cow<[_]> = Cow::Owned(vec![1, 2, 3]);
153 /// let hello = cow.to_mut();
155 /// assert_eq!(hello, &[1, 2, 3]);
157 #[stable(feature = "rust1", since = "1.0.0")]
158 pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned {
160 Borrowed(borrowed) => {
161 *self = Owned(borrowed.to_owned());
164 Owned(ref mut owned) => owned,
168 /// Extracts the owned data.
170 /// Clones the data if it is not already owned.
175 /// use std::borrow::Cow;
177 /// let cow: Cow<[_]> = Cow::Owned(vec![1, 2, 3]);
179 /// let hello = cow.into_owned();
181 /// assert_eq!(vec![1, 2, 3], hello);
183 #[stable(feature = "rust1", since = "1.0.0")]
184 pub fn into_owned(self) -> <B as ToOwned>::Owned {
186 Borrowed(borrowed) => borrowed.to_owned(),
187 Owned(owned) => owned,
192 #[stable(feature = "rust1", since = "1.0.0")]
193 impl<'a, B: ?Sized> Deref for Cow<'a, B> where B: ToOwned {
196 fn deref(&self) -> &B {
198 Borrowed(borrowed) => borrowed,
199 Owned(ref owned) => owned.borrow(),
204 #[stable(feature = "rust1", since = "1.0.0")]
205 impl<'a, B: ?Sized> Eq for Cow<'a, B> where B: Eq + ToOwned {}
207 #[stable(feature = "rust1", since = "1.0.0")]
208 impl<'a, B: ?Sized> Ord for Cow<'a, B> where B: Ord + ToOwned {
210 fn cmp(&self, other: &Cow<'a, B>) -> Ordering {
211 Ord::cmp(&**self, &**other)
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,
221 fn eq(&self, other: &Cow<'b, C>) -> bool {
222 PartialEq::eq(&**self, &**other)
226 #[stable(feature = "rust1", since = "1.0.0")]
227 impl<'a, B: ?Sized> PartialOrd for Cow<'a, B> where B: PartialOrd + ToOwned {
229 fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering> {
230 PartialOrd::partial_cmp(&**self, &**other)
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
239 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
241 Borrowed(ref b) => fmt::Debug::fmt(b, f),
242 Owned(ref o) => fmt::Debug::fmt(o, f),
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
252 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
254 Borrowed(ref b) => fmt::Display::fmt(b, f),
255 Owned(ref o) => fmt::Display::fmt(o, f),
260 #[stable(feature = "default", since = "1.11.0")]
261 impl<'a, B: ?Sized> Default for Cow<'a, B>
263 <B as ToOwned>::Owned: Default
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())
271 #[stable(feature = "rust1", since = "1.0.0")]
272 impl<'a, B: ?Sized> Hash for Cow<'a, B> where B: Hash + ToOwned {
274 fn hash<H: Hasher>(&self, state: &mut H) {
275 Hash::hash(&**self, state)
279 #[stable(feature = "rust1", since = "1.0.0")]
281 impl<'a, T: ?Sized + ToOwned> AsRef<T> for Cow<'a, T> {
282 fn as_ref(&self) -> &T {
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>;
291 fn add(self, rhs: &'a str) -> Self {
294 } else if rhs == "" {
297 Cow::Owned(self.into_owned() + rhs)
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>;
306 fn add(self, rhs: Cow<'a, str>) -> Self {
309 } else if rhs == "" {
312 Cow::Owned(self.into_owned() + rhs.borrow())
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);
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());