1//! A module for working with borrowed data.
2
3#![stable(feature = "rust1", since = "1.0.0")]
4
5use core::cmp::Ordering;
6use core::hash::{Hash, Hasher};
7use core::ops::Deref;
8#[cfg(not(no_global_oom_handling))]
9use core::ops::{Add, AddAssign};
10
11#[stable(feature = "rust1", since = "1.0.0")]
12pub use core::borrow::{Borrow, BorrowMut};
13
14use crate::fmt;
15#[cfg(not(no_global_oom_handling))]
16use crate::string::String;
17
18use Cow::*;
19
20#[stable(feature = "rust1", since = "1.0.0")]
21impl<'a, B: ?Sized> Borrow<B> for Cow<'a, B>
22where
23 B: ToOwned,
24{
25 fn borrow(&self) -> &B {
26 &**self
27 }
28}
29
30/// A generalization of `Clone` to borrowed data.
31///
32/// Some types make it possible to go from borrowed to owned, usually by
33/// implementing the `Clone` trait. But `Clone` works only for going from `&T`
34/// to `T`. The `ToOwned` trait generalizes `Clone` to construct owned data
35/// from any borrow of a given type.
36#[cfg_attr(not(test), rustc_diagnostic_item = "ToOwned")]
37#[stable(feature = "rust1", since = "1.0.0")]
38pub trait ToOwned {
39 /// The resulting type after obtaining ownership.
40 #[stable(feature = "rust1", since = "1.0.0")]
41 type Owned: Borrow<Self>;
42
43 /// Creates owned data from borrowed data, usually by cloning.
44 ///
45 /// # Examples
46 ///
47 /// Basic usage:
48 ///
49 /// ```
50 /// let s: &str = "a";
51 /// let ss: String = s.to_owned();
52 ///
53 /// let v: &[i32] = &[1, 2];
54 /// let vv: Vec<i32> = v.to_owned();
55 /// ```
56 #[stable(feature = "rust1", since = "1.0.0")]
57 #[must_use = "cloning is often expensive and is not expected to have side effects"]
58 #[cfg_attr(not(test), rustc_diagnostic_item = "to_owned_method")]
59 fn to_owned(&self) -> Self::Owned;
60
61 /// Uses borrowed data to replace owned data, usually by cloning.
62 ///
63 /// This is borrow-generalized version of [`Clone::clone_from`].
64 ///
65 /// # Examples
66 ///
67 /// Basic usage:
68 ///
69 /// ```
70 /// let mut s: String = String::new();
71 /// "hello".clone_into(&mut s);
72 ///
73 /// let mut v: Vec<i32> = Vec::new();
74 /// [1, 2][..].clone_into(&mut v);
75 /// ```
76 #[stable(feature = "toowned_clone_into", since = "1.63.0")]
77 fn clone_into(&self, target: &mut Self::Owned) {
78 *target = self.to_owned();
79 }
80}
81
82#[stable(feature = "rust1", since = "1.0.0")]
83impl<T> ToOwned for T
84where
85 T: Clone,
86{
87 type Owned = T;
88 fn to_owned(&self) -> T {
89 self.clone()
90 }
91
92 fn clone_into(&self, target: &mut T) {
93 target.clone_from(self);
94 }
95}
96
97/// A clone-on-write smart pointer.
98///
99/// The type `Cow` is a smart pointer providing clone-on-write functionality: it
100/// can enclose and provide immutable access to borrowed data, and clone the
101/// data lazily when mutation or ownership is required. The type is designed to
102/// work with general borrowed data via the `Borrow` trait.
103///
104/// `Cow` implements `Deref`, which means that you can call
105/// non-mutating methods directly on the data it encloses. If mutation
106/// is desired, `to_mut` will obtain a mutable reference to an owned
107/// value, cloning if necessary.
108///
109/// If you need reference-counting pointers, note that
110/// [`Rc::make_mut`][crate::rc::Rc::make_mut] and
111/// [`Arc::make_mut`][crate::sync::Arc::make_mut] can provide clone-on-write
112/// functionality as well.
113///
114/// # Examples
115///
116/// ```
117/// use std::borrow::Cow;
118///
119/// fn abs_all(input: &mut Cow<'_, [i32]>) {
120/// for i in 0..input.len() {
121/// let v = input[i];
122/// if v < 0 {
123/// // Clones into a vector if not already owned.
124/// input.to_mut()[i] = -v;
125/// }
126/// }
127/// }
128///
129/// // No clone occurs because `input` doesn't need to be mutated.
130/// let slice = [0, 1, 2];
131/// let mut input = Cow::from(&slice[..]);
132/// abs_all(&mut input);
133///
134/// // Clone occurs because `input` needs to be mutated.
135/// let slice = [-1, 0, 1];
136/// let mut input = Cow::from(&slice[..]);
137/// abs_all(&mut input);
138///
139/// // No clone occurs because `input` is already owned.
140/// let mut input = Cow::from(vec![-1, 0, 1]);
141/// abs_all(&mut input);
142/// ```
143///
144/// Another example showing how to keep `Cow` in a struct:
145///
146/// ```
147/// use std::borrow::Cow;
148///
149/// struct Items<'a, X> where [X]: ToOwned<Owned = Vec<X>> {
150/// values: Cow<'a, [X]>,
151/// }
152///
153/// impl<'a, X: Clone + 'a> Items<'a, X> where [X]: ToOwned<Owned = Vec<X>> {
154/// fn new(v: Cow<'a, [X]>) -> Self {
155/// Items { values: v }
156/// }
157/// }
158///
159/// // Creates a container from borrowed values of a slice
160/// let readonly = [1, 2];
161/// let borrowed = Items::new((&readonly[..]).into());
162/// match borrowed {
163/// Items { values: Cow::Borrowed(b) } => println!("borrowed {b:?}"),
164/// _ => panic!("expect borrowed value"),
165/// }
166///
167/// let mut clone_on_write = borrowed;
168/// // Mutates the data from slice into owned vec and pushes a new value on top
169/// clone_on_write.values.to_mut().push(3);
170/// println!("clone_on_write = {:?}", clone_on_write.values);
171///
172/// // The data was mutated. Let's check it out.
173/// match clone_on_write {
174/// Items { values: Cow::Owned(_) } => println!("clone_on_write contains owned data"),
175/// _ => panic!("expect owned data"),
176/// }
177/// ```
178#[stable(feature = "rust1", since = "1.0.0")]
179#[cfg_attr(not(test), rustc_diagnostic_item = "Cow")]
180pub enum Cow<'a, B: ?Sized + 'a>
181where
182 B: ToOwned,
183{
184 /// Borrowed data.
185 #[stable(feature = "rust1", since = "1.0.0")]
186 Borrowed(#[stable(feature = "rust1", since = "1.0.0")] &'a B),
187
188 /// Owned data.
189 #[stable(feature = "rust1", since = "1.0.0")]
190 Owned(#[stable(feature = "rust1", since = "1.0.0")] <B as ToOwned>::Owned),
191}
192
193#[stable(feature = "rust1", since = "1.0.0")]
194impl<B: ?Sized + ToOwned> Clone for Cow<'_, B> {
195 fn clone(&self) -> Self {
196 match *self {
197 Borrowed(b: &B) => Borrowed(b),
198 Owned(ref o: &::Owned) => {
199 let b: &B = o.borrow();
200 Owned(b.to_owned())
201 }
202 }
203 }
204
205 fn clone_from(&mut self, source: &Self) {
206 match (self, source) {
207 (&mut Owned(ref mut dest: &mut ::Owned), &Owned(ref o: &::Owned)) => o.borrow().clone_into(target:dest),
208 (t: &mut Cow<'_, B>, s: &Cow<'_, B>) => *t = s.clone(),
209 }
210 }
211}
212
213impl<B: ?Sized + ToOwned> Cow<'_, B> {
214 /// Returns true if the data is borrowed, i.e. if `to_mut` would require additional work.
215 ///
216 /// # Examples
217 ///
218 /// ```
219 /// #![feature(cow_is_borrowed)]
220 /// use std::borrow::Cow;
221 ///
222 /// let cow = Cow::Borrowed("moo");
223 /// assert!(cow.is_borrowed());
224 ///
225 /// let bull: Cow<'_, str> = Cow::Owned("...moo?".to_string());
226 /// assert!(!bull.is_borrowed());
227 /// ```
228 #[unstable(feature = "cow_is_borrowed", issue = "65143")]
229 #[rustc_const_unstable(feature = "const_cow_is_borrowed", issue = "65143")]
230 pub const fn is_borrowed(&self) -> bool {
231 match *self {
232 Borrowed(_) => true,
233 Owned(_) => false,
234 }
235 }
236
237 /// Returns true if the data is owned, i.e. if `to_mut` would be a no-op.
238 ///
239 /// # Examples
240 ///
241 /// ```
242 /// #![feature(cow_is_borrowed)]
243 /// use std::borrow::Cow;
244 ///
245 /// let cow: Cow<'_, str> = Cow::Owned("moo".to_string());
246 /// assert!(cow.is_owned());
247 ///
248 /// let bull = Cow::Borrowed("...moo?");
249 /// assert!(!bull.is_owned());
250 /// ```
251 #[unstable(feature = "cow_is_borrowed", issue = "65143")]
252 #[rustc_const_unstable(feature = "const_cow_is_borrowed", issue = "65143")]
253 pub const fn is_owned(&self) -> bool {
254 !self.is_borrowed()
255 }
256
257 /// Acquires a mutable reference to the owned form of the data.
258 ///
259 /// Clones the data if it is not already owned.
260 ///
261 /// # Examples
262 ///
263 /// ```
264 /// use std::borrow::Cow;
265 ///
266 /// let mut cow = Cow::Borrowed("foo");
267 /// cow.to_mut().make_ascii_uppercase();
268 ///
269 /// assert_eq!(
270 /// cow,
271 /// Cow::Owned(String::from("FOO")) as Cow<'_, str>
272 /// );
273 /// ```
274 #[stable(feature = "rust1", since = "1.0.0")]
275 pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned {
276 match *self {
277 Borrowed(borrowed) => {
278 *self = Owned(borrowed.to_owned());
279 match *self {
280 Borrowed(..) => unreachable!(),
281 Owned(ref mut owned) => owned,
282 }
283 }
284 Owned(ref mut owned) => owned,
285 }
286 }
287
288 /// Extracts the owned data.
289 ///
290 /// Clones the data if it is not already owned.
291 ///
292 /// # Examples
293 ///
294 /// Calling `into_owned` on a `Cow::Borrowed` returns a clone of the borrowed data:
295 ///
296 /// ```
297 /// use std::borrow::Cow;
298 ///
299 /// let s = "Hello world!";
300 /// let cow = Cow::Borrowed(s);
301 ///
302 /// assert_eq!(
303 /// cow.into_owned(),
304 /// String::from(s)
305 /// );
306 /// ```
307 ///
308 /// Calling `into_owned` on a `Cow::Owned` returns the owned data. The data is moved out of the
309 /// `Cow` without being cloned.
310 ///
311 /// ```
312 /// use std::borrow::Cow;
313 ///
314 /// let s = "Hello world!";
315 /// let cow: Cow<'_, str> = Cow::Owned(String::from(s));
316 ///
317 /// assert_eq!(
318 /// cow.into_owned(),
319 /// String::from(s)
320 /// );
321 /// ```
322 #[stable(feature = "rust1", since = "1.0.0")]
323 pub fn into_owned(self) -> <B as ToOwned>::Owned {
324 match self {
325 Borrowed(borrowed) => borrowed.to_owned(),
326 Owned(owned) => owned,
327 }
328 }
329}
330
331#[stable(feature = "rust1", since = "1.0.0")]
332impl<B: ?Sized + ToOwned> Deref for Cow<'_, B>
333where
334 B::Owned: Borrow<B>,
335{
336 type Target = B;
337
338 fn deref(&self) -> &B {
339 match *self {
340 Borrowed(borrowed: &B) => borrowed,
341 Owned(ref owned: &::Owned) => owned.borrow(),
342 }
343 }
344}
345
346#[stable(feature = "rust1", since = "1.0.0")]
347impl<B: ?Sized> Eq for Cow<'_, B> where B: Eq + ToOwned {}
348
349#[stable(feature = "rust1", since = "1.0.0")]
350impl<B: ?Sized> Ord for Cow<'_, B>
351where
352 B: Ord + ToOwned,
353{
354 #[inline]
355 fn cmp(&self, other: &Self) -> Ordering {
356 Ord::cmp(&**self, &**other)
357 }
358}
359
360#[stable(feature = "rust1", since = "1.0.0")]
361impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, C>> for Cow<'a, B>
362where
363 B: PartialEq<C> + ToOwned,
364 C: ToOwned,
365{
366 #[inline]
367 fn eq(&self, other: &Cow<'b, C>) -> bool {
368 PartialEq::eq(&**self, &**other)
369 }
370}
371
372#[stable(feature = "rust1", since = "1.0.0")]
373impl<'a, B: ?Sized> PartialOrd for Cow<'a, B>
374where
375 B: PartialOrd + ToOwned,
376{
377 #[inline]
378 fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering> {
379 PartialOrd::partial_cmp(&**self, &**other)
380 }
381}
382
383#[stable(feature = "rust1", since = "1.0.0")]
384impl<B: ?Sized> fmt::Debug for Cow<'_, B>
385where
386 B: fmt::Debug + ToOwned<Owned: fmt::Debug>,
387{
388 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389 match *self {
390 Borrowed(ref b: &&B) => fmt::Debug::fmt(self:b, f),
391 Owned(ref o: &::Owned) => fmt::Debug::fmt(self:o, f),
392 }
393 }
394}
395
396#[stable(feature = "rust1", since = "1.0.0")]
397impl<B: ?Sized> fmt::Display for Cow<'_, B>
398where
399 B: fmt::Display + ToOwned<Owned: fmt::Display>,
400{
401 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402 match *self {
403 Borrowed(ref b: &&B) => fmt::Display::fmt(self:b, f),
404 Owned(ref o: &::Owned) => fmt::Display::fmt(self:o, f),
405 }
406 }
407}
408
409#[stable(feature = "default", since = "1.11.0")]
410impl<B: ?Sized> Default for Cow<'_, B>
411where
412 B: ToOwned<Owned: Default>,
413{
414 /// Creates an owned Cow<'a, B> with the default value for the contained owned value.
415 fn default() -> Self {
416 Owned(<B as ToOwned>::Owned::default())
417 }
418}
419
420#[stable(feature = "rust1", since = "1.0.0")]
421impl<B: ?Sized> Hash for Cow<'_, B>
422where
423 B: Hash + ToOwned,
424{
425 #[inline]
426 fn hash<H: Hasher>(&self, state: &mut H) {
427 Hash::hash(&**self, state)
428 }
429}
430
431#[stable(feature = "rust1", since = "1.0.0")]
432impl<T: ?Sized + ToOwned> AsRef<T> for Cow<'_, T> {
433 fn as_ref(&self) -> &T {
434 self
435 }
436}
437
438#[cfg(not(no_global_oom_handling))]
439#[stable(feature = "cow_add", since = "1.14.0")]
440impl<'a> Add<&'a str> for Cow<'a, str> {
441 type Output = Cow<'a, str>;
442
443 #[inline]
444 fn add(mut self, rhs: &'a str) -> Self::Output {
445 self += rhs;
446 self
447 }
448}
449
450#[cfg(not(no_global_oom_handling))]
451#[stable(feature = "cow_add", since = "1.14.0")]
452impl<'a> Add<Cow<'a, str>> for Cow<'a, str> {
453 type Output = Cow<'a, str>;
454
455 #[inline]
456 fn add(mut self, rhs: Cow<'a, str>) -> Self::Output {
457 self += rhs;
458 self
459 }
460}
461
462#[cfg(not(no_global_oom_handling))]
463#[stable(feature = "cow_add", since = "1.14.0")]
464impl<'a> AddAssign<&'a str> for Cow<'a, str> {
465 fn add_assign(&mut self, rhs: &'a str) {
466 if self.is_empty() {
467 *self = Cow::Borrowed(rhs)
468 } else if !rhs.is_empty() {
469 if let Cow::Borrowed(lhs: &str) = *self {
470 let mut s: String = String::with_capacity(lhs.len() + rhs.len());
471 s.push_str(string:lhs);
472 *self = Cow::Owned(s);
473 }
474 self.to_mut().push_str(string:rhs);
475 }
476 }
477}
478
479#[cfg(not(no_global_oom_handling))]
480#[stable(feature = "cow_add", since = "1.14.0")]
481impl<'a> AddAssign<Cow<'a, str>> for Cow<'a, str> {
482 fn add_assign(&mut self, rhs: Cow<'a, str>) {
483 if self.is_empty() {
484 *self = rhs
485 } else if !rhs.is_empty() {
486 if let Cow::Borrowed(lhs: &str) = *self {
487 let mut s: String = String::with_capacity(lhs.len() + rhs.len());
488 s.push_str(string:lhs);
489 *self = Cow::Owned(s);
490 }
491 self.to_mut().push_str(&rhs);
492 }
493 }
494}
495