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_certified"))]
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_certified"))]
328pub trait UseCloned: Clone {
329 // Empty.
330}
331
332#[cfg(not(feature = "ferrocene_certified"))]
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_certified"))]
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)]
371#[cfg(not(feature = "ferrocene_certified"))]
372pub struct AssertParamIsCopy<T: Copy + PointeeSized> {
373 _field: crate::marker::PhantomData<T>,
374}
375
376/// A generalization of [`Clone`] to [dynamically-sized types][DST] stored in arbitrary containers.
377///
378/// This trait is implemented for all types implementing [`Clone`], [slices](slice) of all
379/// such types, and other dynamically-sized types in the standard library.
380/// You may also implement this trait to enable cloning custom DSTs
381/// (structures containing dynamically-sized fields), or use it as a supertrait to enable
382/// cloning a [trait object].
383///
384/// This trait is normally used via operations on container types which support DSTs,
385/// so you should not typically need to call `.clone_to_uninit()` explicitly except when
386/// implementing such a container or otherwise performing explicit management of an allocation,
387/// or when implementing `CloneToUninit` itself.
388///
389/// # Safety
390///
391/// Implementations must ensure that when `.clone_to_uninit(dest)` returns normally rather than
392/// panicking, it always leaves `*dest` initialized as a valid value of type `Self`.
393///
394/// # Examples
395///
396// FIXME(#126799): when `Box::clone` allows use of `CloneToUninit`, rewrite these examples with it
397// since `Rc` is a distraction.
398///
399/// If you are defining a trait, you can add `CloneToUninit` as a supertrait to enable cloning of
400/// `dyn` values of your trait:
401///
402/// ```
403/// #![feature(clone_to_uninit)]
404/// use std::rc::Rc;
405///
406/// trait Foo: std::fmt::Debug + std::clone::CloneToUninit {
407/// fn modify(&mut self);
408/// fn value(&self) -> i32;
409/// }
410///
411/// impl Foo for i32 {
412/// fn modify(&mut self) {
413/// *self *= 10;
414/// }
415/// fn value(&self) -> i32 {
416/// *self
417/// }
418/// }
419///
420/// let first: Rc<dyn Foo> = Rc::new(1234);
421///
422/// let mut second = first.clone();
423/// Rc::make_mut(&mut second).modify(); // make_mut() will call clone_to_uninit()
424///
425/// assert_eq!(first.value(), 1234);
426/// assert_eq!(second.value(), 12340);
427/// ```
428///
429/// The following is an example of implementing `CloneToUninit` for a custom DST.
430/// (It is essentially a limited form of what `derive(CloneToUninit)` would do,
431/// if such a derive macro existed.)
432///
433/// ```
434/// #![feature(clone_to_uninit)]
435/// use std::clone::CloneToUninit;
436/// use std::mem::offset_of;
437/// use std::rc::Rc;
438///
439/// #[derive(PartialEq)]
440/// struct MyDst<T: ?Sized> {
441/// label: String,
442/// contents: T,
443/// }
444///
445/// unsafe impl<T: ?Sized + CloneToUninit> CloneToUninit for MyDst<T> {
446/// unsafe fn clone_to_uninit(&self, dest: *mut u8) {
447/// // The offset of `self.contents` is dynamic because it depends on the alignment of T
448/// // which can be dynamic (if `T = dyn SomeTrait`). Therefore, we have to obtain it
449/// // dynamically by examining `self`, rather than using `offset_of!`.
450/// //
451/// // SAFETY: `self` by definition points somewhere before `&self.contents` in the same
452/// // allocation.
453/// let offset_of_contents = unsafe {
454/// (&raw const self.contents).byte_offset_from_unsigned(self)
455/// };
456///
457/// // Clone the *sized* fields of `self` (just one, in this example).
458/// // (By cloning this first and storing it temporarily in a local variable, we avoid
459/// // leaking it in case of any panic, using the ordinary automatic cleanup of local
460/// // variables. Such a leak would be sound, but undesirable.)
461/// let label = self.label.clone();
462///
463/// // SAFETY: The caller must provide a `dest` such that these field offsets are valid
464/// // to write to.
465/// unsafe {
466/// // Clone the unsized field directly from `self` to `dest`.
467/// self.contents.clone_to_uninit(dest.add(offset_of_contents));
468///
469/// // Now write all the sized fields.
470/// //
471/// // Note that we only do this once all of the clone() and clone_to_uninit() calls
472/// // have completed, and therefore we know that there are no more possible panics;
473/// // this ensures no memory leaks in case of panic.
474/// dest.add(offset_of!(Self, label)).cast::<String>().write(label);
475/// }
476/// // All fields of the struct have been initialized; therefore, the struct is initialized,
477/// // and we have satisfied our `unsafe impl CloneToUninit` obligations.
478/// }
479/// }
480///
481/// fn main() {
482/// // Construct MyDst<[u8; 4]>, then coerce to MyDst<[u8]>.
483/// let first: Rc<MyDst<[u8]>> = Rc::new(MyDst {
484/// label: String::from("hello"),
485/// contents: [1, 2, 3, 4],
486/// });
487///
488/// let mut second = first.clone();
489/// // make_mut() will call clone_to_uninit().
490/// for elem in Rc::make_mut(&mut second).contents.iter_mut() {
491/// *elem *= 10;
492/// }
493///
494/// assert_eq!(first.contents, [1, 2, 3, 4]);
495/// assert_eq!(second.contents, [10, 20, 30, 40]);
496/// assert_eq!(second.label, "hello");
497/// }
498/// ```
499///
500/// # See Also
501///
502/// * [`Clone::clone_from`] is a safe function which may be used instead when [`Self: Sized`](Sized)
503/// and the destination is already initialized; it may be able to reuse allocations owned by
504/// the destination, whereas `clone_to_uninit` cannot, since its destination is assumed to be
505/// uninitialized.
506/// * [`ToOwned`], which allocates a new destination container.
507///
508/// [`ToOwned`]: ../../std/borrow/trait.ToOwned.html
509/// [DST]: https://doc.rust-lang.org/reference/dynamically-sized-types.html
510/// [trait object]: https://doc.rust-lang.org/reference/types/trait-object.html
511#[unstable(feature = "clone_to_uninit", issue = "126799")]
512#[cfg(not(feature = "ferrocene_certified"))]
513pub unsafe trait CloneToUninit {
514 /// Performs copy-assignment from `self` to `dest`.
515 ///
516 /// This is analogous to `std::ptr::write(dest.cast(), self.clone())`,
517 /// except that `Self` may be a dynamically-sized type ([`!Sized`](Sized)).
518 ///
519 /// Before this function is called, `dest` may point to uninitialized memory.
520 /// After this function is called, `dest` will point to initialized memory; it will be
521 /// sound to create a `&Self` reference from the pointer with the [pointer metadata]
522 /// from `self`.
523 ///
524 /// # Safety
525 ///
526 /// Behavior is undefined if any of the following conditions are violated:
527 ///
528 /// * `dest` must be [valid] for writes for `size_of_val(self)` bytes.
529 /// * `dest` must be properly aligned to `align_of_val(self)`.
530 ///
531 /// [valid]: crate::ptr#safety
532 /// [pointer metadata]: crate::ptr::metadata()
533 ///
534 /// # Panics
535 ///
536 /// This function may panic. (For example, it might panic if memory allocation for a clone
537 /// of a value owned by `self` fails.)
538 /// If the call panics, then `*dest` should be treated as uninitialized memory; it must not be
539 /// read or dropped, because even if it was previously valid, it may have been partially
540 /// overwritten.
541 ///
542 /// The caller may wish to take care to deallocate the allocation pointed to by `dest`,
543 /// if applicable, to avoid a memory leak (but this is not a requirement).
544 ///
545 /// Implementors should avoid leaking values by, upon unwinding, dropping all component values
546 /// that might have already been created. (For example, if a `[Foo]` of length 3 is being
547 /// cloned, and the second of the three calls to `Foo::clone()` unwinds, then the first `Foo`
548 /// cloned should be dropped.)
549 unsafe fn clone_to_uninit(&self, dest: *mut u8);
550}
551
552#[unstable(feature = "clone_to_uninit", issue = "126799")]
553#[cfg(not(feature = "ferrocene_certified"))]
554unsafe impl<T: Clone> CloneToUninit for T {
555 #[inline]
556 unsafe fn clone_to_uninit(&self, dest: *mut u8) {
557 // SAFETY: we're calling a specialization with the same contract
558 unsafe { <T as self::uninit::CopySpec>::clone_one(self, dest.cast::<T>()) }
559 }
560}
561
562#[unstable(feature = "clone_to_uninit", issue = "126799")]
563#[cfg(not(feature = "ferrocene_certified"))]
564unsafe impl<T: Clone> CloneToUninit for [T] {
565 #[inline]
566 #[cfg_attr(debug_assertions, track_caller)]
567 unsafe fn clone_to_uninit(&self, dest: *mut u8) {
568 let dest: *mut [T] = dest.with_metadata_of(self);
569 // SAFETY: we're calling a specialization with the same contract
570 unsafe { <T as self::uninit::CopySpec>::clone_slice(self, dest) }
571 }
572}
573
574#[unstable(feature = "clone_to_uninit", issue = "126799")]
575#[cfg(not(feature = "ferrocene_certified"))]
576unsafe impl CloneToUninit for str {
577 #[inline]
578 #[cfg_attr(debug_assertions, track_caller)]
579 unsafe fn clone_to_uninit(&self, dest: *mut u8) {
580 // SAFETY: str is just a [u8] with UTF-8 invariant
581 unsafe { self.as_bytes().clone_to_uninit(dest) }
582 }
583}
584
585#[unstable(feature = "clone_to_uninit", issue = "126799")]
586#[cfg(not(feature = "ferrocene_certified"))]
587unsafe impl CloneToUninit for crate::ffi::CStr {
588 #[cfg_attr(debug_assertions, track_caller)]
589 unsafe fn clone_to_uninit(&self, dest: *mut u8) {
590 // SAFETY: For now, CStr is just a #[repr(trasnsparent)] [c_char] with some invariants.
591 // And we can cast [c_char] to [u8] on all supported platforms (see: to_bytes_with_nul).
592 // The pointer metadata properly preserves the length (so NUL is also copied).
593 // See: `cstr_metadata_is_length_with_nul` in tests.
594 unsafe { self.to_bytes_with_nul().clone_to_uninit(dest) }
595 }
596}
597
598#[unstable(feature = "bstr", issue = "134915")]
599#[cfg(not(feature = "ferrocene_certified"))]
600unsafe impl CloneToUninit for crate::bstr::ByteStr {
601 #[inline]
602 #[cfg_attr(debug_assertions, track_caller)]
603 unsafe fn clone_to_uninit(&self, dst: *mut u8) {
604 // SAFETY: ByteStr is a `#[repr(transparent)]` wrapper around `[u8]`
605 unsafe { self.as_bytes().clone_to_uninit(dst) }
606 }
607}
608
609/// Implementations of `Clone` for primitive types.
610///
611/// Implementations that cannot be described in Rust
612/// are implemented in `traits::SelectionContext::copy_clone_conditions()`
613/// in `rustc_trait_selection`.
614mod impls {
615 use super::TrivialClone;
616 use crate::marker::PointeeSized;
617
618 macro_rules! impl_clone {
619 ($($t:ty)*) => {
620 $(
621 #[stable(feature = "rust1", since = "1.0.0")]
622 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
623 impl const Clone for $t {
624 #[inline(always)]
625 fn clone(&self) -> Self {
626 *self
627 }
628 }
629
630 #[doc(hidden)]
631 #[unstable(feature = "trivial_clone", issue = "none")]
632 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
633 unsafe impl const TrivialClone for $t {}
634 )*
635 }
636 }
637
638 impl_clone! {
639 usize u8 u16 u32 u64 u128
640 isize i8 i16 i32 i64 i128
641 f16 f32 f64 f128
642 bool char
643 }
644
645 #[unstable(feature = "never_type", issue = "35121")]
646 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
647 impl const Clone for ! {
648 #[inline]
649 #[ferrocene::annotation(
650 "This function cannot be executed because it is impossible to create a value of type `!`"
651 )]
652 fn clone(&self) -> Self {
653 *self
654 }
655 }
656
657 #[doc(hidden)]
658 #[unstable(feature = "trivial_clone", issue = "none")]
659 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
660 unsafe impl const TrivialClone for ! {}
661
662 #[stable(feature = "rust1", since = "1.0.0")]
663 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
664 impl<T: PointeeSized> const Clone for *const T {
665 #[inline(always)]
666 #[ferrocene::annotation(
667 "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."
668 )]
669 fn clone(&self) -> Self {
670 *self
671 }
672 }
673
674 #[doc(hidden)]
675 #[unstable(feature = "trivial_clone", issue = "none")]
676 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
677 unsafe impl<T: PointeeSized> const TrivialClone for *const T {}
678
679 #[stable(feature = "rust1", since = "1.0.0")]
680 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
681 impl<T: PointeeSized> const Clone for *mut T {
682 #[inline(always)]
683 #[ferrocene::annotation(
684 "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."
685 )]
686 fn clone(&self) -> Self {
687 *self
688 }
689 }
690
691 #[doc(hidden)]
692 #[unstable(feature = "trivial_clone", issue = "none")]
693 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
694 unsafe impl<T: PointeeSized> const TrivialClone for *mut T {}
695
696 /// Shared references can be cloned, but mutable references *cannot*!
697 #[stable(feature = "rust1", since = "1.0.0")]
698 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
699 impl<T: PointeeSized> const Clone for &T {
700 #[inline(always)]
701 #[rustc_diagnostic_item = "noop_method_clone"]
702 fn clone(&self) -> Self {
703 self
704 }
705 }
706
707 #[doc(hidden)]
708 #[unstable(feature = "trivial_clone", issue = "none")]
709 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
710 unsafe impl<T: PointeeSized> const TrivialClone for &T {}
711
712 /// Shared references can be cloned, but mutable references *cannot*!
713 #[stable(feature = "rust1", since = "1.0.0")]
714 impl<T: PointeeSized> !Clone for &mut T {}
715}