1 //! A module for working with borrowed data.
3 #![stable(feature = "rust1", since = "1.0.0")]
5 use core::cmp::Ordering;
6 use core::hash::{Hash, Hasher};
7 use core::ops::{Add, AddAssign, Deref};
9 #[stable(feature = "rust1", since = "1.0.0")]
10 pub use core::borrow::{Borrow, BorrowMut};
13 use crate::string::String;
17 #[stable(feature = "rust1", since = "1.0.0")]
18 impl<'a, B: ?Sized> Borrow<B> for Cow<'a, B>
20 <B as ToOwned>::Owned: 'a
22 fn borrow(&self) -> &B {
27 /// A generalization of `Clone` to borrowed data.
29 /// Some types make it possible to go from borrowed to owned, usually by
30 /// implementing the `Clone` trait. But `Clone` works only for going from `&T`
31 /// to `T`. The `ToOwned` trait generalizes `Clone` to construct owned data
32 /// from any borrow of a given type.
33 #[stable(feature = "rust1", since = "1.0.0")]
35 #[stable(feature = "rust1", since = "1.0.0")]
36 type Owned: Borrow<Self>;
38 /// Creates owned data from borrowed data, usually by cloning.
45 /// let s: &str = "a";
46 /// let ss: String = s.to_owned();
48 /// let v: &[i32] = &[1, 2];
49 /// let vv: Vec<i32> = v.to_owned();
51 #[stable(feature = "rust1", since = "1.0.0")]
52 #[must_use = "cloning is often expensive and is not expected to have side effects"]
53 fn to_owned(&self) -> Self::Owned;
55 /// Uses borrowed data to replace owned data, usually by cloning.
57 /// This is borrow-generalized version of `Clone::clone_from`.
64 /// # #![feature(toowned_clone_into)]
65 /// let mut s: String = String::new();
66 /// "hello".clone_into(&mut s);
68 /// let mut v: Vec<i32> = Vec::new();
69 /// [1, 2][..].clone_into(&mut v);
71 #[unstable(feature = "toowned_clone_into",
72 reason = "recently added",
74 fn clone_into(&self, target: &mut Self::Owned) {
75 *target = self.to_owned();
79 #[stable(feature = "rust1", since = "1.0.0")]
84 fn to_owned(&self) -> T {
88 fn clone_into(&self, target: &mut T) {
89 target.clone_from(self);
93 /// A clone-on-write smart pointer.
95 /// The type `Cow` is a smart pointer providing clone-on-write functionality: it
96 /// can enclose and provide immutable access to borrowed data, and clone the
97 /// data lazily when mutation or ownership is required. The type is designed to
98 /// work with general borrowed data via the `Borrow` trait.
100 /// `Cow` implements `Deref`, which means that you can call
101 /// non-mutating methods directly on the data it encloses. If mutation
102 /// is desired, `to_mut` will obtain a mutable reference to an owned
103 /// value, cloning if necessary.
108 /// use std::borrow::Cow;
110 /// fn abs_all(input: &mut Cow<[i32]>) {
111 /// for i in 0..input.len() {
112 /// let v = input[i];
114 /// // Clones into a vector if not already owned.
115 /// input.to_mut()[i] = -v;
120 /// // No clone occurs because `input` doesn't need to be mutated.
121 /// let slice = [0, 1, 2];
122 /// let mut input = Cow::from(&slice[..]);
123 /// abs_all(&mut input);
125 /// // Clone occurs because `input` needs to be mutated.
126 /// let slice = [-1, 0, 1];
127 /// let mut input = Cow::from(&slice[..]);
128 /// abs_all(&mut input);
130 /// // No clone occurs because `input` is already owned.
131 /// let mut input = Cow::from(vec![-1, 0, 1]);
132 /// abs_all(&mut input);
135 /// Another example showing how to keep `Cow` in a struct:
138 /// use std::borrow::{Cow, ToOwned};
140 /// struct Items<'a, X: 'a> where [X]: ToOwned<Owned = Vec<X>> {
141 /// values: Cow<'a, [X]>,
144 /// impl<'a, X: Clone + 'a> Items<'a, X> where [X]: ToOwned<Owned = Vec<X>> {
145 /// fn new(v: Cow<'a, [X]>) -> Self {
146 /// Items { values: v }
150 /// // Creates a container from borrowed values of a slice
151 /// let readonly = [1, 2];
152 /// let borrowed = Items::new((&readonly[..]).into());
154 /// Items { values: Cow::Borrowed(b) } => println!("borrowed {:?}", b),
155 /// _ => panic!("expect borrowed value"),
158 /// let mut clone_on_write = borrowed;
159 /// // Mutates the data from slice into owned vec and pushes a new value on top
160 /// clone_on_write.values.to_mut().push(3);
161 /// println!("clone_on_write = {:?}", clone_on_write.values);
163 /// // The data was mutated. Let check it out.
164 /// match clone_on_write {
165 /// Items { values: Cow::Owned(_) } => println!("clone_on_write contains owned data"),
166 /// _ => panic!("expect owned data"),
169 #[stable(feature = "rust1", since = "1.0.0")]
170 pub enum Cow<'a, B: ?Sized + 'a>
174 #[stable(feature = "rust1", since = "1.0.0")]
175 Borrowed(#[stable(feature = "rust1", since = "1.0.0")]
179 #[stable(feature = "rust1", since = "1.0.0")]
180 Owned(#[stable(feature = "rust1", since = "1.0.0")]
181 <B as ToOwned>::Owned),
184 #[stable(feature = "rust1", since = "1.0.0")]
185 impl<B: ?Sized + ToOwned> Clone for Cow<'_, B> {
186 fn clone(&self) -> Self {
188 Borrowed(b) => Borrowed(b),
190 let b: &B = o.borrow();
196 fn clone_from(&mut self, source: &Self) {
197 if let Owned(ref mut dest) = *self {
198 if let Owned(ref o) = *source {
199 o.borrow().clone_into(dest);
204 *self = source.clone();
208 impl<B: ?Sized + ToOwned> Cow<'_, B> {
209 /// Acquires a mutable reference to the owned form of the data.
211 /// Clones the data if it is not already owned.
216 /// use std::borrow::Cow;
218 /// let mut cow = Cow::Borrowed("foo");
219 /// cow.to_mut().make_ascii_uppercase();
223 /// Cow::Owned(String::from("FOO")) as Cow<str>
226 #[stable(feature = "rust1", since = "1.0.0")]
227 pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned {
229 Borrowed(borrowed) => {
230 *self = Owned(borrowed.to_owned());
232 Borrowed(..) => unreachable!(),
233 Owned(ref mut owned) => owned,
236 Owned(ref mut owned) => owned,
240 /// Extracts the owned data.
242 /// Clones the data if it is not already owned.
246 /// Calling `into_owned` on a `Cow::Borrowed` clones the underlying data
247 /// and becomes a `Cow::Owned`:
250 /// use std::borrow::Cow;
252 /// let s = "Hello world!";
253 /// let cow = Cow::Borrowed(s);
256 /// cow.into_owned(),
261 /// Calling `into_owned` on a `Cow::Owned` is a no-op:
264 /// use std::borrow::Cow;
266 /// let s = "Hello world!";
267 /// let cow: Cow<str> = Cow::Owned(String::from(s));
270 /// cow.into_owned(),
274 #[stable(feature = "rust1", since = "1.0.0")]
275 pub fn into_owned(self) -> <B as ToOwned>::Owned {
277 Borrowed(borrowed) => borrowed.to_owned(),
278 Owned(owned) => owned,
283 #[stable(feature = "rust1", since = "1.0.0")]
284 impl<B: ?Sized + ToOwned> Deref for Cow<'_, B> {
287 fn deref(&self) -> &B {
289 Borrowed(borrowed) => borrowed,
290 Owned(ref owned) => owned.borrow(),
295 #[stable(feature = "rust1", since = "1.0.0")]
296 impl<B: ?Sized> Eq for Cow<'_, B> where B: Eq + ToOwned {}
298 #[stable(feature = "rust1", since = "1.0.0")]
299 impl<B: ?Sized> Ord for Cow<'_, B>
300 where B: Ord + ToOwned
303 fn cmp(&self, other: &Self) -> Ordering {
304 Ord::cmp(&**self, &**other)
308 #[stable(feature = "rust1", since = "1.0.0")]
309 impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, C>> for Cow<'a, B>
310 where B: PartialEq<C> + ToOwned,
314 fn eq(&self, other: &Cow<'b, C>) -> bool {
315 PartialEq::eq(&**self, &**other)
319 #[stable(feature = "rust1", since = "1.0.0")]
320 impl<'a, B: ?Sized> PartialOrd for Cow<'a, B>
321 where B: PartialOrd + ToOwned
324 fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering> {
325 PartialOrd::partial_cmp(&**self, &**other)
329 #[stable(feature = "rust1", since = "1.0.0")]
330 impl<B: ?Sized> fmt::Debug for Cow<'_, B>
331 where B: fmt::Debug + ToOwned,
332 <B as ToOwned>::Owned: fmt::Debug
334 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
336 Borrowed(ref b) => fmt::Debug::fmt(b, f),
337 Owned(ref o) => fmt::Debug::fmt(o, f),
342 #[stable(feature = "rust1", since = "1.0.0")]
343 impl<B: ?Sized> fmt::Display for Cow<'_, B>
344 where B: fmt::Display + ToOwned,
345 <B as ToOwned>::Owned: fmt::Display
347 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
349 Borrowed(ref b) => fmt::Display::fmt(b, f),
350 Owned(ref o) => fmt::Display::fmt(o, f),
355 #[stable(feature = "default", since = "1.11.0")]
356 impl<B: ?Sized> Default for Cow<'_, B>
358 <B as ToOwned>::Owned: Default
360 /// Creates an owned Cow<'a, B> with the default value for the contained owned value.
361 fn default() -> Self {
362 Owned(<B as ToOwned>::Owned::default())
366 #[stable(feature = "rust1", since = "1.0.0")]
367 impl<B: ?Sized> Hash for Cow<'_, B>
368 where B: Hash + ToOwned
371 fn hash<H: Hasher>(&self, state: &mut H) {
372 Hash::hash(&**self, state)
376 #[stable(feature = "rust1", since = "1.0.0")]
377 impl<T: ?Sized + ToOwned> AsRef<T> for Cow<'_, T> {
378 fn as_ref(&self) -> &T {
383 #[stable(feature = "cow_add", since = "1.14.0")]
384 impl<'a> Add<&'a str> for Cow<'a, str> {
385 type Output = Cow<'a, str>;
388 fn add(mut self, rhs: &'a str) -> Self::Output {
394 #[stable(feature = "cow_add", since = "1.14.0")]
395 impl<'a> Add<Cow<'a, str>> for Cow<'a, str> {
396 type Output = Cow<'a, str>;
399 fn add(mut self, rhs: Cow<'a, str>) -> Self::Output {
405 #[stable(feature = "cow_add", since = "1.14.0")]
406 impl<'a> AddAssign<&'a str> for Cow<'a, str> {
407 fn add_assign(&mut self, rhs: &'a str) {
409 *self = Cow::Borrowed(rhs)
410 } else if rhs.is_empty() {
413 if let Cow::Borrowed(lhs) = *self {
414 let mut s = String::with_capacity(lhs.len() + rhs.len());
416 *self = Cow::Owned(s);
418 self.to_mut().push_str(rhs);
423 #[stable(feature = "cow_add", since = "1.14.0")]
424 impl<'a> AddAssign<Cow<'a, str>> for Cow<'a, str> {
425 fn add_assign(&mut self, rhs: Cow<'a, str>) {
428 } else if rhs.is_empty() {
431 if let Cow::Borrowed(lhs) = *self {
432 let mut s = String::with_capacity(lhs.len() + rhs.len());
434 *self = Cow::Owned(s);
436 self.to_mut().push_str(&rhs);