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 #[must_use = "cloning is often expensive and is not expected to have side effects"]
63 fn to_owned(&self) -> Self::Owned;
65 /// Uses borrowed data to replace owned data, usually by cloning.
67 /// This is borrow-generalized version of `Clone::clone_from`.
74 /// # #![feature(toowned_clone_into)]
75 /// let mut s: String = String::new();
76 /// "hello".clone_into(&mut s);
78 /// let mut v: Vec<i32> = Vec::new();
79 /// [1, 2][..].clone_into(&mut v);
81 #[unstable(feature = "toowned_clone_into",
82 reason = "recently added",
84 fn clone_into(&self, target: &mut Self::Owned) {
85 *target = self.to_owned();
89 #[stable(feature = "rust1", since = "1.0.0")]
94 fn to_owned(&self) -> T {
98 fn clone_into(&self, target: &mut T) {
99 target.clone_from(self);
103 /// A clone-on-write smart pointer.
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.
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.
118 /// use std::borrow::Cow;
120 /// fn abs_all(input: &mut Cow<[i32]>) {
121 /// for i in 0..input.len() {
122 /// let v = input[i];
124 /// // Clones into a vector if not already owned.
125 /// input.to_mut()[i] = -v;
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);
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);
140 /// // No clone occurs because `input` is already owned.
141 /// let mut input = Cow::from(vec![-1, 0, 1]);
142 /// abs_all(&mut input);
145 /// Another example showing how to keep `Cow` in a struct:
148 /// use std::borrow::{Cow, ToOwned};
150 /// struct Items<'a, X: 'a> where [X]: ToOwned<Owned=Vec<X>> {
151 /// values: Cow<'a, [X]>,
154 /// impl<'a, X: Clone + 'a> Items<'a, X> where [X]: ToOwned<Owned=Vec<X>> {
155 /// fn new(v: Cow<'a, [X]>) -> Self {
156 /// Items { values: v }
160 /// // Creates a container from borrowed values of a slice
161 /// let readonly = [1, 2];
162 /// let borrowed = Items::new((&readonly[..]).into());
164 /// Items { values: Cow::Borrowed(b) } => println!("borrowed {:?}", b),
165 /// _ => panic!("expect borrowed value"),
168 /// let mut clone_on_write = borrowed;
169 /// // Mutates the data from slice into owned vec and pushes a new value on top
170 /// clone_on_write.values.to_mut().push(3);
171 /// println!("clone_on_write = {:?}", clone_on_write.values);
173 /// // The data was mutated. Let check it out.
174 /// match clone_on_write {
175 /// Items { values: Cow::Owned(_) } => println!("clone_on_write contains owned data"),
176 /// _ => panic!("expect owned data"),
179 #[stable(feature = "rust1", since = "1.0.0")]
180 pub enum Cow<'a, B: ?Sized + 'a>
184 #[stable(feature = "rust1", since = "1.0.0")]
185 Borrowed(#[stable(feature = "rust1", since = "1.0.0")]
189 #[stable(feature = "rust1", since = "1.0.0")]
190 Owned(#[stable(feature = "rust1", since = "1.0.0")]
191 <B as ToOwned>::Owned),
194 #[stable(feature = "rust1", since = "1.0.0")]
195 impl<'a, B: ?Sized> Clone for Cow<'a, B>
198 fn clone(&self) -> Cow<'a, B> {
200 Borrowed(b) => Borrowed(b),
202 let b: &B = o.borrow();
208 fn clone_from(&mut self, source: &Cow<'a, B>) {
209 if let Owned(ref mut dest) = *self {
210 if let Owned(ref o) = *source {
211 o.borrow().clone_into(dest);
216 *self = source.clone();
220 impl<'a, B: ?Sized> Cow<'a, B>
223 /// Acquires a mutable reference to the owned form of the data.
225 /// Clones the data if it is not already owned.
230 /// use std::borrow::Cow;
232 /// let mut cow = Cow::Borrowed("foo");
233 /// cow.to_mut().make_ascii_uppercase();
237 /// Cow::Owned(String::from("FOO")) as Cow<str>
240 #[stable(feature = "rust1", since = "1.0.0")]
241 pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned {
243 Borrowed(borrowed) => {
244 *self = Owned(borrowed.to_owned());
246 Borrowed(..) => unreachable!(),
247 Owned(ref mut owned) => owned,
250 Owned(ref mut owned) => owned,
254 /// Extracts the owned data.
256 /// Clones the data if it is not already owned.
260 /// Calling `into_owned` on a `Cow::Borrowed` clones the underlying data
261 /// and becomes a `Cow::Owned`:
264 /// use std::borrow::Cow;
266 /// let s = "Hello world!";
267 /// let cow = Cow::Borrowed(s);
270 /// cow.into_owned(),
275 /// Calling `into_owned` on a `Cow::Owned` is a no-op:
278 /// use std::borrow::Cow;
280 /// let s = "Hello world!";
281 /// let cow: Cow<str> = Cow::Owned(String::from(s));
284 /// cow.into_owned(),
288 #[stable(feature = "rust1", since = "1.0.0")]
289 pub fn into_owned(self) -> <B as ToOwned>::Owned {
291 Borrowed(borrowed) => borrowed.to_owned(),
292 Owned(owned) => owned,
297 #[stable(feature = "rust1", since = "1.0.0")]
298 impl<'a, B: ?Sized> Deref for Cow<'a, B>
303 fn deref(&self) -> &B {
305 Borrowed(borrowed) => borrowed,
306 Owned(ref owned) => owned.borrow(),
311 #[stable(feature = "rust1", since = "1.0.0")]
312 impl<'a, B: ?Sized> Eq for Cow<'a, B> where B: Eq + ToOwned {}
314 #[stable(feature = "rust1", since = "1.0.0")]
315 impl<'a, B: ?Sized> Ord for Cow<'a, B>
316 where B: Ord + ToOwned
319 fn cmp(&self, other: &Cow<'a, B>) -> Ordering {
320 Ord::cmp(&**self, &**other)
324 #[stable(feature = "rust1", since = "1.0.0")]
325 impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, C>> for Cow<'a, B>
326 where B: PartialEq<C> + ToOwned,
330 fn eq(&self, other: &Cow<'b, C>) -> bool {
331 PartialEq::eq(&**self, &**other)
335 #[stable(feature = "rust1", since = "1.0.0")]
336 impl<'a, B: ?Sized> PartialOrd for Cow<'a, B>
337 where B: PartialOrd + ToOwned
340 fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering> {
341 PartialOrd::partial_cmp(&**self, &**other)
345 #[stable(feature = "rust1", since = "1.0.0")]
346 impl<'a, B: ?Sized> fmt::Debug for Cow<'a, B>
347 where B: fmt::Debug + ToOwned,
348 <B as ToOwned>::Owned: fmt::Debug
350 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
352 Borrowed(ref b) => fmt::Debug::fmt(b, f),
353 Owned(ref o) => fmt::Debug::fmt(o, f),
358 #[stable(feature = "rust1", since = "1.0.0")]
359 impl<'a, B: ?Sized> fmt::Display for Cow<'a, B>
360 where B: fmt::Display + ToOwned,
361 <B as ToOwned>::Owned: fmt::Display
363 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
365 Borrowed(ref b) => fmt::Display::fmt(b, f),
366 Owned(ref o) => fmt::Display::fmt(o, f),
371 #[stable(feature = "default", since = "1.11.0")]
372 impl<'a, B: ?Sized> Default for Cow<'a, B>
374 <B as ToOwned>::Owned: Default
376 /// Creates an owned Cow<'a, B> with the default value for the contained owned value.
377 fn default() -> Cow<'a, B> {
378 Owned(<B as ToOwned>::Owned::default())
382 #[stable(feature = "rust1", since = "1.0.0")]
383 impl<'a, B: ?Sized> Hash for Cow<'a, B>
384 where B: Hash + ToOwned
387 fn hash<H: Hasher>(&self, state: &mut H) {
388 Hash::hash(&**self, state)
392 #[stable(feature = "rust1", since = "1.0.0")]
394 impl<'a, T: ?Sized + ToOwned> AsRef<T> for Cow<'a, T> {
395 fn as_ref(&self) -> &T {
400 #[stable(feature = "cow_add", since = "1.14.0")]
401 impl<'a> Add<&'a str> for Cow<'a, str> {
402 type Output = Cow<'a, str>;
405 fn add(mut self, rhs: &'a str) -> Self::Output {
411 #[stable(feature = "cow_add", since = "1.14.0")]
412 impl<'a> Add<Cow<'a, str>> for Cow<'a, str> {
413 type Output = Cow<'a, str>;
416 fn add(mut self, rhs: Cow<'a, str>) -> Self::Output {
422 #[stable(feature = "cow_add", since = "1.14.0")]
423 impl<'a> AddAssign<&'a str> for Cow<'a, str> {
424 fn add_assign(&mut self, rhs: &'a str) {
426 *self = Cow::Borrowed(rhs)
427 } else if rhs.is_empty() {
430 if let Cow::Borrowed(lhs) = *self {
431 let mut s = String::with_capacity(lhs.len() + rhs.len());
433 *self = Cow::Owned(s);
435 self.to_mut().push_str(rhs);
440 #[stable(feature = "cow_add", since = "1.14.0")]
441 impl<'a> AddAssign<Cow<'a, str>> for Cow<'a, str> {
442 fn add_assign(&mut self, rhs: Cow<'a, str>) {
445 } else if rhs.is_empty() {
448 if let Cow::Borrowed(lhs) = *self {
449 let mut s = String::with_capacity(lhs.len() + rhs.len());
451 *self = Cow::Owned(s);
453 self.to_mut().push_str(&rhs);