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