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
41#[cfg(not(feature = "ferrocene_subset"))]
42mod uninit;
43
44/// A common trait that allows explicit creation of a duplicate value.
45///
46/// Calling [`clone`] always produces a new value.
47/// However, for types that are references to other data (such as smart pointers or references),
48/// the new value may still point to the same underlying data, rather than duplicating it.
49/// See [`Clone::clone`] for more details.
50///
51/// This distinction is especially important when using `#[derive(Clone)]` on structs containing
52/// smart pointers like `Arc<Mutex<T>>` - the cloned struct will share mutable state with the
53/// original.
54///
55/// Differs from [`Copy`] in that [`Copy`] is implicit and an inexpensive bit-wise copy, while
56/// `Clone` is always explicit and may or may not be expensive. In order to enforce
57/// these characteristics, Rust does not allow you to reimplement [`Copy`], but you
58/// may reimplement `Clone` and run arbitrary code.
59///
60/// Since `Clone` is more general than [`Copy`], you can automatically make anything
61/// [`Copy`] be `Clone` as well.
62///
63/// ## Derivable
64///
65/// This trait can be used with `#[derive]` if all fields are `Clone`. The `derive`d
66/// implementation of [`Clone`] calls [`clone`] on each field.
67///
68/// [`clone`]: Clone::clone
69///
70/// For a generic struct, `#[derive]` implements `Clone` conditionally by adding bound `Clone` on
71/// generic parameters.
72///
73/// ```
74/// // `derive` implements Clone for Reading<T> when T is Clone.
75/// #[derive(Clone)]
76/// struct Reading<T> {
77///     frequency: T,
78/// }
79/// ```
80///
81/// ## How can I implement `Clone`?
82///
83/// Types that are [`Copy`] should have a trivial implementation of `Clone`. More formally:
84/// if `T: Copy`, `x: T`, and `y: &T`, then `let x = y.clone();` is equivalent to `let x = *y;`.
85/// Manual implementations should be careful to uphold this invariant; however, unsafe code
86/// must not rely on it to ensure memory safety.
87///
88/// An example is a generic struct holding a function pointer. In this case, the
89/// implementation of `Clone` cannot be `derive`d, but can be implemented as:
90///
91/// ```
92/// struct Generate<T>(fn() -> T);
93///
94/// impl<T> Copy for Generate<T> {}
95///
96/// impl<T> Clone for Generate<T> {
97///     fn clone(&self) -> Self {
98///         *self
99///     }
100/// }
101/// ```
102///
103/// If we `derive`:
104///
105/// ```
106/// #[derive(Copy, Clone)]
107/// struct Generate<T>(fn() -> T);
108/// ```
109///
110/// the auto-derived implementations will have unnecessary `T: Copy` and `T: Clone` bounds:
111///
112/// ```
113/// # struct Generate<T>(fn() -> T);
114///
115/// // Automatically derived
116/// impl<T: Copy> Copy for Generate<T> { }
117///
118/// // Automatically derived
119/// impl<T: Clone> Clone for Generate<T> {
120///     fn clone(&self) -> Generate<T> {
121///         Generate(Clone::clone(&self.0))
122///     }
123/// }
124/// ```
125///
126/// The bounds are unnecessary because clearly the function itself should be
127/// copy- and cloneable even if its return type is not:
128///
129/// ```compile_fail,E0599
130/// #[derive(Copy, Clone)]
131/// struct Generate<T>(fn() -> T);
132///
133/// struct NotCloneable;
134///
135/// fn generate_not_cloneable() -> NotCloneable {
136///     NotCloneable
137/// }
138///
139/// Generate(generate_not_cloneable).clone(); // error: trait bounds were not satisfied
140/// // Note: With the manual implementations the above line will compile.
141/// ```
142///
143/// ## `Clone` and `PartialEq`/`Eq`
144/// `Clone` is intended for the duplication of objects. Consequently, when implementing
145/// both `Clone` and [`PartialEq`], the following property is expected to hold:
146/// ```text
147/// x == x -> x.clone() == x
148/// ```
149/// In other words, if an object compares equal to itself,
150/// its clone must also compare equal to the original.
151///
152/// For types that also implement [`Eq`] – for which `x == x` always holds –
153/// this implies that `x.clone() == x` must always be true.
154/// Standard library collections such as
155/// [`HashMap`], [`HashSet`], [`BTreeMap`], [`BTreeSet`] and [`BinaryHeap`]
156/// rely on their keys respecting this property for correct behavior.
157/// Furthermore, these collections require that cloning a key preserves the outcome of the
158/// [`Hash`] and [`Ord`] methods. Thankfully, this follows automatically from `x.clone() == x`
159/// if `Hash` and `Ord` are correctly implemented according to their own requirements.
160///
161/// When deriving both `Clone` and [`PartialEq`] using `#[derive(Clone, PartialEq)]`
162/// or when additionally deriving [`Eq`] using `#[derive(Clone, PartialEq, Eq)]`,
163/// then this property is automatically upheld – provided that it is satisfied by
164/// the underlying types.
165///
166/// Violating this property is a logic error. The behavior resulting from a logic error is not
167/// specified, but users of the trait must ensure that such logic errors do *not* result in
168/// undefined behavior. This means that `unsafe` code **must not** rely on this property
169/// being satisfied.
170///
171/// ## Additional implementors
172///
173/// In addition to the [implementors listed below][impls],
174/// the following types also implement `Clone`:
175///
176/// * Function item types (i.e., the distinct types defined for each function)
177/// * Function pointer types (e.g., `fn() -> i32`)
178/// * Closure types, if they capture no value from the environment
179///   or if all such captured values implement `Clone` themselves.
180///   Note that variables captured by shared reference always implement `Clone`
181///   (even if the referent doesn't),
182///   while variables captured by mutable reference never implement `Clone`.
183///
184/// [`HashMap`]: ../../std/collections/struct.HashMap.html
185/// [`HashSet`]: ../../std/collections/struct.HashSet.html
186/// [`BTreeMap`]: ../../std/collections/struct.BTreeMap.html
187/// [`BTreeSet`]: ../../std/collections/struct.BTreeSet.html
188/// [`BinaryHeap`]: ../../std/collections/struct.BinaryHeap.html
189/// [impls]: #implementors
190#[stable(feature = "rust1", since = "1.0.0")]
191#[lang = "clone"]
192#[rustc_diagnostic_item = "Clone"]
193#[rustc_trivial_field_reads]
194#[rustc_const_unstable(feature = "const_clone", issue = "142757")]
195pub const trait Clone: Sized {
196    /// Returns a duplicate of the value.
197    ///
198    /// Note that what "duplicate" means varies by type:
199    /// - For most types, this creates a deep, independent copy
200    /// - For reference types like `&T`, this creates another reference to the same value
201    /// - For smart pointers like [`Arc`] or [`Rc`], this increments the reference count
202    ///   but still points to the same underlying data
203    ///
204    /// [`Arc`]: ../../std/sync/struct.Arc.html
205    /// [`Rc`]: ../../std/rc/struct.Rc.html
206    ///
207    /// # Examples
208    ///
209    /// ```
210    /// # #![allow(noop_method_call)]
211    /// let hello = "Hello"; // &str implements Clone
212    ///
213    /// assert_eq!("Hello", hello.clone());
214    /// ```
215    ///
216    /// Example with a reference-counted type:
217    ///
218    /// ```
219    /// use std::sync::{Arc, Mutex};
220    ///
221    /// let data = Arc::new(Mutex::new(vec![1, 2, 3]));
222    /// let data_clone = data.clone(); // Creates another Arc pointing to the same Mutex
223    ///
224    /// {
225    ///     let mut lock = data.lock().unwrap();
226    ///     lock.push(4);
227    /// }
228    ///
229    /// // Changes are visible through the clone because they share the same underlying data
230    /// assert_eq!(*data_clone.lock().unwrap(), vec![1, 2, 3, 4]);
231    /// ```
232    #[stable(feature = "rust1", since = "1.0.0")]
233    #[must_use = "cloning is often expensive and is not expected to have side effects"]
234    // Clone::clone is special because the compiler generates MIR to implement it for some types.
235    // See InstanceKind::CloneShim.
236    #[lang = "clone_fn"]
237    fn clone(&self) -> Self;
238
239    /// Performs copy-assignment from `source`.
240    ///
241    /// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality,
242    /// but can be overridden to reuse the resources of `a` to avoid unnecessary
243    /// allocations.
244    #[inline]
245    #[stable(feature = "rust1", since = "1.0.0")]
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, 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"]
327#[cfg(not(feature = "ferrocene_subset"))]
328pub trait UseCloned: Clone {
329    // Empty.
330}
331
332#[cfg(not(feature = "ferrocene_subset"))]
333macro_rules! impl_use_cloned {
334    ($($t:ty)*) => {
335        $(
336            #[unstable(feature = "ergonomic_clones", issue = "132290")]
337            impl UseCloned for $t {}
338        )*
339    }
340}
341
342#[cfg(not(feature = "ferrocene_subset"))]
343impl_use_cloned! {
344    usize u8 u16 u32 u64 u128
345    isize i8 i16 i32 i64 i128
346             f16 f32 f64 f128
347    bool char
348}
349
350// FIXME(aburka): these structs are used solely by #[derive] to
351// assert that every component of a type implements Clone or Copy.
352//
353// These structs should never appear in user code.
354#[doc(hidden)]
355#[allow(missing_debug_implementations)]
356#[unstable(
357    feature = "derive_clone_copy",
358    reason = "deriving hack, should not be public",
359    issue = "none"
360)]
361pub struct AssertParamIsClone<T: Clone + PointeeSized> {
362    _field: crate::marker::PhantomData<T>,
363}
364#[doc(hidden)]
365#[allow(missing_debug_implementations)]
366#[unstable(
367    feature = "derive_clone_copy",
368    reason = "deriving hack, should not be public",
369    issue = "none"
370)]
371pub struct AssertParamIsCopy<T: Copy + PointeeSized> {
372    _field: crate::marker::PhantomData<T>,
373}
374
375/// A generalization of [`Clone`] to [dynamically-sized types][DST] stored in arbitrary containers.
376///
377/// This trait is implemented for all types implementing [`Clone`], [slices](slice) of all
378/// such types, and other dynamically-sized types in the standard library.
379/// You may also implement this trait to enable cloning custom DSTs
380/// (structures containing dynamically-sized fields), or use it as a supertrait to enable
381/// cloning a [trait object].
382///
383/// This trait is normally used via operations on container types which support DSTs,
384/// so you should not typically need to call `.clone_to_uninit()` explicitly except when
385/// implementing such a container or otherwise performing explicit management of an allocation,
386/// or when implementing `CloneToUninit` itself.
387///
388/// # Safety
389///
390/// Implementations must ensure that when `.clone_to_uninit(dest)` returns normally rather than
391/// panicking, it always leaves `*dest` initialized as a valid value of type `Self`.
392///
393/// # Examples
394///
395// FIXME(#126799): when `Box::clone` allows use of `CloneToUninit`, rewrite these examples with it
396// since `Rc` is a distraction.
397///
398/// If you are defining a trait, you can add `CloneToUninit` as a supertrait to enable cloning of
399/// `dyn` values of your trait:
400///
401/// ```
402/// #![feature(clone_to_uninit)]
403/// use std::rc::Rc;
404///
405/// trait Foo: std::fmt::Debug + std::clone::CloneToUninit {
406///     fn modify(&mut self);
407///     fn value(&self) -> i32;
408/// }
409///
410/// impl Foo for i32 {
411///     fn modify(&mut self) {
412///         *self *= 10;
413///     }
414///     fn value(&self) -> i32 {
415///         *self
416///     }
417/// }
418///
419/// let first: Rc<dyn Foo> = Rc::new(1234);
420///
421/// let mut second = first.clone();
422/// Rc::make_mut(&mut second).modify(); // make_mut() will call clone_to_uninit()
423///
424/// assert_eq!(first.value(), 1234);
425/// assert_eq!(second.value(), 12340);
426/// ```
427///
428/// The following is an example of implementing `CloneToUninit` for a custom DST.
429/// (It is essentially a limited form of what `derive(CloneToUninit)` would do,
430/// if such a derive macro existed.)
431///
432/// ```
433/// #![feature(clone_to_uninit)]
434/// use std::clone::CloneToUninit;
435/// use std::mem::offset_of;
436/// use std::rc::Rc;
437///
438/// #[derive(PartialEq)]
439/// struct MyDst<T: ?Sized> {
440///     label: String,
441///     contents: T,
442/// }
443///
444/// unsafe impl<T: ?Sized + CloneToUninit> CloneToUninit for MyDst<T> {
445///     unsafe fn clone_to_uninit(&self, dest: *mut u8) {
446///         // The offset of `self.contents` is dynamic because it depends on the alignment of T
447///         // which can be dynamic (if `T = dyn SomeTrait`). Therefore, we have to obtain it
448///         // dynamically by examining `self`, rather than using `offset_of!`.
449///         //
450///         // SAFETY: `self` by definition points somewhere before `&self.contents` in the same
451///         // allocation.
452///         let offset_of_contents = unsafe {
453///             (&raw const self.contents).byte_offset_from_unsigned(self)
454///         };
455///
456///         // Clone the *sized* fields of `self` (just one, in this example).
457///         // (By cloning this first and storing it temporarily in a local variable, we avoid
458///         // leaking it in case of any panic, using the ordinary automatic cleanup of local
459///         // variables. Such a leak would be sound, but undesirable.)
460///         let label = self.label.clone();
461///
462///         // SAFETY: The caller must provide a `dest` such that these field offsets are valid
463///         // to write to.
464///         unsafe {
465///             // Clone the unsized field directly from `self` to `dest`.
466///             self.contents.clone_to_uninit(dest.add(offset_of_contents));
467///
468///             // Now write all the sized fields.
469///             //
470///             // Note that we only do this once all of the clone() and clone_to_uninit() calls
471///             // have completed, and therefore we know that there are no more possible panics;
472///             // this ensures no memory leaks in case of panic.
473///             dest.add(offset_of!(Self, label)).cast::<String>().write(label);
474///         }
475///         // All fields of the struct have been initialized; therefore, the struct is initialized,
476///         // and we have satisfied our `unsafe impl CloneToUninit` obligations.
477///     }
478/// }
479///
480/// fn main() {
481///     // Construct MyDst<[u8; 4]>, then coerce to MyDst<[u8]>.
482///     let first: Rc<MyDst<[u8]>> = Rc::new(MyDst {
483///         label: String::from("hello"),
484///         contents: [1, 2, 3, 4],
485///     });
486///
487///     let mut second = first.clone();
488///     // make_mut() will call clone_to_uninit().
489///     for elem in Rc::make_mut(&mut second).contents.iter_mut() {
490///         *elem *= 10;
491///     }
492///
493///     assert_eq!(first.contents, [1, 2, 3, 4]);
494///     assert_eq!(second.contents, [10, 20, 30, 40]);
495///     assert_eq!(second.label, "hello");
496/// }
497/// ```
498///
499/// # See Also
500///
501/// * [`Clone::clone_from`] is a safe function which may be used instead when [`Self: Sized`](Sized)
502///   and the destination is already initialized; it may be able to reuse allocations owned by
503///   the destination, whereas `clone_to_uninit` cannot, since its destination is assumed to be
504///   uninitialized.
505/// * [`ToOwned`], which allocates a new destination container.
506///
507/// [`ToOwned`]: ../../std/borrow/trait.ToOwned.html
508/// [DST]: https://doc.rust-lang.org/reference/dynamically-sized-types.html
509/// [trait object]: https://doc.rust-lang.org/reference/types/trait-object.html
510#[unstable(feature = "clone_to_uninit", issue = "126799")]
511#[cfg(not(feature = "ferrocene_subset"))]
512pub unsafe trait CloneToUninit {
513    /// Performs copy-assignment from `self` to `dest`.
514    ///
515    /// This is analogous to `std::ptr::write(dest.cast(), self.clone())`,
516    /// except that `Self` may be a dynamically-sized type ([`!Sized`](Sized)).
517    ///
518    /// Before this function is called, `dest` may point to uninitialized memory.
519    /// After this function is called, `dest` will point to initialized memory; it will be
520    /// sound to create a `&Self` reference from the pointer with the [pointer metadata]
521    /// from `self`.
522    ///
523    /// # Safety
524    ///
525    /// Behavior is undefined if any of the following conditions are violated:
526    ///
527    /// * `dest` must be [valid] for writes for `size_of_val(self)` bytes.
528    /// * `dest` must be properly aligned to `align_of_val(self)`.
529    ///
530    /// [valid]: crate::ptr#safety
531    /// [pointer metadata]: crate::ptr::metadata()
532    ///
533    /// # Panics
534    ///
535    /// This function may panic. (For example, it might panic if memory allocation for a clone
536    /// of a value owned by `self` fails.)
537    /// If the call panics, then `*dest` should be treated as uninitialized memory; it must not be
538    /// read or dropped, because even if it was previously valid, it may have been partially
539    /// overwritten.
540    ///
541    /// The caller may wish to take care to deallocate the allocation pointed to by `dest`,
542    /// if applicable, to avoid a memory leak (but this is not a requirement).
543    ///
544    /// Implementors should avoid leaking values by, upon unwinding, dropping all component values
545    /// that might have already been created. (For example, if a `[Foo]` of length 3 is being
546    /// cloned, and the second of the three calls to `Foo::clone()` unwinds, then the first `Foo`
547    /// cloned should be dropped.)
548    unsafe fn clone_to_uninit(&self, dest: *mut u8);
549}
550
551#[unstable(feature = "clone_to_uninit", issue = "126799")]
552#[cfg(not(feature = "ferrocene_subset"))]
553unsafe impl<T: Clone> CloneToUninit for T {
554    #[inline]
555    unsafe fn clone_to_uninit(&self, dest: *mut u8) {
556        // SAFETY: we're calling a specialization with the same contract
557        unsafe { <T as self::uninit::CopySpec>::clone_one(self, dest.cast::<T>()) }
558    }
559}
560
561#[unstable(feature = "clone_to_uninit", issue = "126799")]
562#[cfg(not(feature = "ferrocene_subset"))]
563unsafe impl<T: Clone> CloneToUninit for [T] {
564    #[inline]
565    #[cfg_attr(debug_assertions, track_caller)]
566    unsafe fn clone_to_uninit(&self, dest: *mut u8) {
567        let dest: *mut [T] = dest.with_metadata_of(self);
568        // SAFETY: we're calling a specialization with the same contract
569        unsafe { <T as self::uninit::CopySpec>::clone_slice(self, dest) }
570    }
571}
572
573#[unstable(feature = "clone_to_uninit", issue = "126799")]
574#[cfg(not(feature = "ferrocene_subset"))]
575unsafe impl CloneToUninit for str {
576    #[inline]
577    #[cfg_attr(debug_assertions, track_caller)]
578    unsafe fn clone_to_uninit(&self, dest: *mut u8) {
579        // SAFETY: str is just a [u8] with UTF-8 invariant
580        unsafe { self.as_bytes().clone_to_uninit(dest) }
581    }
582}
583
584#[unstable(feature = "clone_to_uninit", issue = "126799")]
585#[cfg(not(feature = "ferrocene_subset"))]
586unsafe impl CloneToUninit for crate::ffi::CStr {
587    #[cfg_attr(debug_assertions, track_caller)]
588    unsafe fn clone_to_uninit(&self, dest: *mut u8) {
589        // SAFETY: For now, CStr is just a #[repr(trasnsparent)] [c_char] with some invariants.
590        // And we can cast [c_char] to [u8] on all supported platforms (see: to_bytes_with_nul).
591        // The pointer metadata properly preserves the length (so NUL is also copied).
592        // See: `cstr_metadata_is_length_with_nul` in tests.
593        unsafe { self.to_bytes_with_nul().clone_to_uninit(dest) }
594    }
595}
596
597#[unstable(feature = "bstr", issue = "134915")]
598#[cfg(not(feature = "ferrocene_subset"))]
599unsafe impl CloneToUninit for crate::bstr::ByteStr {
600    #[inline]
601    #[cfg_attr(debug_assertions, track_caller)]
602    unsafe fn clone_to_uninit(&self, dst: *mut u8) {
603        // SAFETY: ByteStr is a `#[repr(transparent)]` wrapper around `[u8]`
604        unsafe { self.as_bytes().clone_to_uninit(dst) }
605    }
606}
607
608/// Implementations of `Clone` for primitive types.
609///
610/// Implementations that cannot be described in Rust
611/// are implemented in `traits::SelectionContext::copy_clone_conditions()`
612/// in `rustc_trait_selection`.
613mod impls {
614    use super::TrivialClone;
615    use crate::marker::PointeeSized;
616
617    macro_rules! impl_clone {
618        ($($t:ty)*) => {
619            $(
620                #[stable(feature = "rust1", since = "1.0.0")]
621                #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
622                impl const Clone for $t {
623                    #[inline(always)]
624                    fn clone(&self) -> Self {
625                        *self
626                    }
627                }
628
629                #[doc(hidden)]
630                #[unstable(feature = "trivial_clone", issue = "none")]
631                #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
632                unsafe impl const TrivialClone for $t {}
633            )*
634        }
635    }
636
637    impl_clone! {
638        usize u8 u16 u32 u64 u128
639        isize i8 i16 i32 i64 i128
640        f16 f32 f64 f128
641        bool char
642    }
643
644    #[unstable(feature = "never_type", issue = "35121")]
645    #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
646    impl const Clone for ! {
647        #[inline]
648        #[ferrocene::annotation(
649            "This function cannot be executed because it is impossible to create a value of type `!`"
650        )]
651        fn clone(&self) -> Self {
652            *self
653        }
654    }
655
656    #[doc(hidden)]
657    #[unstable(feature = "trivial_clone", issue = "none")]
658    #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
659    unsafe impl const TrivialClone for ! {}
660
661    #[stable(feature = "rust1", since = "1.0.0")]
662    #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
663    impl<T: PointeeSized> const Clone for *const T {
664        #[inline(always)]
665        #[ferrocene::annotation(
666            "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."
667        )]
668        fn clone(&self) -> Self {
669            *self
670        }
671    }
672
673    #[doc(hidden)]
674    #[unstable(feature = "trivial_clone", issue = "none")]
675    #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
676    unsafe impl<T: PointeeSized> const TrivialClone for *const T {}
677
678    #[stable(feature = "rust1", since = "1.0.0")]
679    #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
680    impl<T: PointeeSized> const Clone for *mut T {
681        #[inline(always)]
682        #[ferrocene::annotation(
683            "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."
684        )]
685        fn clone(&self) -> Self {
686            *self
687        }
688    }
689
690    #[doc(hidden)]
691    #[unstable(feature = "trivial_clone", issue = "none")]
692    #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
693    unsafe impl<T: PointeeSized> const TrivialClone for *mut T {}
694
695    /// Shared references can be cloned, but mutable references *cannot*!
696    #[stable(feature = "rust1", since = "1.0.0")]
697    #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
698    impl<T: PointeeSized> const Clone for &T {
699        #[inline(always)]
700        #[rustc_diagnostic_item = "noop_method_clone"]
701        fn clone(&self) -> Self {
702            self
703        }
704    }
705
706    #[doc(hidden)]
707    #[unstable(feature = "trivial_clone", issue = "none")]
708    #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
709    unsafe impl<T: PointeeSized> const TrivialClone for &T {}
710
711    /// Shared references can be cloned, but mutable references *cannot*!
712    #[stable(feature = "rust1", since = "1.0.0")]
713    impl<T: PointeeSized> !Clone for &mut T {}
714}