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};
8 #[cfg(not(no_global_oom_handling))]
9 use core::ops::{Add, AddAssign};
11 #[stable(feature = "rust1", since = "1.0.0")]
12 pub use core::borrow::{Borrow, BorrowMut};
15 #[cfg(not(no_global_oom_handling))]
16 use crate::string::String;
20 #[stable(feature = "rust1", since = "1.0.0")]
21 impl<'a, B: ?Sized> Borrow<B> for Cow<'a, B>
24 <B as ToOwned>::Owned: 'a,
26 fn borrow(&self) -> &B {
31 /// A generalization of `Clone` to borrowed data.
33 /// Some types make it possible to go from borrowed to owned, usually by
34 /// implementing the `Clone` trait. But `Clone` works only for going from `&T`
35 /// to `T`. The `ToOwned` trait generalizes `Clone` to construct owned data
36 /// from any borrow of a given type.
37 #[cfg_attr(not(test), rustc_diagnostic_item = "ToOwned")]
38 #[stable(feature = "rust1", since = "1.0.0")]
40 /// The resulting type after obtaining ownership.
41 #[stable(feature = "rust1", since = "1.0.0")]
42 type Owned: Borrow<Self>;
44 /// Creates owned data from borrowed data, usually by cloning.
51 /// let s: &str = "a";
52 /// let ss: String = s.to_owned();
54 /// let v: &[i32] = &[1, 2];
55 /// let vv: Vec<i32> = v.to_owned();
57 #[stable(feature = "rust1", since = "1.0.0")]
58 #[must_use = "cloning is often expensive and is not expected to have side effects"]
59 fn to_owned(&self) -> Self::Owned;
61 /// Uses borrowed data to replace owned data, usually by cloning.
63 /// This is borrow-generalized version of `Clone::clone_from`.
70 /// # #![feature(toowned_clone_into)]
71 /// let mut s: String = String::new();
72 /// "hello".clone_into(&mut s);
74 /// let mut v: Vec<i32> = Vec::new();
75 /// [1, 2][..].clone_into(&mut v);
77 #[unstable(feature = "toowned_clone_into", reason = "recently added", issue = "41263")]
78 fn clone_into(&self, target: &mut Self::Owned) {
79 *target = self.to_owned();
83 #[stable(feature = "rust1", since = "1.0.0")]
89 fn to_owned(&self) -> T {
93 fn clone_into(&self, target: &mut T) {
94 target.clone_from(self);
98 /// A clone-on-write smart pointer.
100 /// The type `Cow` is a smart pointer providing clone-on-write functionality: it
101 /// can enclose and provide immutable access to borrowed data, and clone the
102 /// data lazily when mutation or ownership is required. The type is designed to
103 /// work with general borrowed data via the `Borrow` trait.
105 /// `Cow` implements `Deref`, which means that you can call
106 /// non-mutating methods directly on the data it encloses. If mutation
107 /// is desired, `to_mut` will obtain a mutable reference to an owned
108 /// value, cloning if necessary.
110 /// If you need reference-counting pointers, note that
111 /// [`Rc::make_mut`][crate::rc::Rc::make_mut] and
112 /// [`Arc::make_mut`][crate::sync::Arc::make_mut] can provide clone-on-write
113 /// functionality as well.
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;
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's 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 #[cfg_attr(not(test), rustc_diagnostic_item = "Cow")]
181 pub enum Cow<'a, B: ?Sized + 'a>
186 #[stable(feature = "rust1", since = "1.0.0")]
187 Borrowed(#[stable(feature = "rust1", since = "1.0.0")] &'a B),
190 #[stable(feature = "rust1", since = "1.0.0")]
191 Owned(#[stable(feature = "rust1", since = "1.0.0")] <B as ToOwned>::Owned),
194 #[stable(feature = "rust1", since = "1.0.0")]
195 impl<B: ?Sized + ToOwned> Clone for Cow<'_, B> {
196 fn clone(&self) -> Self {
198 Borrowed(b) => Borrowed(b),
200 let b: &B = o.borrow();
206 fn clone_from(&mut self, source: &Self) {
207 match (self, source) {
208 (&mut Owned(ref mut dest), &Owned(ref o)) => o.borrow().clone_into(dest),
209 (t, s) => *t = s.clone(),
214 impl<B: ?Sized + ToOwned> Cow<'_, B> {
215 /// Returns true if the data is borrowed, i.e. if `to_mut` would require additional work.
220 /// #![feature(cow_is_borrowed)]
221 /// use std::borrow::Cow;
223 /// let cow = Cow::Borrowed("moo");
224 /// assert!(cow.is_borrowed());
226 /// let bull: Cow<'_, str> = Cow::Owned("...moo?".to_string());
227 /// assert!(!bull.is_borrowed());
229 #[unstable(feature = "cow_is_borrowed", issue = "65143")]
230 #[rustc_const_unstable(feature = "const_cow_is_borrowed", issue = "65143")]
231 pub const fn is_borrowed(&self) -> bool {
238 /// Returns true if the data is owned, i.e. if `to_mut` would be a no-op.
243 /// #![feature(cow_is_borrowed)]
244 /// use std::borrow::Cow;
246 /// let cow: Cow<'_, str> = Cow::Owned("moo".to_string());
247 /// assert!(cow.is_owned());
249 /// let bull = Cow::Borrowed("...moo?");
250 /// assert!(!bull.is_owned());
252 #[unstable(feature = "cow_is_borrowed", issue = "65143")]
253 #[rustc_const_unstable(feature = "const_cow_is_borrowed", issue = "65143")]
254 pub const fn is_owned(&self) -> bool {
258 /// Acquires a mutable reference to the owned form of the data.
260 /// Clones the data if it is not already owned.
265 /// use std::borrow::Cow;
267 /// let mut cow = Cow::Borrowed("foo");
268 /// cow.to_mut().make_ascii_uppercase();
272 /// Cow::Owned(String::from("FOO")) as Cow<str>
275 #[stable(feature = "rust1", since = "1.0.0")]
276 pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned {
278 Borrowed(borrowed) => {
279 *self = Owned(borrowed.to_owned());
281 Borrowed(..) => unreachable!(),
282 Owned(ref mut owned) => owned,
285 Owned(ref mut owned) => owned,
289 /// Extracts the owned data.
291 /// Clones the data if it is not already owned.
295 /// Calling `into_owned` on a `Cow::Borrowed` returns a clone of the borrowed data:
298 /// use std::borrow::Cow;
300 /// let s = "Hello world!";
301 /// let cow = Cow::Borrowed(s);
304 /// cow.into_owned(),
309 /// Calling `into_owned` on a `Cow::Owned` returns the owned data. The data is moved out of the
310 /// `Cow` without being cloned.
313 /// use std::borrow::Cow;
315 /// let s = "Hello world!";
316 /// let cow: Cow<str> = Cow::Owned(String::from(s));
319 /// cow.into_owned(),
323 #[stable(feature = "rust1", since = "1.0.0")]
324 pub fn into_owned(self) -> <B as ToOwned>::Owned {
326 Borrowed(borrowed) => borrowed.to_owned(),
327 Owned(owned) => owned,
332 #[stable(feature = "rust1", since = "1.0.0")]
333 #[rustc_const_unstable(feature = "const_deref", issue = "88955")]
334 impl<B: ?Sized + ToOwned> const Deref for Cow<'_, B>
336 B::Owned: ~const Borrow<B>,
340 fn deref(&self) -> &B {
342 Borrowed(borrowed) => borrowed,
343 Owned(ref owned) => owned.borrow(),
348 #[stable(feature = "rust1", since = "1.0.0")]
349 impl<B: ?Sized> Eq for Cow<'_, B> where B: Eq + ToOwned {}
351 #[stable(feature = "rust1", since = "1.0.0")]
352 impl<B: ?Sized> Ord for Cow<'_, B>
357 fn cmp(&self, other: &Self) -> Ordering {
358 Ord::cmp(&**self, &**other)
362 #[stable(feature = "rust1", since = "1.0.0")]
363 impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, C>> for Cow<'a, B>
365 B: PartialEq<C> + ToOwned,
369 fn eq(&self, other: &Cow<'b, C>) -> bool {
370 PartialEq::eq(&**self, &**other)
374 #[stable(feature = "rust1", since = "1.0.0")]
375 impl<'a, B: ?Sized> PartialOrd for Cow<'a, B>
377 B: PartialOrd + ToOwned,
380 fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering> {
381 PartialOrd::partial_cmp(&**self, &**other)
385 #[stable(feature = "rust1", since = "1.0.0")]
386 impl<B: ?Sized> fmt::Debug for Cow<'_, B>
388 B: fmt::Debug + ToOwned<Owned: fmt::Debug>,
390 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
392 Borrowed(ref b) => fmt::Debug::fmt(b, f),
393 Owned(ref o) => fmt::Debug::fmt(o, f),
398 #[stable(feature = "rust1", since = "1.0.0")]
399 impl<B: ?Sized> fmt::Display for Cow<'_, B>
401 B: fmt::Display + ToOwned<Owned: fmt::Display>,
403 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
405 Borrowed(ref b) => fmt::Display::fmt(b, f),
406 Owned(ref o) => fmt::Display::fmt(o, f),
411 #[stable(feature = "default", since = "1.11.0")]
412 impl<B: ?Sized> Default for Cow<'_, B>
414 B: ToOwned<Owned: Default>,
416 /// Creates an owned Cow<'a, B> with the default value for the contained owned value.
417 fn default() -> Self {
418 Owned(<B as ToOwned>::Owned::default())
422 #[stable(feature = "rust1", since = "1.0.0")]
423 impl<B: ?Sized> Hash for Cow<'_, B>
428 fn hash<H: Hasher>(&self, state: &mut H) {
429 Hash::hash(&**self, state)
433 #[stable(feature = "rust1", since = "1.0.0")]
434 impl<T: ?Sized + ToOwned> AsRef<T> for Cow<'_, T> {
435 fn as_ref(&self) -> &T {
440 #[cfg(not(no_global_oom_handling))]
441 #[stable(feature = "cow_add", since = "1.14.0")]
442 impl<'a> Add<&'a str> for Cow<'a, str> {
443 type Output = Cow<'a, str>;
446 fn add(mut self, rhs: &'a str) -> Self::Output {
452 #[cfg(not(no_global_oom_handling))]
453 #[stable(feature = "cow_add", since = "1.14.0")]
454 impl<'a> Add<Cow<'a, str>> for Cow<'a, str> {
455 type Output = Cow<'a, str>;
458 fn add(mut self, rhs: Cow<'a, str>) -> Self::Output {
464 #[cfg(not(no_global_oom_handling))]
465 #[stable(feature = "cow_add", since = "1.14.0")]
466 impl<'a> AddAssign<&'a str> for Cow<'a, str> {
467 fn add_assign(&mut self, rhs: &'a str) {
469 *self = Cow::Borrowed(rhs)
470 } else if !rhs.is_empty() {
471 if let Cow::Borrowed(lhs) = *self {
472 let mut s = String::with_capacity(lhs.len() + rhs.len());
474 *self = Cow::Owned(s);
476 self.to_mut().push_str(rhs);
481 #[cfg(not(no_global_oom_handling))]
482 #[stable(feature = "cow_add", since = "1.14.0")]
483 impl<'a> AddAssign<Cow<'a, str>> for Cow<'a, str> {
484 fn add_assign(&mut self, rhs: Cow<'a, str>) {
487 } else if !rhs.is_empty() {
488 if let Cow::Borrowed(lhs) = *self {
489 let mut s = String::with_capacity(lhs.len() + rhs.len());
491 *self = Cow::Owned(s);
493 self.to_mut().push_str(&rhs);