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};
24 #[stable(feature = "rust1", since = "1.0.0")]
25 pub use core::borrow::{Borrow, BorrowMut};
27 #[stable(feature = "rust1", since = "1.0.0")]
28 impl<'a, B: ?Sized> Borrow<B> for Cow<'a, B>
30 <B as ToOwned>::Owned: 'a
32 fn borrow(&self) -> &B {
37 /// A generalization of `Clone` to borrowed data.
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")]
45 #[stable(feature = "rust1", since = "1.0.0")]
46 type Owned: Borrow<Self>;
48 /// Creates owned data from borrowed data, usually by cloning.
55 /// let s: &str = "a";
56 /// let ss: String = s.to_owned();
58 /// let v: &[i32] = &[1, 2];
59 /// let vv: Vec<i32> = v.to_owned();
61 #[stable(feature = "rust1", since = "1.0.0")]
62 fn to_owned(&self) -> Self::Owned;
65 #[stable(feature = "rust1", since = "1.0.0")]
70 fn to_owned(&self) -> T {
75 /// A clone-on-write smart pointer.
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.
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.
90 /// use std::borrow::Cow;
92 /// fn abs_all(input: &mut Cow<[i32]>) {
93 /// for i in 0..input.len() {
96 /// // Clones into a vector if not already owned.
97 /// input.to_mut()[i] = -v;
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);
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);
112 /// // No clone occurs because `input` is already owned.
113 /// let mut input = Cow::from(vec![-1, 0, 1]);
114 /// abs_all(&mut input);
116 #[stable(feature = "rust1", since = "1.0.0")]
117 pub enum Cow<'a, B: ?Sized + 'a>
121 #[stable(feature = "rust1", since = "1.0.0")]
122 Borrowed(#[stable(feature = "rust1", since = "1.0.0")]
126 #[stable(feature = "rust1", since = "1.0.0")]
127 Owned(#[stable(feature = "rust1", since = "1.0.0")]
128 <B as ToOwned>::Owned),
131 #[stable(feature = "rust1", since = "1.0.0")]
132 impl<'a, B: ?Sized> Clone for Cow<'a, B>
135 fn clone(&self) -> Cow<'a, B> {
137 Borrowed(b) => Borrowed(b),
139 let b: &B = o.borrow();
146 impl<'a, B: ?Sized> Cow<'a, B>
149 /// Acquires a mutable reference to the owned form of the data.
151 /// Clones the data if it is not already owned.
156 /// use std::borrow::Cow;
158 /// let mut cow: Cow<[_]> = Cow::Owned(vec![1, 2, 3]);
160 /// let hello = cow.to_mut();
162 /// assert_eq!(hello, &[1, 2, 3]);
164 #[stable(feature = "rust1", since = "1.0.0")]
165 pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned {
167 Borrowed(borrowed) => {
168 *self = Owned(borrowed.to_owned());
170 Borrowed(..) => unreachable!(),
171 Owned(ref mut owned) => owned,
174 Owned(ref mut owned) => owned,
178 /// Extracts the owned data.
180 /// Clones the data if it is not already owned.
185 /// use std::borrow::Cow;
187 /// let cow: Cow<[_]> = Cow::Owned(vec![1, 2, 3]);
189 /// let hello = cow.into_owned();
191 /// assert_eq!(vec![1, 2, 3], hello);
193 #[stable(feature = "rust1", since = "1.0.0")]
194 pub fn into_owned(self) -> <B as ToOwned>::Owned {
196 Borrowed(borrowed) => borrowed.to_owned(),
197 Owned(owned) => owned,
202 #[stable(feature = "rust1", since = "1.0.0")]
203 impl<'a, B: ?Sized> Deref for Cow<'a, B>
208 fn deref(&self) -> &B {
210 Borrowed(borrowed) => borrowed,
211 Owned(ref owned) => owned.borrow(),
216 #[stable(feature = "rust1", since = "1.0.0")]
217 impl<'a, B: ?Sized> Eq for Cow<'a, B> where B: Eq + ToOwned {}
219 #[stable(feature = "rust1", since = "1.0.0")]
220 impl<'a, B: ?Sized> Ord for Cow<'a, B>
221 where B: Ord + ToOwned
224 fn cmp(&self, other: &Cow<'a, B>) -> Ordering {
225 Ord::cmp(&**self, &**other)
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,
235 fn eq(&self, other: &Cow<'b, C>) -> bool {
236 PartialEq::eq(&**self, &**other)
240 #[stable(feature = "rust1", since = "1.0.0")]
241 impl<'a, B: ?Sized> PartialOrd for Cow<'a, B>
242 where B: PartialOrd + ToOwned
245 fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering> {
246 PartialOrd::partial_cmp(&**self, &**other)
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
255 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
257 Borrowed(ref b) => fmt::Debug::fmt(b, f),
258 Owned(ref o) => fmt::Debug::fmt(o, f),
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
268 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
270 Borrowed(ref b) => fmt::Display::fmt(b, f),
271 Owned(ref o) => fmt::Display::fmt(o, f),
276 #[stable(feature = "default", since = "1.11.0")]
277 impl<'a, B: ?Sized> Default for Cow<'a, B>
279 <B as ToOwned>::Owned: Default
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())
287 #[stable(feature = "rust1", since = "1.0.0")]
288 impl<'a, B: ?Sized> Hash for Cow<'a, B>
289 where B: Hash + ToOwned
292 fn hash<H: Hasher>(&self, state: &mut H) {
293 Hash::hash(&**self, state)
297 #[stable(feature = "rust1", since = "1.0.0")]
299 impl<'a, T: ?Sized + ToOwned> AsRef<T> for Cow<'a, T> {
300 fn as_ref(&self) -> &T {
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>;
310 fn add(mut self, rhs: &'a str) -> Self::Output {
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>;
321 fn add(mut self, rhs: Cow<'a, str>) -> Self::Output {
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) {
331 *self = Cow::Borrowed(rhs)
332 } else if rhs.is_empty() {
335 if let Cow::Borrowed(lhs) = *self {
336 let mut s = String::with_capacity(lhs.len() + rhs.len());
338 *self = Cow::Owned(s);
340 self.to_mut().push_str(rhs);
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>) {
350 } else if rhs.is_empty() {
353 if let Cow::Borrowed(lhs) = *self {
354 let mut s = String::with_capacity(lhs.len() + rhs.len());
356 *self = Cow::Owned(s);
358 self.to_mut().push_str(&rhs);