1//! The `Clone` trait for types that cannot be 'implicitly copied'.2//!3//! In Rust, some simple types are "implicitly copyable" and when you4//! assign them or pass them as arguments, the receiver will get a copy,5//! leaving the original value in place. These types do not require6//! allocation to copy and do not have finalizers (i.e., they do not7//! contain owned boxes or implement [`Drop`]), so the compiler considers8//! them cheap and safe to copy. For other types copies must be made9//! explicitly, by convention implementing the [`Clone`] trait and calling10//! the [`clone`] method.11//!12//! [`clone`]: Clone::clone13//!14//! Basic usage example:15//!16//! ```17//! let s = String::new(); // String type implements Clone18//! let copy = s.clone(); // so we can clone it19//! ```20//!21//! To easily implement the Clone trait, you can also use22//! `#[derive(Clone)]`. Example:23//!24//! ```25//! #[derive(Clone)] // we add the Clone trait to Morpheus struct26//! struct Morpheus {27//! blue_pill: f32,28//! red_pill: i64,29//! }30//!31//! fn main() {32//! let f = Morpheus { blue_pill: 0.0, red_pill: 0 };33//! let copy = f.clone(); // and now we can clone it!34//! }35//! ```3637#![stable(feature ="rust1", since ="1.0.0")]3839usecrate::marker::{Destruct, PointeeSized};4041moduninit;4243/// A common trait that allows explicit creation of a duplicate value.44///45/// Calling [`clone`] always produces a new value.46/// However, for types that are references to other data (such as smart pointers or references),47/// the new value may still point to the same underlying data, rather than duplicating it.48/// See [`Clone::clone`] for more details.49///50/// This distinction is especially important when using `#[derive(Clone)]` on structs containing51/// smart pointers like `Arc<Mutex<T>>` - the cloned struct will share mutable state with the52/// original.53///54/// Differs from [`Copy`] in that [`Copy`] is implicit and an inexpensive bit-wise copy, while55/// `Clone` is always explicit and may or may not be expensive. In order to enforce56/// these characteristics, Rust does not allow you to reimplement [`Copy`], but you57/// may reimplement `Clone` and run arbitrary code.58///59/// Since `Clone` is more general than [`Copy`], you can automatically make anything60/// [`Copy`] be `Clone` as well.61///62/// ## Derivable63///64/// This trait can be used with `#[derive]` if all fields are `Clone`. The `derive`d65/// implementation of [`Clone`] calls [`clone`] on each field.66///67/// [`clone`]: Clone::clone68///69/// For a generic struct, `#[derive]` implements `Clone` conditionally by adding bound `Clone` on70/// generic parameters.71///72/// ```73/// // `derive` implements Clone for Reading<T> when T is Clone.74/// #[derive(Clone)]75/// struct Reading<T> {76/// frequency: T,77/// }78/// ```79///80/// ## How can I implement `Clone`?81///82/// Types that are [`Copy`] should have a trivial implementation of `Clone`. More formally:83/// if `T: Copy`, `x: T`, and `y: &T`, then `let x = y.clone();` is equivalent to `let x = *y;`.84/// Manual implementations should be careful to uphold this invariant; however, unsafe code85/// must not rely on it to ensure memory safety.86///87/// An example is a generic struct holding a function pointer. In this case, the88/// implementation of `Clone` cannot be `derive`d, but can be implemented as:89///90/// ```91/// struct Generate<T>(fn() -> T);92///93/// impl<T> Copy for Generate<T> {}94///95/// impl<T> Clone for Generate<T> {96/// fn clone(&self) -> Self {97/// *self98/// }99/// }100/// ```101///102/// If we `derive`:103///104/// ```105/// #[derive(Copy, Clone)]106/// struct Generate<T>(fn() -> T);107/// ```108///109/// the auto-derived implementations will have unnecessary `T: Copy` and `T: Clone` bounds:110///111/// ```112/// # struct Generate<T>(fn() -> T);113///114/// // Automatically derived115/// impl<T: Copy> Copy for Generate<T> { }116///117/// // Automatically derived118/// impl<T: Clone> Clone for Generate<T> {119/// fn clone(&self) -> Generate<T> {120/// Generate(Clone::clone(&self.0))121/// }122/// }123/// ```124///125/// The bounds are unnecessary because clearly the function itself should be126/// copy- and cloneable even if its return type is not:127///128/// ```compile_fail,E0599129/// #[derive(Copy, Clone)]130/// struct Generate<T>(fn() -> T);131///132/// struct NotCloneable;133///134/// fn generate_not_cloneable() -> NotCloneable {135/// NotCloneable136/// }137///138/// Generate(generate_not_cloneable).clone(); // error: trait bounds were not satisfied139/// // Note: With the manual implementations the above line will compile.140/// ```141///142/// ## Additional implementors143///144/// In addition to the [implementors listed below][impls],145/// the following types also implement `Clone`:146///147/// * Function item types (i.e., the distinct types defined for each function)148/// * Function pointer types (e.g., `fn() -> i32`)149/// * Closure types, if they capture no value from the environment150/// or if all such captured values implement `Clone` themselves.151/// Note that variables captured by shared reference always implement `Clone`152/// (even if the referent doesn't),153/// while variables captured by mutable reference never implement `Clone`.154///155/// [impls]: #implementors156#[stable(feature ="rust1", since ="1.0.0")]157#[lang ="clone"]158#[rustc_diagnostic_item ="Clone"]159#[rustc_trivial_field_reads]160#[rustc_const_unstable(feature ="const_clone", issue ="142757")]161#[const_trait]162pub traitClone: Sized {163/// Returns a duplicate of the value.164 ///165 /// Note that what "duplicate" means varies by type:166 /// - For most types, this creates a deep, independent copy167 /// - For reference types like `&T`, this creates another reference to the same value168 /// - For smart pointers like [`Arc`] or [`Rc`], this increments the reference count169 /// but still points to the same underlying data170 ///171 /// [`Arc`]: ../../std/sync/struct.Arc.html172 /// [`Rc`]: ../../std/rc/struct.Rc.html173 ///174 /// # Examples175 ///176 /// ```177 /// # #![allow(noop_method_call)]178 /// let hello = "Hello"; // &str implements Clone179 ///180 /// assert_eq!("Hello", hello.clone());181 /// ```182 ///183 /// Example with a reference-counted type:184 ///185 /// ```186 /// use std::sync::{Arc, Mutex};187 ///188 /// let data = Arc::new(Mutex::new(vec![1, 2, 3]));189 /// let data_clone = data.clone(); // Creates another Arc pointing to the same Mutex190 ///191 /// {192 /// let mut lock = data.lock().unwrap();193 /// lock.push(4);194 /// }195 ///196 /// // Changes are visible through the clone because they share the same underlying data197 /// assert_eq!(*data_clone.lock().unwrap(), vec![1, 2, 3, 4]);198 /// ```199#[stable(feature ="rust1", since ="1.0.0")]200 #[must_use ="cloning is often expensive and is not expected to have side effects"]201// Clone::clone is special because the compiler generates MIR to implement it for some types.202 // See InstanceKind::CloneShim.203#[lang ="clone_fn"]204fnclone(&self) ->Self;205206/// Performs copy-assignment from `source`.207 ///208 /// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality,209 /// but can be overridden to reuse the resources of `a` to avoid unnecessary210 /// allocations.211#[inline]212 #[stable(feature ="rust1", since ="1.0.0")]213fnclone_from(&mutself, source:&Self)214where215Self: ~constDestruct,216 {217*self= source.clone()218 }219}220221/// Derive macro generating an impl of the trait `Clone`.222#[rustc_builtin_macro]223#[stable(feature ="builtin_macro_prelude", since ="1.38.0")]224#[allow_internal_unstable(core_intrinsics, derive_clone_copy)]225pub macroClone($item:item) {226/* compiler built-in */227}228229/// Trait for objects whose [`Clone`] impl is lightweight (e.g. reference-counted)230///231/// Cloning an object implementing this trait should in general:232/// - be O(1) (constant) time regardless of the amount of data managed by the object,233/// - not require a memory allocation,234/// - not require copying more than roughly 64 bytes (a typical cache line size),235/// - not block the current thread,236/// - not have any semantic side effects (e.g. allocating a file descriptor), and237/// - not have overhead larger than a couple of atomic operations.238///239/// The `UseCloned` trait does not provide a method; instead, it indicates that240/// `Clone::clone` is lightweight, and allows the use of the `.use` syntax.241///242/// ## .use postfix syntax243///244/// Values can be `.use`d by adding `.use` postfix to the value you want to use.245///246/// ```ignore (this won't work until we land use)247/// fn foo(f: Foo) {248/// // if `Foo` implements `Copy` f would be copied into x.249/// // if `Foo` implements `UseCloned` f would be cloned into x.250/// // otherwise f would be moved into x.251/// let x = f.use;252/// // ...253/// }254/// ```255///256/// ## use closures257///258/// Use closures allow captured values to be automatically used.259/// This is similar to have a closure that you would call `.use` over each captured value.260#[unstable(feature ="ergonomic_clones", issue ="132290")]261#[lang ="use_cloned"]262pub traitUseCloned: Clone {263// Empty.264}265266macro_rules! impl_use_cloned {267 ($($t:ty)*) => {268 $(269#[unstable(feature ="ergonomic_clones", issue ="132290")]270implUseClonedfor$t{}271 )*272 }273}274275impl_use_cloned! {276 usize u8 u16 u32 u64 u128277 isize i8 i16 i32 i64 i128278 f16 f32 f64 f128279 bool char280}281282// FIXME(aburka): these structs are used solely by #[derive] to283// assert that every component of a type implements Clone or Copy.284//285// These structs should never appear in user code.286#[doc(hidden)]287#[allow(missing_debug_implementations)]288#[unstable(289 feature ="derive_clone_copy",290 reason ="deriving hack, should not be public",291 issue ="none"292)]293pub structAssertParamIsClone<T: Clone + PointeeSized> {294 _field:crate::marker::PhantomData<T>,295}296#[doc(hidden)]297#[allow(missing_debug_implementations)]298#[unstable(299 feature ="derive_clone_copy",300 reason ="deriving hack, should not be public",301 issue ="none"302)]303pub structAssertParamIsCopy<T: Copy + PointeeSized> {304 _field:crate::marker::PhantomData<T>,305}306307/// A generalization of [`Clone`] to [dynamically-sized types][DST] stored in arbitrary containers.308///309/// This trait is implemented for all types implementing [`Clone`], [slices](slice) of all310/// such types, and other dynamically-sized types in the standard library.311/// You may also implement this trait to enable cloning custom DSTs312/// (structures containing dynamically-sized fields), or use it as a supertrait to enable313/// cloning a [trait object].314///315/// This trait is normally used via operations on container types which support DSTs,316/// so you should not typically need to call `.clone_to_uninit()` explicitly except when317/// implementing such a container or otherwise performing explicit management of an allocation,318/// or when implementing `CloneToUninit` itself.319///320/// # Safety321///322/// Implementations must ensure that when `.clone_to_uninit(dest)` returns normally rather than323/// panicking, it always leaves `*dest` initialized as a valid value of type `Self`.324///325/// # Examples326///327// FIXME(#126799): when `Box::clone` allows use of `CloneToUninit`, rewrite these examples with it328// since `Rc` is a distraction.329///330/// If you are defining a trait, you can add `CloneToUninit` as a supertrait to enable cloning of331/// `dyn` values of your trait:332///333/// ```334/// #![feature(clone_to_uninit)]335/// use std::rc::Rc;336///337/// trait Foo: std::fmt::Debug + std::clone::CloneToUninit {338/// fn modify(&mut self);339/// fn value(&self) -> i32;340/// }341///342/// impl Foo for i32 {343/// fn modify(&mut self) {344/// *self *= 10;345/// }346/// fn value(&self) -> i32 {347/// *self348/// }349/// }350///351/// let first: Rc<dyn Foo> = Rc::new(1234);352///353/// let mut second = first.clone();354/// Rc::make_mut(&mut second).modify(); // make_mut() will call clone_to_uninit()355///356/// assert_eq!(first.value(), 1234);357/// assert_eq!(second.value(), 12340);358/// ```359///360/// The following is an example of implementing `CloneToUninit` for a custom DST.361/// (It is essentially a limited form of what `derive(CloneToUninit)` would do,362/// if such a derive macro existed.)363///364/// ```365/// #![feature(clone_to_uninit)]366/// use std::clone::CloneToUninit;367/// use std::mem::offset_of;368/// use std::rc::Rc;369///370/// #[derive(PartialEq)]371/// struct MyDst<T: ?Sized> {372/// label: String,373/// contents: T,374/// }375///376/// unsafe impl<T: ?Sized + CloneToUninit> CloneToUninit for MyDst<T> {377/// unsafe fn clone_to_uninit(&self, dest: *mut u8) {378/// // The offset of `self.contents` is dynamic because it depends on the alignment of T379/// // which can be dynamic (if `T = dyn SomeTrait`). Therefore, we have to obtain it380/// // dynamically by examining `self`, rather than using `offset_of!`.381/// //382/// // SAFETY: `self` by definition points somewhere before `&self.contents` in the same383/// // allocation.384/// let offset_of_contents = unsafe {385/// (&raw const self.contents).byte_offset_from_unsigned(self)386/// };387///388/// // Clone the *sized* fields of `self` (just one, in this example).389/// // (By cloning this first and storing it temporarily in a local variable, we avoid390/// // leaking it in case of any panic, using the ordinary automatic cleanup of local391/// // variables. Such a leak would be sound, but undesirable.)392/// let label = self.label.clone();393///394/// // SAFETY: The caller must provide a `dest` such that these field offsets are valid395/// // to write to.396/// unsafe {397/// // Clone the unsized field directly from `self` to `dest`.398/// self.contents.clone_to_uninit(dest.add(offset_of_contents));399///400/// // Now write all the sized fields.401/// //402/// // Note that we only do this once all of the clone() and clone_to_uninit() calls403/// // have completed, and therefore we know that there are no more possible panics;404/// // this ensures no memory leaks in case of panic.405/// dest.add(offset_of!(Self, label)).cast::<String>().write(label);406/// }407/// // All fields of the struct have been initialized; therefore, the struct is initialized,408/// // and we have satisfied our `unsafe impl CloneToUninit` obligations.409/// }410/// }411///412/// fn main() {413/// // Construct MyDst<[u8; 4]>, then coerce to MyDst<[u8]>.414/// let first: Rc<MyDst<[u8]>> = Rc::new(MyDst {415/// label: String::from("hello"),416/// contents: [1, 2, 3, 4],417/// });418///419/// let mut second = first.clone();420/// // make_mut() will call clone_to_uninit().421/// for elem in Rc::make_mut(&mut second).contents.iter_mut() {422/// *elem *= 10;423/// }424///425/// assert_eq!(first.contents, [1, 2, 3, 4]);426/// assert_eq!(second.contents, [10, 20, 30, 40]);427/// assert_eq!(second.label, "hello");428/// }429/// ```430///431/// # See Also432///433/// * [`Clone::clone_from`] is a safe function which may be used instead when [`Self: Sized`](Sized)434/// and the destination is already initialized; it may be able to reuse allocations owned by435/// the destination, whereas `clone_to_uninit` cannot, since its destination is assumed to be436/// uninitialized.437/// * [`ToOwned`], which allocates a new destination container.438///439/// [`ToOwned`]: ../../std/borrow/trait.ToOwned.html440/// [DST]: https://doc.rust-lang.org/reference/dynamically-sized-types.html441/// [trait object]: https://doc.rust-lang.org/reference/types/trait-object.html442#[unstable(feature ="clone_to_uninit", issue ="126799")]443pub unsafe traitCloneToUninit {444/// Performs copy-assignment from `self` to `dest`.445 ///446 /// This is analogous to `std::ptr::write(dest.cast(), self.clone())`,447 /// except that `Self` may be a dynamically-sized type ([`!Sized`](Sized)).448 ///449 /// Before this function is called, `dest` may point to uninitialized memory.450 /// After this function is called, `dest` will point to initialized memory; it will be451 /// sound to create a `&Self` reference from the pointer with the [pointer metadata]452 /// from `self`.453 ///454 /// # Safety455 ///456 /// Behavior is undefined if any of the following conditions are violated:457 ///458 /// * `dest` must be [valid] for writes for `size_of_val(self)` bytes.459 /// * `dest` must be properly aligned to `align_of_val(self)`.460 ///461 /// [valid]: crate::ptr#safety462 /// [pointer metadata]: crate::ptr::metadata()463 ///464 /// # Panics465 ///466 /// This function may panic. (For example, it might panic if memory allocation for a clone467 /// of a value owned by `self` fails.)468 /// If the call panics, then `*dest` should be treated as uninitialized memory; it must not be469 /// read or dropped, because even if it was previously valid, it may have been partially470 /// overwritten.471 ///472 /// The caller may wish to take care to deallocate the allocation pointed to by `dest`,473 /// if applicable, to avoid a memory leak (but this is not a requirement).474 ///475 /// Implementors should avoid leaking values by, upon unwinding, dropping all component values476 /// that might have already been created. (For example, if a `[Foo]` of length 3 is being477 /// cloned, and the second of the three calls to `Foo::clone()` unwinds, then the first `Foo`478 /// cloned should be dropped.)479unsafe fnclone_to_uninit(&self, dest:*mutu8);480}481482#[unstable(feature ="clone_to_uninit", issue ="126799")]483unsafe impl<T: Clone> CloneToUninitforT {484#[inline]485unsafe fnclone_to_uninit(&self, dest:*mutu8) {486// SAFETY: we're calling a specialization with the same contract487unsafe{ <Tasself::uninit::CopySpec>::clone_one(self, dest.cast::<T>()) }488 }489}490491#[unstable(feature ="clone_to_uninit", issue ="126799")]492unsafe impl<T: Clone> CloneToUninitfor[T] {493#[inline]494 #[cfg_attr(debug_assertions, track_caller)]495unsafe fnclone_to_uninit(&self, dest:*mutu8) {496letdest:*mut[T] = dest.with_metadata_of(self);497// SAFETY: we're calling a specialization with the same contract498unsafe{ <Tasself::uninit::CopySpec>::clone_slice(self, dest) }499 }500}501502#[unstable(feature ="clone_to_uninit", issue ="126799")]503unsafe implCloneToUninitforstr {504#[inline]505 #[cfg_attr(debug_assertions, track_caller)]506unsafe fnclone_to_uninit(&self, dest:*mutu8) {507// SAFETY: str is just a [u8] with UTF-8 invariant508unsafe{self.as_bytes().clone_to_uninit(dest) }509 }510}511512#[unstable(feature ="clone_to_uninit", issue ="126799")]513unsafe implCloneToUninitforcrate::ffi::CStr {514#[cfg_attr(debug_assertions, track_caller)]515unsafe fnclone_to_uninit(&self, dest:*mutu8) {516// SAFETY: For now, CStr is just a #[repr(trasnsparent)] [c_char] with some invariants.517 // And we can cast [c_char] to [u8] on all supported platforms (see: to_bytes_with_nul).518 // The pointer metadata properly preserves the length (so NUL is also copied).519 // See: `cstr_metadata_is_length_with_nul` in tests.520unsafe{self.to_bytes_with_nul().clone_to_uninit(dest) }521 }522}523524#[unstable(feature ="bstr", issue ="134915")]525unsafe implCloneToUninitforcrate::bstr::ByteStr {526#[inline]527 #[cfg_attr(debug_assertions, track_caller)]528unsafe fnclone_to_uninit(&self, dst:*mutu8) {529// SAFETY: ByteStr is a `#[repr(transparent)]` wrapper around `[u8]`530unsafe{self.as_bytes().clone_to_uninit(dst) }531 }532}533534/// Implementations of `Clone` for primitive types.535///536/// Implementations that cannot be described in Rust537/// are implemented in `traits::SelectionContext::copy_clone_conditions()`538/// in `rustc_trait_selection`.539modimpls {540usecrate::marker::PointeeSized;541542macro_rules! impl_clone {543 ($($t:ty)*) => {544 $(545#[stable(feature ="rust1", since ="1.0.0")]546implClonefor$t{547#[inline(always)]548fnclone(&self) ->Self{549*self550}551 }552 )*553 }554 }555556impl_clone! {557 usize u8 u16 u32 u64 u128558 isize i8 i16 i32 i64 i128559 f16 f32 f64 f128560 bool char561 }562563#[unstable(feature ="never_type", issue ="35121")]564implClonefor! {565#[inline]566fnclone(&self) ->Self{567*self568}569 }570571#[stable(feature ="rust1", since ="1.0.0")]572impl<T: PointeeSized> Clonefor*constT {573#[inline(always)]574fnclone(&self) ->Self{575*self576}577 }578579#[stable(feature ="rust1", since ="1.0.0")]580impl<T: PointeeSized> Clonefor*mutT {581#[inline(always)]582fnclone(&self) ->Self{583*self584}585 }586587/// Shared references can be cloned, but mutable references *cannot*!588#[stable(feature ="rust1", since ="1.0.0")]589impl<T: PointeeSized> Clonefor&T {590#[inline(always)]591 #[rustc_diagnostic_item ="noop_method_clone"]592fnclone(&self) ->Self{593*self594}595 }596597/// Shared references can be cloned, but mutable references *cannot*!598#[stable(feature ="rust1", since ="1.0.0")]599impl<T: PointeeSized> !Clonefor&mutT {}600}