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