Skip to main content

core/
clone.rs

1//! The `Clone` trait for types that cannot be 'implicitly copied'.
2//!
3//! In Rust, some simple types are "implicitly copyable" and when you
4//! assign them or pass them as arguments, the receiver will get a copy,
5//! leaving the original value in place. These types do not require
6//! allocation to copy and do not have finalizers (i.e., they do not
7//! contain owned boxes or implement [`Drop`]), so the compiler considers
8//! them cheap and safe to copy. For other types copies must be made
9//! explicitly, by convention implementing the [`Clone`] trait and calling
10//! the [`clone`] method.
11//!
12//! [`clone`]: Clone::clone
13//!
14//! Basic usage example:
15//!
16//! ```
17//! let s = String::new(); // String type implements Clone
18//! let copy = s.clone(); // so we can clone it
19//! ```
20//!
21//! To easily implement the Clone trait, you can also use
22//! `#[derive(Clone)]`. Example:
23//!
24//! ```
25//! #[derive(Clone)] // we add the Clone trait to Morpheus struct
26//! 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
39use crate::marker::{Destruct, PointeeSized};
40
41mod 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 containing
51/// smart pointers like `Arc<Mutex<T>>` - the cloned struct will share mutable state with the
52/// original.
53///
54/// Differs from [`Copy`] in that [`Copy`] is implicit and an inexpensive bit-wise copy, while
55/// `Clone` is always explicit and may or may not be expensive. [`Copy`] has no methods, so you
56/// cannot change its behavior, but when implementing `Clone`, the `clone` method you provide
57/// may run arbitrary code.
58///
59/// Since `Clone` is a supertrait of [`Copy`], any type that implements `Copy` must also implement
60/// `Clone`.
61///
62/// ## Derivable
63///
64/// This trait can be used with `#[derive]` if all fields are `Clone`. The `derive`d
65/// implementation of [`Clone`] calls [`clone`] on each field.
66///
67/// [`clone`]: Clone::clone
68///
69/// For a generic struct, `#[derive]` implements `Clone` conditionally by adding bound `Clone` on
70/// 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 code
85/// must not rely on it to ensure memory safety.
86///
87/// An example is a generic struct holding a function pointer. In this case, the
88/// 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///         *self
98///     }
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 derived
115/// impl<T: Copy> Copy for Generate<T> { }
116///
117/// // Automatically derived
118/// 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 be
126/// copy- and cloneable even if its return type is not:
127///
128/// ```compile_fail,E0599
129/// #[derive(Copy, Clone)]
130/// struct Generate<T>(fn() -> T);
131///
132/// struct NotCloneable;
133///
134/// fn generate_not_cloneable() -> NotCloneable {
135///     NotCloneable
136/// }
137///
138/// Generate(generate_not_cloneable).clone(); // error: trait bounds were not satisfied
139/// // 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 implementing
144/// both `Clone` and [`PartialEq`], the following property is expected to hold:
145/// ```text
146/// x == x -> x.clone() == x
147/// ```
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 as
154/// [`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 the
157/// [`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 by
163/// the underlying types.
164///
165/// Violating this property is a logic error. The behavior resulting from a logic error is not
166/// specified, but users of the trait must ensure that such logic errors do *not* result in
167/// undefined behavior. This means that `unsafe` code **must not** rely on this property
168/// being satisfied.
169///
170/// ## Additional implementors
171///
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 environment
178///   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.html
184/// [`HashSet`]: ../../std/collections/struct.HashSet.html
185/// [`BTreeMap`]: ../../std/collections/struct.BTreeMap.html
186/// [`BTreeSet`]: ../../std/collections/struct.BTreeSet.html
187/// [`BinaryHeap`]: ../../std/collections/struct.BinaryHeap.html
188/// [impls]: #implementors
189#[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")]
194pub 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 copy
199    /// - For reference types like `&T`, this creates another reference to the same value
200    /// - For smart pointers like [`Arc`] or [`Rc`], this increments the reference count
201    ///   but still points to the same underlying data
202    ///
203    /// [`Arc`]: ../../std/sync/struct.Arc.html
204    /// [`Rc`]: ../../std/rc/struct.Rc.html
205    ///
206    /// # Examples
207    ///
208    /// ```
209    /// # #![allow(noop_method_call)]
210    /// let hello = "Hello"; // &str implements Clone
211    ///
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 Mutex
222    ///
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 data
229    /// 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 unnecessary
242    /// allocations.
243    #[inline]
244    #[stable(feature = "rust1", since = "1.0.0")]
245    #[ferrocene::prevalidated]
246    fn clone_from(&mut self, source: &Self)
247    where
248        Self: [const] Destruct,
249    {
250        *self = source.clone()
251    }
252}
253
254/// Indicates that the `Clone` implementation is identical to copying the value.
255///
256/// This is used for some optimizations in the standard library, which specializes
257/// on this trait to select faster implementations of functions such as
258/// [`clone_from_slice`](slice::clone_from_slice). It is automatically implemented
259/// when using `#[derive(Clone, Copy)]`.
260///
261/// Note that this trait does not imply that the type is `Copy`, because e.g.
262/// `core::ops::Range<i32>` could soundly implement this trait.
263///
264/// # Safety
265/// `Clone::clone` must be equivalent to copying the value, otherwise calling functions
266/// such as `slice::clone_from_slice` can have undefined behaviour.
267#[unstable(
268    feature = "trivial_clone",
269    reason = "this isn't part of any API guarantee",
270    issue = "none"
271)]
272#[rustc_const_unstable(feature = "const_clone", issue = "142757")]
273#[lang = "trivial_clone"]
274// SAFETY:
275// It is sound to specialize on this because the `clone` implementation cannot be
276// lifetime-dependent. Therefore, if `TrivialClone` is implemented for any lifetime,
277// its invariant holds whenever `Clone` is implemented, even if the actual
278// `TrivialClone` bound would not be satisfied because of lifetime bounds.
279#[rustc_unsafe_specialization_marker]
280// If `#[derive(Clone, Clone, Copy)]` is written, there will be multiple
281// implementations of `TrivialClone`. To keep it from appearing in error
282// messages, make it a `#[marker]` trait.
283#[marker]
284pub const unsafe trait TrivialClone: [const] Clone {}
285
286/// Derive macro generating an impl of the trait `Clone`.
287#[rustc_builtin_macro]
288#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
289#[allow_internal_unstable(core_intrinsics, derive_clone_copy_internals, trivial_clone)]
290pub macro Clone($item:item) {
291    /* compiler built-in */
292}
293
294/// Trait for objects whose [`Clone`] impl is lightweight (e.g. reference-counted)
295///
296/// Cloning an object implementing this trait should in general:
297/// - be O(1) (constant) time regardless of the amount of data managed by the object,
298/// - not require a memory allocation,
299/// - not require copying more than roughly 64 bytes (a typical cache line size),
300/// - not block the current thread,
301/// - not have any semantic side effects (e.g. allocating a file descriptor), and
302/// - not have overhead larger than a couple of atomic operations.
303///
304/// The `UseCloned` trait does not provide a method; instead, it indicates that
305/// `Clone::clone` is lightweight, and allows the use of the `.use` syntax.
306///
307/// ## .use postfix syntax
308///
309/// Values can be `.use`d by adding `.use` postfix to the value you want to use.
310///
311/// ```ignore (this won't work until we land use)
312/// fn foo(f: Foo) {
313///     // if `Foo` implements `Copy` f would be copied into x.
314///     // if `Foo` implements `UseCloned` f would be cloned into x.
315///     // otherwise f would be moved into x.
316///     let x = f.use;
317///     // ...
318/// }
319/// ```
320///
321/// ## use closures
322///
323/// Use closures allow captured values to be automatically used.
324/// This is similar to have a closure that you would call `.use` over each captured value.
325#[unstable(feature = "ergonomic_clones", issue = "132290")]
326#[lang = "use_cloned"]
327pub trait UseCloned: Clone {
328    // Empty.
329}
330
331macro_rules! impl_use_cloned {
332    ($($t:ty)*) => {
333        $(
334            #[unstable(feature = "ergonomic_clones", issue = "132290")]
335            impl UseCloned for $t {}
336        )*
337    }
338}
339
340impl_use_cloned! {
341    usize u8 u16 u32 u64 u128
342    isize i8 i16 i32 i64 i128
343             f16 f32 f64 f128
344    bool char
345}
346
347// FIXME(aburka): these structs are used solely by #[derive] to
348// assert that every component of a type implements Clone or Copy.
349//
350// These structs should never appear in user code.
351#[doc(hidden)]
352#[allow(missing_debug_implementations)]
353#[unstable(
354    feature = "derive_clone_copy_internals",
355    reason = "deriving hack, should not be public",
356    issue = "none"
357)]
358#[ferrocene::prevalidated]
359pub struct AssertParamIsClone<T: Clone + PointeeSized> {
360    _field: crate::marker::PhantomData<T>,
361}
362#[doc(hidden)]
363#[allow(missing_debug_implementations)]
364#[unstable(
365    feature = "derive_clone_copy_internals",
366    reason = "deriving hack, should not be public",
367    issue = "none"
368)]
369#[ferrocene::prevalidated]
370pub struct AssertParamIsCopy<T: Copy + PointeeSized> {
371    _field: crate::marker::PhantomData<T>,
372}
373
374/// A generalization of [`Clone`] to [dynamically-sized types][DST] stored in arbitrary containers.
375///
376/// This trait is implemented for all types implementing [`Clone`], [slices](slice) of all
377/// such types, and other dynamically-sized types in the standard library.
378/// You may also implement this trait to enable cloning custom DSTs
379/// (structures containing dynamically-sized fields), or use it as a supertrait to enable
380/// cloning a [trait object].
381///
382/// This trait is normally used via operations on container types which support DSTs,
383/// so you should not typically need to call `.clone_to_uninit()` explicitly except when
384/// implementing such a container or otherwise performing explicit management of an allocation,
385/// or when implementing `CloneToUninit` itself.
386///
387/// # Safety
388///
389/// Implementations must ensure that when `.clone_to_uninit(dest)` returns normally rather than
390/// panicking, it always leaves `*dest` initialized as a valid value of type `Self`.
391///
392/// # Examples
393///
394// FIXME(#126799): when `Box::clone` allows use of `CloneToUninit`, rewrite these examples with it
395// since `Rc` is a distraction.
396///
397/// If you are defining a trait, you can add `CloneToUninit` as a supertrait to enable cloning of
398/// `dyn` values of your trait:
399///
400/// ```
401/// #![feature(clone_to_uninit)]
402/// use std::rc::Rc;
403///
404/// trait Foo: std::fmt::Debug + std::clone::CloneToUninit {
405///     fn modify(&mut self);
406///     fn value(&self) -> i32;
407/// }
408///
409/// impl Foo for i32 {
410///     fn modify(&mut self) {
411///         *self *= 10;
412///     }
413///     fn value(&self) -> i32 {
414///         *self
415///     }
416/// }
417///
418/// let first: Rc<dyn Foo> = Rc::new(1234);
419///
420/// let mut second = first.clone();
421/// Rc::make_mut(&mut second).modify(); // make_mut() will call clone_to_uninit()
422///
423/// assert_eq!(first.value(), 1234);
424/// assert_eq!(second.value(), 12340);
425/// ```
426///
427/// The following is an example of implementing `CloneToUninit` for a custom DST.
428/// (It is essentially a limited form of what `derive(CloneToUninit)` would do,
429/// if such a derive macro existed.)
430///
431/// ```
432/// #![feature(clone_to_uninit)]
433/// use std::clone::CloneToUninit;
434/// use std::mem::offset_of;
435/// use std::rc::Rc;
436///
437/// #[derive(PartialEq)]
438/// struct MyDst<T: ?Sized> {
439///     label: String,
440///     contents: T,
441/// }
442///
443/// unsafe impl<T: ?Sized + CloneToUninit> CloneToUninit for MyDst<T> {
444///     unsafe fn clone_to_uninit(&self, dest: *mut u8) {
445///         // The offset of `self.contents` is dynamic because it depends on the alignment of T
446///         // which can be dynamic (if `T = dyn SomeTrait`). Therefore, we have to obtain it
447///         // dynamically by examining `self`, rather than using `offset_of!`.
448///         //
449///         // SAFETY: `self` by definition points somewhere before `&self.contents` in the same
450///         // allocation.
451///         let offset_of_contents = unsafe {
452///             (&raw const self.contents).byte_offset_from_unsigned(self)
453///         };
454///
455///         // Clone the *sized* fields of `self` (just one, in this example).
456///         // (By cloning this first and storing it temporarily in a local variable, we avoid
457///         // leaking it in case of any panic, using the ordinary automatic cleanup of local
458///         // variables. Such a leak would be sound, but undesirable.)
459///         let label = self.label.clone();
460///
461///         // SAFETY: The caller must provide a `dest` such that these field offsets are valid
462///         // to write to.
463///         unsafe {
464///             // Clone the unsized field directly from `self` to `dest`.
465///             self.contents.clone_to_uninit(dest.add(offset_of_contents));
466///
467///             // Now write all the sized fields.
468///             //
469///             // Note that we only do this once all of the clone() and clone_to_uninit() calls
470///             // have completed, and therefore we know that there are no more possible panics;
471///             // this ensures no memory leaks in case of panic.
472///             dest.add(offset_of!(Self, label)).cast::<String>().write(label);
473///         }
474///         // All fields of the struct have been initialized; therefore, the struct is initialized,
475///         // and we have satisfied our `unsafe impl CloneToUninit` obligations.
476///     }
477/// }
478///
479/// fn main() {
480///     // Construct MyDst<[u8; 4]>, then coerce to MyDst<[u8]>.
481///     let first: Rc<MyDst<[u8]>> = Rc::new(MyDst {
482///         label: String::from("hello"),
483///         contents: [1, 2, 3, 4],
484///     });
485///
486///     let mut second = first.clone();
487///     // make_mut() will call clone_to_uninit().
488///     for elem in Rc::make_mut(&mut second).contents.iter_mut() {
489///         *elem *= 10;
490///     }
491///
492///     assert_eq!(first.contents, [1, 2, 3, 4]);
493///     assert_eq!(second.contents, [10, 20, 30, 40]);
494///     assert_eq!(second.label, "hello");
495/// }
496/// ```
497///
498/// # See Also
499///
500/// * [`Clone::clone_from`] is a safe function which may be used instead when [`Self: Sized`](Sized)
501///   and the destination is already initialized; it may be able to reuse allocations owned by
502///   the destination, whereas `clone_to_uninit` cannot, since its destination is assumed to be
503///   uninitialized.
504/// * [`ToOwned`], which allocates a new destination container.
505///
506/// [`ToOwned`]: ../../std/borrow/trait.ToOwned.html
507/// [DST]: https://doc.rust-lang.org/reference/dynamically-sized-types.html
508/// [trait object]: https://doc.rust-lang.org/reference/types/trait-object.html
509#[unstable(feature = "clone_to_uninit", issue = "126799")]
510pub unsafe trait CloneToUninit {
511    /// Performs copy-assignment from `self` to `dest`.
512    ///
513    /// This is analogous to `std::ptr::write(dest.cast(), self.clone())`,
514    /// except that `Self` may be a dynamically-sized type ([`!Sized`](Sized)).
515    ///
516    /// Before this function is called, `dest` may point to uninitialized memory.
517    /// After this function is called, `dest` will point to initialized memory; it will be
518    /// sound to create a `&Self` reference from the pointer with the [pointer metadata]
519    /// from `self`.
520    ///
521    /// # Safety
522    ///
523    /// Behavior is undefined if any of the following conditions are violated:
524    ///
525    /// * `dest` must be [valid] for writes for `size_of_val(self)` bytes.
526    /// * `dest` must be properly aligned to `align_of_val(self)`.
527    ///
528    /// [valid]: crate::ptr#safety
529    /// [pointer metadata]: crate::ptr::metadata()
530    ///
531    /// # Panics
532    ///
533    /// This function may panic. (For example, it might panic if memory allocation for a clone
534    /// of a value owned by `self` fails.)
535    /// If the call panics, then `*dest` should be treated as uninitialized memory; it must not be
536    /// read or dropped, because even if it was previously valid, it may have been partially
537    /// overwritten.
538    ///
539    /// The caller may wish to take care to deallocate the allocation pointed to by `dest`,
540    /// if applicable, to avoid a memory leak (but this is not a requirement).
541    ///
542    /// Implementors should avoid leaking values by, upon unwinding, dropping all component values
543    /// that might have already been created. (For example, if a `[Foo]` of length 3 is being
544    /// cloned, and the second of the three calls to `Foo::clone()` unwinds, then the first `Foo`
545    /// cloned should be dropped.)
546    unsafe fn clone_to_uninit(&self, dest: *mut u8);
547}
548
549#[unstable(feature = "clone_to_uninit", issue = "126799")]
550unsafe impl<T: Clone> CloneToUninit for T {
551    #[inline]
552    unsafe fn clone_to_uninit(&self, dest: *mut u8) {
553        // SAFETY: we're calling a specialization with the same contract
554        unsafe { <T as self::uninit::CopySpec>::clone_one(self, dest.cast::<T>()) }
555    }
556}
557
558#[unstable(feature = "clone_to_uninit", issue = "126799")]
559unsafe impl<T: Clone> CloneToUninit for [T] {
560    #[inline]
561    #[cfg_attr(debug_assertions, track_caller)]
562    unsafe fn clone_to_uninit(&self, dest: *mut u8) {
563        let dest: *mut [T] = dest.with_metadata_of(self);
564        // SAFETY: we're calling a specialization with the same contract
565        unsafe { <T as self::uninit::CopySpec>::clone_slice(self, dest) }
566    }
567}
568
569#[unstable(feature = "clone_to_uninit", issue = "126799")]
570unsafe impl CloneToUninit for str {
571    #[inline]
572    #[cfg_attr(debug_assertions, track_caller)]
573    unsafe fn clone_to_uninit(&self, dest: *mut u8) {
574        // SAFETY: str is just a [u8] with UTF-8 invariant
575        unsafe { self.as_bytes().clone_to_uninit(dest) }
576    }
577}
578
579#[unstable(feature = "clone_to_uninit", issue = "126799")]
580unsafe impl CloneToUninit for crate::ffi::CStr {
581    #[cfg_attr(debug_assertions, track_caller)]
582    unsafe fn clone_to_uninit(&self, dest: *mut u8) {
583        // SAFETY: For now, CStr is just a #[repr(trasnsparent)] [c_char] with some invariants.
584        // And we can cast [c_char] to [u8] on all supported platforms (see: to_bytes_with_nul).
585        // The pointer metadata properly preserves the length (so NUL is also copied).
586        // See: `cstr_metadata_is_length_with_nul` in tests.
587        unsafe { self.to_bytes_with_nul().clone_to_uninit(dest) }
588    }
589}
590
591#[unstable(feature = "bstr", issue = "134915")]
592unsafe impl CloneToUninit for crate::bstr::ByteStr {
593    #[inline]
594    #[cfg_attr(debug_assertions, track_caller)]
595    unsafe fn clone_to_uninit(&self, dst: *mut u8) {
596        // SAFETY: ByteStr is a `#[repr(transparent)]` wrapper around `[u8]`
597        unsafe { self.as_bytes().clone_to_uninit(dst) }
598    }
599}
600
601/// Implementations of `Clone` for primitive types.
602///
603/// Implementations that cannot be described in Rust
604/// are implemented in `traits::SelectionContext::copy_clone_conditions()`
605/// in `rustc_trait_selection`.
606mod impls {
607    use super::TrivialClone;
608    use crate::marker::PointeeSized;
609
610    macro_rules! impl_clone {
611        ($($t:ty)*) => {
612            $(
613                #[stable(feature = "rust1", since = "1.0.0")]
614                #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
615                impl const Clone for $t {
616                    #[inline(always)]
617                    #[ferrocene::prevalidated]
618                    fn clone(&self) -> Self {
619                        *self
620                    }
621                }
622
623                #[doc(hidden)]
624                #[unstable(feature = "trivial_clone", issue = "none")]
625                #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
626                unsafe impl const TrivialClone for $t {}
627            )*
628        }
629    }
630
631    impl_clone! {
632        usize u8 u16 u32 u64 u128
633        isize i8 i16 i32 i64 i128
634        f16 f32 f64 f128
635        bool char
636    }
637
638    #[unstable(feature = "never_type", issue = "35121")]
639    #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
640    impl const Clone for ! {
641        #[inline]
642        #[ferrocene::annotation(
643            "This function cannot be executed because it is impossible to create a value of type `!`"
644        )]
645        #[ferrocene::prevalidated]
646        fn clone(&self) -> Self {
647            *self
648        }
649    }
650
651    #[doc(hidden)]
652    #[unstable(feature = "trivial_clone", issue = "none")]
653    #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
654    unsafe impl const TrivialClone for ! {}
655
656    #[stable(feature = "rust1", since = "1.0.0")]
657    #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
658    impl<T: PointeeSized> const Clone for *const T {
659        #[inline(always)]
660        #[ferrocene::annotation(
661            "This function is thoroughly tested inside the `test_clone` test in `coretests`. The fact that is shown as uncovered is a bug in our coverage tooling."
662        )]
663        #[ferrocene::prevalidated]
664        fn clone(&self) -> Self {
665            *self
666        }
667    }
668
669    #[doc(hidden)]
670    #[unstable(feature = "trivial_clone", issue = "none")]
671    #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
672    unsafe impl<T: PointeeSized> const TrivialClone for *const T {}
673
674    #[stable(feature = "rust1", since = "1.0.0")]
675    #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
676    impl<T: PointeeSized> const Clone for *mut T {
677        #[inline(always)]
678        #[ferrocene::annotation(
679            "This function is thoroughly tested inside the `test_clone` test in `coretests`. The fact that is shown as uncovered is a bug in our coverage tooling."
680        )]
681        #[ferrocene::prevalidated]
682        fn clone(&self) -> Self {
683            *self
684        }
685    }
686
687    #[doc(hidden)]
688    #[unstable(feature = "trivial_clone", issue = "none")]
689    #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
690    unsafe impl<T: PointeeSized> const TrivialClone for *mut T {}
691
692    /// Shared references can be cloned, but mutable references *cannot*!
693    #[stable(feature = "rust1", since = "1.0.0")]
694    #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
695    impl<T: PointeeSized> const Clone for &T {
696        #[inline(always)]
697        #[rustc_diagnostic_item = "noop_method_clone"]
698        #[ferrocene::prevalidated]
699        fn clone(&self) -> Self {
700            self
701        }
702    }
703
704    #[doc(hidden)]
705    #[unstable(feature = "trivial_clone", issue = "none")]
706    #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
707    unsafe impl<T: PointeeSized> const TrivialClone for &T {}
708
709    /// Shared references can be cloned, but mutable references *cannot*!
710    #[stable(feature = "rust1", since = "1.0.0")]
711    impl<T: PointeeSized> !Clone for &mut T {}
712}