Rust standard library

library/core/src/clone.rs

This is Rust standard-library source from the compiler version used in the run.

Download Rust file

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 //! ```36 37 #![stable(feature = "rust1", since = "1.0.0")]38 39 use crate::marker::{Destruct, PointeeSized};40 41 mod uninit;42 43 /// 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. [`Copy`] has no methods, so you56 /// cannot change its behavior, but when implementing `Clone`, the `clone` method you provide57 /// may run arbitrary code.58 ///59 /// Since `Clone` is a supertrait of [`Copy`], any type that implements `Copy` must also implement60 /// `Clone`.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 /// ## `Clone` and `PartialEq`/`Eq`143 /// `Clone` is intended for the duplication of objects. Consequently, when implementing144 /// both `Clone` and [`PartialEq`], the following property is expected to hold:145 /// ```text146 /// x == x -> x.clone() == x147 /// ```148 /// In other words, if an object compares equal to itself,149 /// its clone must also compare equal to the original.150 ///151 /// For types that also implement [`Eq`] – for which `x == x` always holds –152 /// this implies that `x.clone() == x` must always be true.153 /// Standard library collections such as154 /// [`HashMap`], [`HashSet`], [`BTreeMap`], [`BTreeSet`] and [`BinaryHeap`]155 /// rely on their keys respecting this property for correct behavior.156 /// Furthermore, these collections require that cloning a key preserves the outcome of the157 /// [`Hash`] and [`Ord`] methods. Thankfully, this follows automatically from `x.clone() == x`158 /// if `Hash` and `Ord` are correctly implemented according to their own requirements.159 ///160 /// When deriving both `Clone` and [`PartialEq`] using `#[derive(Clone, PartialEq)]`161 /// or when additionally deriving [`Eq`] using `#[derive(Clone, PartialEq, Eq)]`,162 /// then this property is automatically upheld – provided that it is satisfied by163 /// the underlying types.164 ///165 /// Violating this property is a logic error. The behavior resulting from a logic error is not166 /// specified, but users of the trait must ensure that such logic errors do *not* result in167 /// undefined behavior. This means that `unsafe` code **must not** rely on this property168 /// being satisfied.169 ///170 /// ## Additional implementors171 ///172 /// In addition to the [implementors listed below][impls],173 /// the following types also implement `Clone`:174 ///175 /// * Function item types (i.e., the distinct types defined for each function)176 /// * Function pointer types (e.g., `fn() -> i32`)177 /// * Closure types, if they capture no value from the environment178 ///   or if all such captured values implement `Clone` themselves.179 ///   Note that variables captured by shared reference always implement `Clone`180 ///   (even if the referent doesn't),181 ///   while variables captured by mutable reference never implement `Clone`.182 ///183 /// [`HashMap`]: ../../std/collections/struct.HashMap.html184 /// [`HashSet`]: ../../std/collections/struct.HashSet.html185 /// [`BTreeMap`]: ../../std/collections/struct.BTreeMap.html186 /// [`BTreeSet`]: ../../std/collections/struct.BTreeSet.html187 /// [`BinaryHeap`]: ../../std/collections/struct.BinaryHeap.html188 /// [impls]: #implementors189 #[stable(feature = "rust1", since = "1.0.0")]190 #[lang = "clone"]191 #[rustc_diagnostic_item = "Clone"]192 #[rustc_trivial_field_reads]193 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]194 pub const trait Clone: Sized {195     /// Returns a duplicate of the value.196     ///197     /// Note that what "duplicate" means varies by type:198     /// - For most types, this creates a deep, independent copy199     /// - For reference types like `&T`, this creates another reference to the same value200     /// - For smart pointers like [`Arc`] or [`Rc`], this increments the reference count201     ///   but still points to the same underlying data202     ///203     /// [`Arc`]: ../../std/sync/struct.Arc.html204     /// [`Rc`]: ../../std/rc/struct.Rc.html205     ///206     /// # Examples207     ///208     /// ```209     /// # #![allow(noop_method_call)]210     /// let hello = "Hello"; // &str implements Clone211     ///212     /// assert_eq!("Hello", hello.clone());213     /// ```214     ///215     /// Example with a reference-counted type:216     ///217     /// ```218     /// use std::sync::{Arc, Mutex};219     ///220     /// let data = Arc::new(Mutex::new(vec![1, 2, 3]));221     /// let data_clone = data.clone(); // Creates another Arc pointing to the same Mutex222     ///223     /// {224     ///     let mut lock = data.lock().unwrap();225     ///     lock.push(4);226     /// }227     ///228     /// // Changes are visible through the clone because they share the same underlying data229     /// assert_eq!(*data_clone.lock().unwrap(), vec![1, 2, 3, 4]);230     /// ```231     #[stable(feature = "rust1", since = "1.0.0")]232     #[must_use = "cloning is often expensive and is not expected to have side effects"]233     // Clone::clone is special because the compiler generates MIR to implement it for some types.234     // See InstanceKind::CloneShim.235     #[lang = "clone_fn"]236     fn clone(&self) -> Self;237 238     /// Performs copy-assignment from `source`.239     ///240     /// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality,241     /// but can be overridden to reuse the resources of `a` to avoid unnecessary242     /// allocations.243     #[inline]244     #[stable(feature = "rust1", since = "1.0.0")]245     fn clone_from(&mut self, source: &Self)246     where247         Self: [const] Destruct,248     {249         *self = source.clone()250     }251 }252 253 /// Indicates that the `Clone` implementation is identical to copying the value.254 ///255 /// This is used for some optimizations in the standard library, which specializes256 /// on this trait to select faster implementations of functions such as257 /// [`clone_from_slice`](slice::clone_from_slice). It is automatically implemented258 /// when using `#[derive(Clone, Copy)]`.259 ///260 /// Note that this trait does not imply that the type is `Copy`, because e.g.261 /// `core::ops::Range<i32>` could soundly implement this trait.262 ///263 /// # Safety264 /// `Clone::clone` must be equivalent to copying the value, otherwise calling functions265 /// such as `slice::clone_from_slice` can have undefined behaviour.266 #[unstable(267     feature = "trivial_clone",268     reason = "this isn't part of any API guarantee",269     issue = "none"270 )]271 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]272 #[lang = "trivial_clone"]273 // SAFETY:274 // It is sound to specialize on this because the `clone` implementation cannot be275 // lifetime-dependent. Therefore, if `TrivialClone` is implemented for any lifetime,276 // its invariant holds whenever `Clone` is implemented, even if the actual277 // `TrivialClone` bound would not be satisfied because of lifetime bounds.278 #[rustc_unsafe_specialization_marker]279 // If `#[derive(Clone, Clone, Copy)]` is written, there will be multiple280 // implementations of `TrivialClone`. To keep it from appearing in error281 // messages, make it a `#[marker]` trait.282 #[marker]283 pub const unsafe trait TrivialClone: [const] Clone {}284 285 /// Derive macro generating an impl of the trait `Clone`.286 #[rustc_builtin_macro]287 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]288 #[allow_internal_unstable(core_intrinsics, derive_clone_copy_internals, trivial_clone)]289 pub macro Clone($item:item) {290     /* compiler built-in */291 }292 293 /// A trait for types whose [`Clone`] operation creates another alias to the same294 /// logical resource or shared state.295 ///296 /// `Share` marks types where cloning creates another handle, reference, or alias297 /// to the same logical resource or shared state, rather than an independent owned298 /// value. The distinction is semantic, not cost-based: implementing `Share` does299 /// not merely mean that cloning is cheap, constant-time, allocation-free, or300 /// convenient.301 ///302 /// Calling [`share`](Share::share) is equivalent to calling [`clone`](Clone::clone)303 /// for implementors, but communicates that the resulting value aliases the same304 /// underlying resource.305 ///306 /// Shared references, `Rc<T>`, `Arc<T>`, `Sender<T>`, and `SyncSender<T>` are307 /// examples of types that can be shared this way. Types such as `Vec<T>`,308 /// `String`, and `Box<T>` are not `Share` even though they implement `Clone`,309 /// because cloning them creates another owned value rather than another handle310 /// to the same logical resource.311 ///312 /// # Examples313 ///314 /// ```315 /// #![feature(share_trait)]316 ///317 /// use std::cell::Cell;318 /// use std::clone::Share;319 /// use std::rc::Rc;320 /// use std::sync::{321 ///     Arc,322 ///     atomic::{AtomicUsize, Ordering},323 /// };324 ///325 /// let value = 1;326 /// let reference = &value;327 /// assert!(std::ptr::eq(reference, reference.share()));328 ///329 /// let rc = Rc::new(Cell::new(2));330 /// let shared_rc = rc.share();331 /// assert!(Rc::ptr_eq(&rc, &shared_rc));332 /// shared_rc.set(3);333 /// assert_eq!(rc.get(), 3);334 ///335 /// let arc = Arc::new(AtomicUsize::new(4));336 /// let shared_arc = arc.share();337 /// assert!(Arc::ptr_eq(&arc, &shared_arc));338 /// shared_arc.store(5, Ordering::Relaxed);339 /// assert_eq!(arc.load(Ordering::Relaxed), 5);340 /// ```341 ///342 /// ```343 /// #![feature(share_trait)]344 ///345 /// use std::clone::Share;346 /// use std::sync::mpsc::{channel, sync_channel};347 ///348 /// let (sender, receiver) = channel();349 /// let shared_sender = sender.share();350 /// sender.send(1).unwrap();351 /// shared_sender.send(2).unwrap();352 ///353 /// let mut received = [receiver.recv().unwrap(), receiver.recv().unwrap()];354 /// received.sort();355 /// assert_eq!(received, [1, 2]);356 ///357 /// let (sync_sender, sync_receiver) = sync_channel(2);358 /// let shared_sync_sender = sync_sender.share();359 /// sync_sender.send(3).unwrap();360 /// shared_sync_sender.send(4).unwrap();361 ///362 /// let mut received = [sync_receiver.recv().unwrap(), sync_receiver.recv().unwrap()];363 /// received.sort();364 /// assert_eq!(received, [3, 4]);365 /// ```366 #[unstable(feature = "share_trait", issue = "156756")]367 pub trait Share: Clone {368     /// Creates another alias to the same underlying resource or shared state.369     ///370     /// This is equivalent to calling [`Clone::clone`].371     #[unstable(feature = "share_trait", issue = "156756")]372     fn share(&self) -> Self {373         Clone::clone(self)374     }375 }376 377 /// Trait for objects whose [`Clone`] impl is lightweight (e.g. reference-counted)378 ///379 /// Cloning an object implementing this trait should in general:380 /// - be O(1) (constant) time regardless of the amount of data managed by the object,381 /// - not require a memory allocation,382 /// - not require copying more than roughly 64 bytes (a typical cache line size),383 /// - not block the current thread,384 /// - not have any semantic side effects (e.g. allocating a file descriptor), and385 /// - not have overhead larger than a couple of atomic operations.386 ///387 /// The `UseCloned` trait does not provide a method; instead, it indicates that388 /// `Clone::clone` is lightweight, and allows the use of the `.use` syntax.389 ///390 /// ## .use postfix syntax391 ///392 /// Values can be `.use`d by adding `.use` postfix to the value you want to use.393 ///394 /// ```ignore (this won't work until we land use)395 /// fn foo(f: Foo) {396 ///     // if `Foo` implements `Copy` f would be copied into x.397 ///     // if `Foo` implements `UseCloned` f would be cloned into x.398 ///     // otherwise f would be moved into x.399 ///     let x = f.use;400 ///     // ...401 /// }402 /// ```403 ///404 /// ## use closures405 ///406 /// Use closures allow captured values to be automatically used.407 /// This is similar to have a closure that you would call `.use` over each captured value.408 #[unstable(feature = "ergonomic_clones", issue = "132290")]409 #[lang = "use_cloned"]410 pub trait UseCloned: Clone {411     // Empty.412 }413 414 macro_rules! impl_use_cloned {415     ($($t:ty)*) => {416         $(417             #[unstable(feature = "ergonomic_clones", issue = "132290")]418             impl UseCloned for $t {}419         )*420     }421 }422 423 impl_use_cloned! {424     usize u8 u16 u32 u64 u128425     isize i8 i16 i32 i64 i128426              f16 f32 f64 f128427     bool char428 }429 430 // FIXME(aburka): these structs are used solely by #[derive] to431 // assert that every component of a type implements Clone or Copy.432 //433 // These structs should never appear in user code.434 #[doc(hidden)]435 #[allow(missing_debug_implementations)]436 #[unstable(437     feature = "derive_clone_copy_internals",438     reason = "deriving hack, should not be public",439     issue = "none"440 )]441 pub struct AssertParamIsClone<T: Clone + PointeeSized> {442     _field: crate::marker::PhantomData<T>,443 }444 #[doc(hidden)]445 #[allow(missing_debug_implementations)]446 #[unstable(447     feature = "derive_clone_copy_internals",448     reason = "deriving hack, should not be public",449     issue = "none"450 )]451 pub struct AssertParamIsCopy<T: Copy + PointeeSized> {452     _field: crate::marker::PhantomData<T>,453 }454 455 /// A generalization of [`Clone`] to [dynamically-sized types][DST] stored in arbitrary containers.456 ///457 /// This trait is implemented for all types implementing [`Clone`], [slices](slice) of all458 /// such types, and other dynamically-sized types in the standard library.459 /// You may also implement this trait to enable cloning custom DSTs460 /// (structures containing dynamically-sized fields), or use it as a supertrait to enable461 /// cloning a [trait object].462 ///463 /// This trait is normally used via operations on container types which support DSTs,464 /// so you should not typically need to call `.clone_to_uninit()` explicitly except when465 /// implementing such a container or otherwise performing explicit management of an allocation,466 /// or when implementing `CloneToUninit` itself.467 ///468 /// # Safety469 ///470 /// Implementations must ensure that when `.clone_to_uninit(dest)` returns normally rather than471 /// panicking, it always leaves `*dest` initialized as a valid value of type `Self`.472 ///473 /// # Examples474 ///475 // FIXME(#126799): when `Box::clone` allows use of `CloneToUninit`, rewrite these examples with it476 // since `Rc` is a distraction.477 ///478 /// If you are defining a trait, you can add `CloneToUninit` as a supertrait to enable cloning of479 /// `dyn` values of your trait:480 ///481 /// ```482 /// #![feature(clone_to_uninit)]483 /// use std::rc::Rc;484 ///485 /// trait Foo: std::fmt::Debug + std::clone::CloneToUninit {486 ///     fn modify(&mut self);487 ///     fn value(&self) -> i32;488 /// }489 ///490 /// impl Foo for i32 {491 ///     fn modify(&mut self) {492 ///         *self *= 10;493 ///     }494 ///     fn value(&self) -> i32 {495 ///         *self496 ///     }497 /// }498 ///499 /// let first: Rc<dyn Foo> = Rc::new(1234);500 ///501 /// let mut second = first.clone();502 /// Rc::make_mut(&mut second).modify(); // make_mut() will call clone_to_uninit()503 ///504 /// assert_eq!(first.value(), 1234);505 /// assert_eq!(second.value(), 12340);506 /// ```507 ///508 /// The following is an example of implementing `CloneToUninit` for a custom DST.509 /// (It is essentially a limited form of what `derive(CloneToUninit)` would do,510 /// if such a derive macro existed.)511 ///512 /// ```513 /// #![feature(clone_to_uninit)]514 /// use std::clone::CloneToUninit;515 /// use std::mem::offset_of;516 /// use std::rc::Rc;517 ///518 /// #[derive(PartialEq)]519 /// struct MyDst<T: ?Sized> {520 ///     label: String,521 ///     contents: T,522 /// }523 ///524 /// unsafe impl<T: ?Sized + CloneToUninit> CloneToUninit for MyDst<T> {525 ///     unsafe fn clone_to_uninit(&self, dest: *mut u8) {526 ///         // The offset of `self.contents` is dynamic because it depends on the alignment of T527 ///         // which can be dynamic (if `T = dyn SomeTrait`). Therefore, we have to obtain it528 ///         // dynamically by examining `self`, rather than using `offset_of!`.529 ///         //530 ///         // SAFETY: `self` by definition points somewhere before `&self.contents` in the same531 ///         // allocation.532 ///         let offset_of_contents = unsafe {533 ///             (&raw const self.contents).byte_offset_from_unsigned(self)534 ///         };535 ///536 ///         // Clone the *sized* fields of `self` (just one, in this example).537 ///         // (By cloning this first and storing it temporarily in a local variable, we avoid538 ///         // leaking it in case of any panic, using the ordinary automatic cleanup of local539 ///         // variables. Such a leak would be sound, but undesirable.)540 ///         let label = self.label.clone();541 ///542 ///         // SAFETY: The caller must provide a `dest` such that these field offsets are valid543 ///         // to write to.544 ///         unsafe {545 ///             // Clone the unsized field directly from `self` to `dest`.546 ///             self.contents.clone_to_uninit(dest.add(offset_of_contents));547 ///548 ///             // Now write all the sized fields.549 ///             //550 ///             // Note that we only do this once all of the clone() and clone_to_uninit() calls551 ///             // have completed, and therefore we know that there are no more possible panics;552 ///             // this ensures no memory leaks in case of panic.553 ///             dest.add(offset_of!(Self, label)).cast::<String>().write(label);554 ///         }555 ///         // All fields of the struct have been initialized; therefore, the struct is initialized,556 ///         // and we have satisfied our `unsafe impl CloneToUninit` obligations.557 ///     }558 /// }559 ///560 /// fn main() {561 ///     // Construct MyDst<[u8; 4]>, then coerce to MyDst<[u8]>.562 ///     let first: Rc<MyDst<[u8]>> = Rc::new(MyDst {563 ///         label: String::from("hello"),564 ///         contents: [1, 2, 3, 4],565 ///     });566 ///567 ///     let mut second = first.clone();568 ///     // make_mut() will call clone_to_uninit().569 ///     for elem in Rc::make_mut(&mut second).contents.iter_mut() {570 ///         *elem *= 10;571 ///     }572 ///573 ///     assert_eq!(first.contents, [1, 2, 3, 4]);574 ///     assert_eq!(second.contents, [10, 20, 30, 40]);575 ///     assert_eq!(second.label, "hello");576 /// }577 /// ```578 ///579 /// # See Also580 ///581 /// * [`Clone::clone_from`] is a safe function which may be used instead when [`Self: Sized`](Sized)582 ///   and the destination is already initialized; it may be able to reuse allocations owned by583 ///   the destination, whereas `clone_to_uninit` cannot, since its destination is assumed to be584 ///   uninitialized.585 /// * [`ToOwned`], which allocates a new destination container.586 ///587 /// [`ToOwned`]: ../../std/borrow/trait.ToOwned.html588 /// [DST]: https://doc.rust-lang.org/reference/dynamically-sized-types.html589 /// [trait object]: https://doc.rust-lang.org/reference/types/trait-object.html590 #[unstable(feature = "clone_to_uninit", issue = "126799")]591 pub unsafe trait CloneToUninit {592     /// Performs copy-assignment from `self` to `dest`.593     ///594     /// This is analogous to `std::ptr::write(dest.cast(), self.clone())`,595     /// except that `Self` may be a dynamically-sized type ([`!Sized`](Sized)).596     ///597     /// Before this function is called, `dest` may point to uninitialized memory.598     /// After this function is called, `dest` will point to initialized memory; it will be599     /// sound to create a `&Self` reference from the pointer with the [pointer metadata]600     /// from `self`.601     ///602     /// # Safety603     ///604     /// Behavior is undefined if any of the following conditions are violated:605     ///606     /// * `dest` must be [valid] for writes for `size_of_val(self)` bytes.607     /// * `dest` must be properly aligned to `align_of_val(self)`.608     ///609     /// [valid]: crate::ptr#safety610     /// [pointer metadata]: crate::ptr::metadata()611     ///612     /// # Panics613     ///614     /// This function may panic. (For example, it might panic if memory allocation for a clone615     /// of a value owned by `self` fails.)616     /// If the call panics, then `*dest` should be treated as uninitialized memory; it must not be617     /// read or dropped, because even if it was previously valid, it may have been partially618     /// overwritten.619     ///620     /// The caller may wish to take care to deallocate the allocation pointed to by `dest`,621     /// if applicable, to avoid a memory leak (but this is not a requirement).622     ///623     /// Implementors should avoid leaking values by, upon unwinding, dropping all component values624     /// that might have already been created. (For example, if a `[Foo]` of length 3 is being625     /// cloned, and the second of the three calls to `Foo::clone()` unwinds, then the first `Foo`626     /// cloned should be dropped.)627     unsafe fn clone_to_uninit(&self, dest: *mut u8);628 }629 630 #[unstable(feature = "clone_to_uninit", issue = "126799")]631 unsafe impl<T: Clone> CloneToUninit for T {632     #[inline]633     unsafe fn clone_to_uninit(&self, dest: *mut u8) {634         // SAFETY: we're calling a specialization with the same contract635         unsafe { <T as self::uninit::CopySpec>::clone_one(self, dest.cast::<T>()) }636     }637 }638 639 #[unstable(feature = "clone_to_uninit", issue = "126799")]640 unsafe impl<T: Clone> CloneToUninit for [T] {641     #[inline]642     #[cfg_attr(debug_assertions, track_caller)]643     unsafe fn clone_to_uninit(&self, dest: *mut u8) {644         let dest: *mut [T] = dest.with_metadata_of(self);645         // SAFETY: we're calling a specialization with the same contract646         unsafe { <T as self::uninit::CopySpec>::clone_slice(self, dest) }647     }648 }649 650 #[unstable(feature = "clone_to_uninit", issue = "126799")]651 unsafe impl CloneToUninit for str {652     #[inline]653     #[cfg_attr(debug_assertions, track_caller)]654     unsafe fn clone_to_uninit(&self, dest: *mut u8) {655         // SAFETY: str is just a [u8] with UTF-8 invariant656         unsafe { self.as_bytes().clone_to_uninit(dest) }657     }658 }659 660 #[unstable(feature = "clone_to_uninit", issue = "126799")]661 unsafe impl CloneToUninit for crate::ffi::CStr {662     #[cfg_attr(debug_assertions, track_caller)]663     unsafe fn clone_to_uninit(&self, dest: *mut u8) {664         // SAFETY: For now, CStr is just a #[repr(trasnsparent)] [c_char] with some invariants.665         // And we can cast [c_char] to [u8] on all supported platforms (see: to_bytes_with_nul).666         // The pointer metadata properly preserves the length (so NUL is also copied).667         // See: `cstr_metadata_is_length_with_nul` in tests.668         unsafe { self.to_bytes_with_nul().clone_to_uninit(dest) }669     }670 }671 672 #[unstable(feature = "bstr", issue = "134915")]673 unsafe impl CloneToUninit for crate::bstr::ByteStr {674     #[inline]675     #[cfg_attr(debug_assertions, track_caller)]676     unsafe fn clone_to_uninit(&self, dst: *mut u8) {677         // SAFETY: ByteStr is a `#[repr(transparent)]` wrapper around `[u8]`678         unsafe { self.as_bytes().clone_to_uninit(dst) }679     }680 }681 682 /// Implementations of `Clone` for primitive types.683 ///684 /// Implementations that cannot be described in Rust685 /// are implemented in `traits::SelectionContext::copy_clone_conditions()`686 /// in `rustc_trait_selection`.687 mod impls {688     use super::{Share, TrivialClone};689     use crate::marker::PointeeSized;690 691     macro_rules! impl_clone {692         ($($t:ty)*) => {693             $(694                 #[stable(feature = "rust1", since = "1.0.0")]695                 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]696                 impl const Clone for $t {697                     #[inline(always)]698                     fn clone(&self) -> Self {699                         *self700                     }701                 }702 703                 #[doc(hidden)]704                 #[unstable(feature = "trivial_clone", issue = "none")]705                 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]706                 unsafe impl const TrivialClone for $t {}707             )*708         }709     }710 711     impl_clone! {712         usize u8 u16 u32 u64 u128713         isize i8 i16 i32 i64 i128714         f16 f32 f64 f128715         bool char716     }717 718     #[unstable(feature = "never_type", issue = "35121")]719     #[rustc_const_unstable(feature = "const_clone", issue = "142757")]720     const impl Clone for ! {721         #[inline]722         fn clone(&self) -> Self {723             *self724         }725     }726 727     #[doc(hidden)]728     #[unstable(feature = "trivial_clone", issue = "none")]729     #[rustc_const_unstable(feature = "const_clone", issue = "142757")]730     const unsafe impl TrivialClone for ! {}731 732     #[stable(feature = "rust1", since = "1.0.0")]733     #[rustc_const_unstable(feature = "const_clone", issue = "142757")]734     const impl<T: PointeeSized> Clone for *const T {735         #[inline(always)]736         fn clone(&self) -> Self {737             *self738         }739     }740 741     #[doc(hidden)]742     #[unstable(feature = "trivial_clone", issue = "none")]743     #[rustc_const_unstable(feature = "const_clone", issue = "142757")]744     const unsafe impl<T: PointeeSized> TrivialClone for *const T {}745 746     #[stable(feature = "rust1", since = "1.0.0")]747     #[rustc_const_unstable(feature = "const_clone", issue = "142757")]748     const impl<T: PointeeSized> Clone for *mut T {749         #[inline(always)]750         fn clone(&self) -> Self {751             *self752         }753     }754 755     #[doc(hidden)]756     #[unstable(feature = "trivial_clone", issue = "none")]757     #[rustc_const_unstable(feature = "const_clone", issue = "142757")]758     const unsafe impl<T: PointeeSized> TrivialClone for *mut T {}759 760     /// Shared references can be cloned, but mutable references *cannot*!761     #[stable(feature = "rust1", since = "1.0.0")]762     #[rustc_const_unstable(feature = "const_clone", issue = "142757")]763     const impl<T: PointeeSized> Clone for &T {764         #[inline(always)]765         #[rustc_diagnostic_item = "noop_method_clone"]766         fn clone(&self) -> Self {767             *self768         }769     }770 771     #[doc(hidden)]772     #[unstable(feature = "trivial_clone", issue = "none")]773     #[rustc_const_unstable(feature = "const_clone", issue = "142757")]774     const unsafe impl<T: PointeeSized> TrivialClone for &T {}775 776     #[unstable(feature = "share_trait", issue = "156756")]777     impl<T: PointeeSized> Share for &T {}778 779     /// Shared references can be cloned, but mutable references *cannot*!780     #[stable(feature = "rust1", since = "1.0.0")]781     impl<T: PointeeSized> !Clone for &mut T {}782 }
Reference details
commit14210df0e27ccd7d9e6a05b8085cbd438e4bbc65
sha25623f9cfc80347fde6b8457d46fbf7a2b8d9f34c8c58601b0b6f714ca2f6d1976b
urlhttps://raw.githubusercontent.com/rust-lang/rust/14210df0e27ccd7d9e6a05b8085cbd438e4bbc65/library/core/src/clone.rs