Movatterモバイル変換


[0]ホーム

URL:


alloc/
borrow.rs

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#[stable(feature ="rust1", since ="1.0.0")]20impl<'a, B:?Sized> Borrow<B>forCow<'a, B>21where22B: ToOwned,23{24fnborrow(&self) ->&B {25&**self26}27}2829/// A generalization of `Clone` to borrowed data.30///31/// Some types make it possible to go from borrowed to owned, usually by32/// implementing the `Clone` trait. But `Clone` works only for going from `&T`33/// to `T`. The `ToOwned` trait generalizes `Clone` to construct owned data34/// from any borrow of a given type.35#[rustc_diagnostic_item ="ToOwned"]36#[stable(feature ="rust1", since ="1.0.0")]37pub traitToOwned {38/// The resulting type after obtaining ownership.39#[stable(feature ="rust1", since ="1.0.0")]40typeOwned: Borrow<Self>;4142/// Creates owned data from borrowed data, usually by cloning.43    ///44    /// # Examples45    ///46    /// Basic usage:47    ///48    /// ```49    /// let s: &str = "a";50    /// let ss: String = s.to_owned();51    ///52    /// let v: &[i32] = &[1, 2];53    /// let vv: Vec<i32> = v.to_owned();54    /// ```55#[stable(feature ="rust1", since ="1.0.0")]56    #[must_use ="cloning is often expensive and is not expected to have side effects"]57    #[rustc_diagnostic_item ="to_owned_method"]58fnto_owned(&self) ->Self::Owned;5960/// Uses borrowed data to replace owned data, usually by cloning.61    ///62    /// This is borrow-generalized version of [`Clone::clone_from`].63    ///64    /// # Examples65    ///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")]76fnclone_into(&self, target:&mutSelf::Owned) {77*target =self.to_owned();78    }79}8081#[stable(feature ="rust1", since ="1.0.0")]82impl<T> ToOwnedforT83where84T: Clone,85{86typeOwned = T;87fnto_owned(&self) -> T {88self.clone()89    }9091fnclone_into(&self, target:&mutT) {92        target.clone_from(self);93    }94}9596/// A clone-on-write smart pointer.97///98/// The type `Cow` is a smart pointer providing clone-on-write functionality: it99/// can enclose and provide immutable access to borrowed data, and clone the100/// data lazily when mutation or ownership is required. The type is designed to101/// work with general borrowed data via the `Borrow` trait.102///103/// `Cow` implements `Deref`, which means that you can call104/// non-mutating methods directly on the data it encloses. If mutation105/// is desired, `to_mut` will obtain a mutable reference to an owned106/// value, cloning if necessary.107///108/// If you need reference-counting pointers, note that109/// [`Rc::make_mut`][crate::rc::Rc::make_mut] and110/// [`Arc::make_mut`][crate::sync::Arc::make_mut] can provide clone-on-write111/// functionality as well.112///113/// # Examples114///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 slice159/// 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 top168/// 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#[rustc_diagnostic_item ="Cow"]179pub enumCow<'a, B:?Sized +'a>180where181B: ToOwned,182{183/// Borrowed data.184#[stable(feature ="rust1", since ="1.0.0")]185Borrowed(#[stable(feature ="rust1", since ="1.0.0")]&'aB),186187/// Owned data.188#[stable(feature ="rust1", since ="1.0.0")]189Owned(#[stable(feature ="rust1", since ="1.0.0")]<BasToOwned>::Owned),190}191192#[stable(feature ="rust1", since ="1.0.0")]193impl<B:?Sized + ToOwned> CloneforCow<'_, B> {194fnclone(&self) ->Self{195match*self{196            Borrowed(b) => Borrowed(b),197            Owned(refo) => {198letb:&B = o.borrow();199                Owned(b.to_owned())200            }201        }202    }203204fnclone_from(&mutself, source:&Self) {205match(self, source) {206            (&mutOwned(ref mutdest),&Owned(refo)) => o.borrow().clone_into(dest),207            (t, s) =>*t = s.clone(),208        }209    }210}211212impl<B:?Sized + ToOwned> Cow<'_, B> {213/// Returns true if the data is borrowed, i.e. if `to_mut` would require additional work.214    ///215    /// # Examples216    ///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")]228pub const fnis_borrowed(&self) -> bool {229match*self{230            Borrowed(_) =>true,231            Owned(_) =>false,232        }233    }234235/// Returns true if the data is owned, i.e. if `to_mut` would be a no-op.236    ///237    /// # Examples238    ///239    /// ```240    /// #![feature(cow_is_borrowed)]241    /// use std::borrow::Cow;242    ///243    /// let cow: Cow<'_, str> = Cow::Owned("moo".to_string());244    /// assert!(cow.is_owned());245    ///246    /// let bull = Cow::Borrowed("...moo?");247    /// assert!(!bull.is_owned());248    /// ```249#[unstable(feature ="cow_is_borrowed", issue ="65143")]250pub const fnis_owned(&self) -> bool {251        !self.is_borrowed()252    }253254/// Acquires a mutable reference to the owned form of the data.255    ///256    /// Clones the data if it is not already owned.257    ///258    /// # Examples259    ///260    /// ```261    /// use std::borrow::Cow;262    ///263    /// let mut cow = Cow::Borrowed("foo");264    /// cow.to_mut().make_ascii_uppercase();265    ///266    /// assert_eq!(267    ///   cow,268    ///   Cow::Owned(String::from("FOO")) as Cow<'_, str>269    /// );270    /// ```271#[stable(feature ="rust1", since ="1.0.0")]272pub fnto_mut(&mutself) ->&mut<BasToOwned>::Owned {273match*self{274            Borrowed(borrowed) => {275*self= Owned(borrowed.to_owned());276match*self{277                    Borrowed(..) =>unreachable!(),278                    Owned(ref mutowned) => owned,279                }280            }281            Owned(ref mutowned) => owned,282        }283    }284285/// Extracts the owned data.286    ///287    /// Clones the data if it is not already owned.288    ///289    /// # Examples290    ///291    /// Calling `into_owned` on a `Cow::Borrowed` returns a clone of the borrowed data:292    ///293    /// ```294    /// use std::borrow::Cow;295    ///296    /// let s = "Hello world!";297    /// let cow = Cow::Borrowed(s);298    ///299    /// assert_eq!(300    ///   cow.into_owned(),301    ///   String::from(s)302    /// );303    /// ```304    ///305    /// Calling `into_owned` on a `Cow::Owned` returns the owned data. The data is moved out of the306    /// `Cow` without being cloned.307    ///308    /// ```309    /// use std::borrow::Cow;310    ///311    /// let s = "Hello world!";312    /// let cow: Cow<'_, str> = Cow::Owned(String::from(s));313    ///314    /// assert_eq!(315    ///   cow.into_owned(),316    ///   String::from(s)317    /// );318    /// ```319#[stable(feature ="rust1", since ="1.0.0")]320pub fninto_owned(self) -> <BasToOwned>::Owned {321matchself{322            Borrowed(borrowed) => borrowed.to_owned(),323            Owned(owned) => owned,324        }325    }326}327328#[stable(feature ="rust1", since ="1.0.0")]329impl<B:?Sized + ToOwned> DerefforCow<'_, B>330where331B::Owned: Borrow<B>,332{333typeTarget = B;334335fnderef(&self) ->&B {336match*self{337            Borrowed(borrowed) => borrowed,338            Owned(refowned) => owned.borrow(),339        }340    }341}342343// `Cow<'_, T>` can only implement `DerefPure` if `<T::Owned as Borrow<T>>` (and `BorrowMut<T>`) is trusted.344// For now, we restrict `DerefPure for Cow<T>` to `T: Sized` (`T as Borrow<T>` is trusted),345// `str` (`String as Borrow<str>` is trusted) and `[T]` (`Vec<T> as Borrow<[T]>` is trusted).346// In the future, a `BorrowPure<T>` trait analogous to `DerefPure` might generalize this.347#[unstable(feature ="deref_pure_trait", issue ="87121")]348unsafe impl<T: Clone> DerefPureforCow<'_, T> {}349#[cfg(not(no_global_oom_handling))]350#[unstable(feature ="deref_pure_trait", issue ="87121")]351unsafe implDerefPureforCow<'_, str> {}352#[cfg(not(no_global_oom_handling))]353#[unstable(feature ="deref_pure_trait", issue ="87121")]354unsafe impl<T: Clone> DerefPureforCow<'_, [T]> {}355356#[stable(feature ="rust1", since ="1.0.0")]357impl<B:?Sized> EqforCow<'_, B>whereB: Eq + ToOwned {}358359#[stable(feature ="rust1", since ="1.0.0")]360impl<B:?Sized> OrdforCow<'_, B>361where362B: Ord + ToOwned,363{364#[inline]365fncmp(&self, other:&Self) -> Ordering {366        Ord::cmp(&**self,&**other)367    }368}369370#[stable(feature ="rust1", since ="1.0.0")]371impl<'a,'b, B:?Sized, C:?Sized> PartialEq<Cow<'b, C>>forCow<'a, B>372where373B: PartialEq<C> + ToOwned,374    C: ToOwned,375{376#[inline]377fneq(&self, other:&Cow<'b, C>) -> bool {378        PartialEq::eq(&**self,&**other)379    }380}381382#[stable(feature ="rust1", since ="1.0.0")]383impl<'a, B:?Sized> PartialOrdforCow<'a, B>384where385B: PartialOrd + ToOwned,386{387#[inline]388fnpartial_cmp(&self, other:&Cow<'a, B>) ->Option<Ordering> {389        PartialOrd::partial_cmp(&**self,&**other)390    }391}392393#[stable(feature ="rust1", since ="1.0.0")]394impl<B:?Sized> fmt::DebugforCow<'_, B>395where396B: fmt::Debug + ToOwned<Owned: fmt::Debug>,397{398fnfmt(&self, f:&mutfmt::Formatter<'_>) -> fmt::Result {399match*self{400            Borrowed(refb) => fmt::Debug::fmt(b, f),401            Owned(refo) => fmt::Debug::fmt(o, f),402        }403    }404}405406#[stable(feature ="rust1", since ="1.0.0")]407impl<B:?Sized> fmt::DisplayforCow<'_, B>408where409B: fmt::Display + ToOwned<Owned: fmt::Display>,410{411fnfmt(&self, f:&mutfmt::Formatter<'_>) -> fmt::Result {412match*self{413            Borrowed(refb) => fmt::Display::fmt(b, f),414            Owned(refo) => fmt::Display::fmt(o, f),415        }416    }417}418419#[stable(feature ="default", since ="1.11.0")]420impl<B:?Sized> DefaultforCow<'_, B>421where422B: ToOwned<Owned: Default>,423{424/// Creates an owned Cow<'a, B> with the default value for the contained owned value.425fndefault() ->Self{426        Owned(<BasToOwned>::Owned::default())427    }428}429430#[stable(feature ="rust1", since ="1.0.0")]431impl<B:?Sized> HashforCow<'_, B>432where433B: Hash + ToOwned,434{435#[inline]436fnhash<H: Hasher>(&self, state:&mutH) {437        Hash::hash(&**self, state)438    }439}440441#[stable(feature ="rust1", since ="1.0.0")]442impl<T:?Sized + ToOwned> AsRef<T>forCow<'_, T> {443fnas_ref(&self) ->&T {444self445}446}447448#[cfg(not(no_global_oom_handling))]449#[stable(feature ="cow_add", since ="1.14.0")]450impl<'a> Add<&'astr>forCow<'a, str> {451typeOutput = Cow<'a, str>;452453#[inline]454fnadd(mutself, rhs:&'astr) ->Self::Output {455self+= rhs;456self457}458}459460#[cfg(not(no_global_oom_handling))]461#[stable(feature ="cow_add", since ="1.14.0")]462impl<'a> Add<Cow<'a, str>>forCow<'a, str> {463typeOutput = Cow<'a, str>;464465#[inline]466fnadd(mutself, rhs: Cow<'a, str>) ->Self::Output {467self+= rhs;468self469}470}471472#[cfg(not(no_global_oom_handling))]473#[stable(feature ="cow_add", since ="1.14.0")]474impl<'a> AddAssign<&'astr>forCow<'a, str> {475fnadd_assign(&mutself, rhs:&'astr) {476ifself.is_empty() {477*self= Cow::Borrowed(rhs)478        }else if!rhs.is_empty() {479if letCow::Borrowed(lhs) =*self{480letmuts = String::with_capacity(lhs.len() + rhs.len());481                s.push_str(lhs);482*self= Cow::Owned(s);483            }484self.to_mut().push_str(rhs);485        }486    }487}488489#[cfg(not(no_global_oom_handling))]490#[stable(feature ="cow_add", since ="1.14.0")]491impl<'a> AddAssign<Cow<'a, str>>forCow<'a, str> {492fnadd_assign(&mutself, rhs: Cow<'a, str>) {493ifself.is_empty() {494*self= rhs495        }else if!rhs.is_empty() {496if letCow::Borrowed(lhs) =*self{497letmuts = String::with_capacity(lhs.len() + rhs.len());498                s.push_str(lhs);499*self= Cow::Owned(s);500            }501self.to_mut().push_str(&rhs);502        }503    }504}

[8]ページ先頭

©2009-2025 Movatter.jp