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