1//! A module for working with borrowed data.23#![stable(feature ="rust1", since ="1.0.0")]45#[stable(feature ="rust1", since ="1.0.0")]6pub usecore::borrow::{Borrow, BorrowMut};7usecore::cmp::Ordering;8usecore::hash::{Hash, Hasher};9#[cfg(not(no_global_oom_handling))]10usecore::ops::{Add, AddAssign};11usecore::ops::{Deref, DerefPure};1213useCow::*;1415usecrate::fmt;16#[cfg(not(no_global_oom_handling))]17usecrate::string::String;1819// FIXME(inference): const bounds removed due to inference regressions found by crater;20// see https://github.com/rust-lang/rust/issues/14796421// #[rustc_const_unstable(feature = "const_convert", issue = "143773")]22#[stable(feature ="rust1", since ="1.0.0")]23impl<'a, B:?Sized + ToOwned> Borrow<B>forCow<'a, B>24// where25// B::Owned: [const] Borrow<B>,26{27fnborrow(&self) ->&B {28&**self29}30}3132/// A generalization of `Clone` to borrowed data.33///34/// Some types make it possible to go from borrowed to owned, usually by35/// implementing the `Clone` trait. But `Clone` works only for going from `&T`36/// to `T`. The `ToOwned` trait generalizes `Clone` to construct owned data37/// from any borrow of a given type.38#[rustc_diagnostic_item ="ToOwned"]39#[stable(feature ="rust1", since ="1.0.0")]40pub traitToOwned {41/// The resulting type after obtaining ownership.42#[stable(feature ="rust1", since ="1.0.0")]43typeOwned: Borrow<Self>;4445/// Creates owned data from borrowed data, usually by cloning.46 ///47 /// # Examples48 ///49 /// Basic usage:50 ///51 /// ```52 /// let s: &str = "a";53 /// let ss: String = s.to_owned();54 ///55 /// let v: &[i32] = &[1, 2];56 /// let vv: Vec<i32> = v.to_owned();57 /// ```58#[stable(feature ="rust1", since ="1.0.0")]59 #[must_use ="cloning is often expensive and is not expected to have side effects"]60 #[rustc_diagnostic_item ="to_owned_method"]61fnto_owned(&self) ->Self::Owned;6263/// Uses borrowed data to replace owned data, usually by cloning.64 ///65 /// This is borrow-generalized version of [`Clone::clone_from`].66 ///67 /// # Examples68 ///69 /// Basic usage:70 ///71 /// ```72 /// let mut s: String = String::new();73 /// "hello".clone_into(&mut s);74 ///75 /// let mut v: Vec<i32> = Vec::new();76 /// [1, 2][..].clone_into(&mut v);77 /// ```78#[stable(feature ="toowned_clone_into", since ="1.63.0")]79fnclone_into(&self, target:&mutSelf::Owned) {80*target =self.to_owned();81 }82}8384#[stable(feature ="rust1", since ="1.0.0")]85impl<T> ToOwnedforT86where87T: Clone,88{89typeOwned = T;90fnto_owned(&self) -> T {91self.clone()92 }9394fnclone_into(&self, target:&mutT) {95 target.clone_from(self);96 }97}9899/// A clone-on-write smart pointer.100///101/// The type `Cow` is a smart pointer providing clone-on-write functionality: it102/// can enclose and provide immutable access to borrowed data, and clone the103/// data lazily when mutation or ownership is required. The type is designed to104/// work with general borrowed data via the `Borrow` trait.105///106/// `Cow` implements `Deref`, which means that you can call107/// non-mutating methods directly on the data it encloses. If mutation108/// is desired, `to_mut` will obtain a mutable reference to an owned109/// value, cloning if necessary.110///111/// If you need reference-counting pointers, note that112/// [`Rc::make_mut`][crate::rc::Rc::make_mut] and113/// [`Arc::make_mut`][crate::sync::Arc::make_mut] can provide clone-on-write114/// functionality as well.115///116/// # Examples117///118/// ```119/// use std::borrow::Cow;120///121/// fn abs_all(input: &mut Cow<'_, [i32]>) {122/// for i in 0..input.len() {123/// let v = input[i];124/// if v < 0 {125/// // Clones into a vector if not already owned.126/// input.to_mut()[i] = -v;127/// }128/// }129/// }130///131/// // No clone occurs because `input` doesn't need to be mutated.132/// let slice = [0, 1, 2];133/// let mut input = Cow::from(&slice[..]);134/// abs_all(&mut input);135///136/// // Clone occurs because `input` needs to be mutated.137/// let slice = [-1, 0, 1];138/// let mut input = Cow::from(&slice[..]);139/// abs_all(&mut input);140///141/// // No clone occurs because `input` is already owned.142/// let mut input = Cow::from(vec![-1, 0, 1]);143/// abs_all(&mut input);144/// ```145///146/// Another example showing how to keep `Cow` in a struct:147///148/// ```149/// use std::borrow::Cow;150///151/// struct Items<'a, X> where [X]: ToOwned<Owned = Vec<X>> {152/// values: Cow<'a, [X]>,153/// }154///155/// impl<'a, X: Clone + 'a> Items<'a, X> where [X]: ToOwned<Owned = Vec<X>> {156/// fn new(v: Cow<'a, [X]>) -> Self {157/// Items { values: v }158/// }159/// }160///161/// // Creates a container from borrowed values of a slice162/// let readonly = [1, 2];163/// let borrowed = Items::new((&readonly[..]).into());164/// match borrowed {165/// Items { values: Cow::Borrowed(b) } => println!("borrowed {b:?}"),166/// _ => panic!("expect borrowed value"),167/// }168///169/// let mut clone_on_write = borrowed;170/// // Mutates the data from slice into owned vec and pushes a new value on top171/// clone_on_write.values.to_mut().push(3);172/// println!("clone_on_write = {:?}", clone_on_write.values);173///174/// // The data was mutated. Let's check it out.175/// match clone_on_write {176/// Items { values: Cow::Owned(_) } => println!("clone_on_write contains owned data"),177/// _ => panic!("expect owned data"),178/// }179/// ```180#[stable(feature ="rust1", since ="1.0.0")]181#[rustc_diagnostic_item ="Cow"]182pub enumCow<'a, B:?Sized +'a>183where184B: ToOwned,185{186/// Borrowed data.187#[stable(feature ="rust1", since ="1.0.0")]188Borrowed(#[stable(feature ="rust1", since ="1.0.0")]&'aB),189190/// Owned data.191#[stable(feature ="rust1", since ="1.0.0")]192Owned(#[stable(feature ="rust1", since ="1.0.0")]<BasToOwned>::Owned),193}194195#[stable(feature ="rust1", since ="1.0.0")]196impl<B:?Sized + ToOwned> CloneforCow<'_, B> {197fnclone(&self) ->Self{198match*self{199 Borrowed(b) => Borrowed(b),200 Owned(refo) => {201letb:&B = o.borrow();202 Owned(b.to_owned())203 }204 }205 }206207fnclone_from(&mutself, source:&Self) {208match(self, source) {209 (&mutOwned(ref mutdest),&Owned(refo)) => o.borrow().clone_into(dest),210 (t, s) =>*t = s.clone(),211 }212 }213}214215impl<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 call219 /// it as `Cow::is_borrowed(&c)` instead of `c.is_borrowed()`. This is so220 /// that there is no conflict with a method on the inner type.221 ///222 /// # Examples223 ///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")]235pub const fnis_borrowed(c:&Self) -> bool {236match*c {237 Borrowed(_) =>true,238 Owned(_) =>false,239 }240 }241242/// 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 call245 /// it as `Cow::is_owned(&c)` instead of `c.is_owned()`. This is so that246 /// there is no conflict with a method on the inner type.247 ///248 /// # Examples249 ///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")]261pub const fnis_owned(c:&Self) -> bool {262 !Cow::is_borrowed(c)263 }264265/// Acquires a mutable reference to the owned form of the data.266 ///267 /// Clones the data if it is not already owned.268 ///269 /// # Examples270 ///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")]283pub fnto_mut(&mutself) ->&mut<BasToOwned>::Owned {284match*self{285 Borrowed(borrowed) => {286*self= Owned(borrowed.to_owned());287match*self{288 Borrowed(..) =>unreachable!(),289 Owned(ref mutowned) => owned,290 }291 }292 Owned(ref mutowned) => owned,293 }294 }295296/// Extracts the owned data.297 ///298 /// Clones the data if it is not already owned.299 ///300 /// # Examples301 ///302 /// Calling `into_owned` on a `Cow::Borrowed` returns a clone of the borrowed data:303 ///304 /// ```305 /// use std::borrow::Cow;306 ///307 /// let s = "Hello world!";308 /// let cow = Cow::Borrowed(s);309 ///310 /// assert_eq!(311 /// cow.into_owned(),312 /// String::from(s)313 /// );314 /// ```315 ///316 /// Calling `into_owned` on a `Cow::Owned` returns the owned data. The data is moved out of the317 /// `Cow` without being cloned.318 ///319 /// ```320 /// use std::borrow::Cow;321 ///322 /// let s = "Hello world!";323 /// let cow: Cow<'_, str> = Cow::Owned(String::from(s));324 ///325 /// assert_eq!(326 /// cow.into_owned(),327 /// String::from(s)328 /// );329 /// ```330#[stable(feature ="rust1", since ="1.0.0")]331pub fninto_owned(self) -> <BasToOwned>::Owned {332matchself{333 Borrowed(borrowed) => borrowed.to_owned(),334 Owned(owned) => owned,335 }336 }337}338339// FIXME(inference): const bounds removed due to inference regressions found by crater;340// see https://github.com/rust-lang/rust/issues/147964341// #[rustc_const_unstable(feature = "const_convert", issue = "143773")]342#[stable(feature ="rust1", since ="1.0.0")]343impl<B:?Sized + ToOwned> DerefforCow<'_, B>344// where345// B::Owned: [const] Borrow<B>,346{347typeTarget = B;348349fnderef(&self) ->&B {350match*self{351 Borrowed(borrowed) => borrowed,352 Owned(refowned) => owned.borrow(),353 }354 }355}356357// `Cow<'_, T>` can only implement `DerefPure` if `<T::Owned as Borrow<T>>` (and `BorrowMut<T>`) is trusted.358// For now, we restrict `DerefPure for Cow<T>` to `T: Sized` (`T as Borrow<T>` is trusted),359// `str` (`String as Borrow<str>` is trusted) and `[T]` (`Vec<T> as Borrow<[T]>` is trusted).360// In the future, a `BorrowPure<T>` trait analogous to `DerefPure` might generalize this.361#[unstable(feature ="deref_pure_trait", issue ="87121")]362unsafe impl<T: Clone> DerefPureforCow<'_, T> {}363#[cfg(not(no_global_oom_handling))]364#[unstable(feature ="deref_pure_trait", issue ="87121")]365unsafe implDerefPureforCow<'_, str> {}366#[cfg(not(no_global_oom_handling))]367#[unstable(feature ="deref_pure_trait", issue ="87121")]368unsafe impl<T: Clone> DerefPureforCow<'_, [T]> {}369370#[stable(feature ="rust1", since ="1.0.0")]371impl<B:?Sized> EqforCow<'_, B>whereB: Eq + ToOwned {}372373#[stable(feature ="rust1", since ="1.0.0")]374impl<B:?Sized> OrdforCow<'_, B>375where376B: Ord + ToOwned,377{378#[inline]379fncmp(&self, other:&Self) -> Ordering {380 Ord::cmp(&**self,&**other)381 }382}383384#[stable(feature ="rust1", since ="1.0.0")]385impl<'a,'b, B:?Sized, C:?Sized> PartialEq<Cow<'b, C>>forCow<'a, B>386where387B: PartialEq<C> + ToOwned,388 C: ToOwned,389{390#[inline]391fneq(&self, other:&Cow<'b, C>) -> bool {392 PartialEq::eq(&**self,&**other)393 }394}395396#[stable(feature ="rust1", since ="1.0.0")]397impl<'a, B:?Sized> PartialOrdforCow<'a, B>398where399B: PartialOrd + ToOwned,400{401#[inline]402fnpartial_cmp(&self, other:&Cow<'a, B>) ->Option<Ordering> {403 PartialOrd::partial_cmp(&**self,&**other)404 }405}406407#[stable(feature ="rust1", since ="1.0.0")]408impl<B:?Sized> fmt::DebugforCow<'_, B>409where410B: fmt::Debug + ToOwned<Owned: fmt::Debug>,411{412fnfmt(&self, f:&mutfmt::Formatter<'_>) -> fmt::Result {413match*self{414 Borrowed(refb) => fmt::Debug::fmt(b, f),415 Owned(refo) => fmt::Debug::fmt(o, f),416 }417 }418}419420#[stable(feature ="rust1", since ="1.0.0")]421impl<B:?Sized> fmt::DisplayforCow<'_, B>422where423B: fmt::Display + ToOwned<Owned: fmt::Display>,424{425fnfmt(&self, f:&mutfmt::Formatter<'_>) -> fmt::Result {426match*self{427 Borrowed(refb) => fmt::Display::fmt(b, f),428 Owned(refo) => fmt::Display::fmt(o, f),429 }430 }431}432433#[stable(feature ="default", since ="1.11.0")]434impl<B:?Sized> DefaultforCow<'_, B>435where436B: ToOwned<Owned: Default>,437{438/// Creates an owned Cow<'a, B> with the default value for the contained owned value.439fndefault() ->Self{440 Owned(<BasToOwned>::Owned::default())441 }442}443444#[stable(feature ="rust1", since ="1.0.0")]445impl<B:?Sized> HashforCow<'_, B>446where447B: Hash + ToOwned,448{449#[inline]450fnhash<H: Hasher>(&self, state:&mutH) {451 Hash::hash(&**self, state)452 }453}454455// FIXME(inference): const bounds removed due to inference regressions found by crater;456// see https://github.com/rust-lang/rust/issues/147964457// #[rustc_const_unstable(feature = "const_convert", issue = "143773")]458#[stable(feature ="rust1", since ="1.0.0")]459impl<T:?Sized + ToOwned> AsRef<T>forCow<'_, T>460// where461// T::Owned: [const] Borrow<T>,462{463fnas_ref(&self) ->&T {464self465}466}467468#[cfg(not(no_global_oom_handling))]469#[stable(feature ="cow_add", since ="1.14.0")]470impl<'a> Add<&'astr>forCow<'a, str> {471typeOutput = Cow<'a, str>;472473#[inline]474fnadd(mutself, rhs:&'astr) ->Self::Output {475self+= rhs;476self477}478}479480#[cfg(not(no_global_oom_handling))]481#[stable(feature ="cow_add", since ="1.14.0")]482impl<'a> Add<Cow<'a, str>>forCow<'a, str> {483typeOutput = Cow<'a, str>;484485#[inline]486fnadd(mutself, rhs: Cow<'a, str>) ->Self::Output {487self+= rhs;488self489}490}491492#[cfg(not(no_global_oom_handling))]493#[stable(feature ="cow_add", since ="1.14.0")]494impl<'a> AddAssign<&'astr>forCow<'a, str> {495fnadd_assign(&mutself, rhs:&'astr) {496ifself.is_empty() {497*self= Cow::Borrowed(rhs)498 }elseif !rhs.is_empty() {499if letCow::Borrowed(lhs) =*self{500letmuts = String::with_capacity(lhs.len() + rhs.len());501 s.push_str(lhs);502*self= Cow::Owned(s);503 }504self.to_mut().push_str(rhs);505 }506 }507}508509#[cfg(not(no_global_oom_handling))]510#[stable(feature ="cow_add", since ="1.14.0")]511impl<'a> AddAssign<Cow<'a, str>>forCow<'a, str> {512fnadd_assign(&mutself, rhs: Cow<'a, str>) {513ifself.is_empty() {514*self= rhs515 }elseif !rhs.is_empty() {516if letCow::Borrowed(lhs) =*self{517letmuts = String::with_capacity(lhs.len() + rhs.len());518 s.push_str(lhs);519*self= Cow::Owned(s);520 }521self.to_mut().push_str(&rhs);522 }523 }524}