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/// A trait for types whose [`Clone`] operation creates another alias to the same
295/// logical resource or shared state.
296///
297/// `Share` marks types where cloning creates another handle, reference, or alias
298/// to the same logical resource or shared state, rather than an independent owned
299/// value. The distinction is semantic, not cost-based: implementing `Share` does
300/// not merely mean that cloning is cheap, constant-time, allocation-free, or
301/// convenient.
302///
303/// Calling [`share`](Share::share) is equivalent to calling [`clone`](Clone::clone)
304/// for implementors, but communicates that the resulting value aliases the same
305/// underlying resource.
306///
307/// Shared references, `Rc<T>`, `Arc<T>`, `Sender<T>`, and `SyncSender<T>` are
308/// examples of types that can be shared this way. Types such as `Vec<T>`,
309/// `String`, and `Box<T>` are not `Share` even though they implement `Clone`,
310/// because cloning them creates another owned value rather than another handle
311/// to the same logical resource.
312///
313/// # Examples
314///
315/// ```
316/// #![feature(share_trait)]
317///
318/// use std::cell::Cell;
319/// use std::clone::Share;
320/// use std::rc::Rc;
321/// use std::sync::{
322/// Arc,
323/// atomic::{AtomicUsize, Ordering},
324/// };
325///
326/// let value = 1;
327/// let reference = &value;
328/// assert!(std::ptr::eq(reference, reference.share()));
329///
330/// let rc = Rc::new(Cell::new(2));
331/// let shared_rc = rc.share();
332/// assert!(Rc::ptr_eq(&rc, &shared_rc));
333/// shared_rc.set(3);
334/// assert_eq!(rc.get(), 3);
335///
336/// let arc = Arc::new(AtomicUsize::new(4));
337/// let shared_arc = arc.share();
338/// assert!(Arc::ptr_eq(&arc, &shared_arc));
339/// shared_arc.store(5, Ordering::Relaxed);
340/// assert_eq!(arc.load(Ordering::Relaxed), 5);
341/// ```
342///
343/// ```
344/// #![feature(share_trait)]
345///
346/// use std::clone::Share;
347/// use std::sync::mpsc::{channel, sync_channel};
348///
349/// let (sender, receiver) = channel();
350/// let shared_sender = sender.share();
351/// sender.send(1).unwrap();
352/// shared_sender.send(2).unwrap();
353///
354/// let mut received = [receiver.recv().unwrap(), receiver.recv().unwrap()];
355/// received.sort();
356/// assert_eq!(received, [1, 2]);
357///
358/// let (sync_sender, sync_receiver) = sync_channel(2);
359/// let shared_sync_sender = sync_sender.share();
360/// sync_sender.send(3).unwrap();
361/// shared_sync_sender.send(4).unwrap();
362///
363/// let mut received = [sync_receiver.recv().unwrap(), sync_receiver.recv().unwrap()];
364/// received.sort();
365/// assert_eq!(received, [3, 4]);
366/// ```
367#[unstable(feature = "share_trait", issue = "156756")]
368pub trait Share: Clone {
369 /// Creates another alias to the same underlying resource or shared state.
370 ///
371 /// This is equivalent to calling [`Clone::clone`].
372 #[unstable(feature = "share_trait", issue = "156756")]
373 fn share(&self) -> Self {
374 Clone::clone(self)
375 }
376}
377
378/// Trait for objects whose [`Clone`] impl is lightweight (e.g. reference-counted)
379///
380/// Cloning an object implementing this trait should in general:
381/// - be O(1) (constant) time regardless of the amount of data managed by the object,
382/// - not require a memory allocation,
383/// - not require copying more than roughly 64 bytes (a typical cache line size),
384/// - not block the current thread,
385/// - not have any semantic side effects (e.g. allocating a file descriptor), and
386/// - not have overhead larger than a couple of atomic operations.
387///
388/// The `UseCloned` trait does not provide a method; instead, it indicates that
389/// `Clone::clone` is lightweight, and allows the use of the `.use` syntax.
390///
391/// ## .use postfix syntax
392///
393/// Values can be `.use`d by adding `.use` postfix to the value you want to use.
394///
395/// ```ignore (this won't work until we land use)
396/// fn foo(f: Foo) {
397/// // if `Foo` implements `Copy` f would be copied into x.
398/// // if `Foo` implements `UseCloned` f would be cloned into x.
399/// // otherwise f would be moved into x.
400/// let x = f.use;
401/// // ...
402/// }
403/// ```
404///
405/// ## use closures
406///
407/// Use closures allow captured values to be automatically used.
408/// This is similar to have a closure that you would call `.use` over each captured value.
409#[unstable(feature = "ergonomic_clones", issue = "132290")]
410#[lang = "use_cloned"]
411pub trait UseCloned: Clone {
412 // Empty.
413}
414
415macro_rules! impl_use_cloned {
416 ($($t:ty)*) => {
417 $(
418 #[unstable(feature = "ergonomic_clones", issue = "132290")]
419 impl UseCloned for $t {}
420 )*
421 }
422}
423
424impl_use_cloned! {
425 usize u8 u16 u32 u64 u128
426 isize i8 i16 i32 i64 i128
427 f16 f32 f64 f128
428 bool char
429}
430
431// FIXME(aburka): these structs are used solely by #[derive] to
432// assert that every component of a type implements Clone or Copy.
433//
434// These structs should never appear in user code.
435#[doc(hidden)]
436#[allow(missing_debug_implementations)]
437#[unstable(
438 feature = "derive_clone_copy_internals",
439 reason = "deriving hack, should not be public",
440 issue = "none"
441)]
442#[ferrocene::prevalidated]
443pub struct AssertParamIsClone<T: Clone + PointeeSized> {
444 _field: crate::marker::PhantomData<T>,
445}
446#[doc(hidden)]
447#[allow(missing_debug_implementations)]
448#[unstable(
449 feature = "derive_clone_copy_internals",
450 reason = "deriving hack, should not be public",
451 issue = "none"
452)]
453#[ferrocene::prevalidated]
454pub struct AssertParamIsCopy<T: Copy + PointeeSized> {
455 _field: crate::marker::PhantomData<T>,
456}
457
458/// A generalization of [`Clone`] to [dynamically-sized types][DST] stored in arbitrary containers.
459///
460/// This trait is implemented for all types implementing [`Clone`], [slices](slice) of all
461/// such types, and other dynamically-sized types in the standard library.
462/// You may also implement this trait to enable cloning custom DSTs
463/// (structures containing dynamically-sized fields), or use it as a supertrait to enable
464/// cloning a [trait object].
465///
466/// This trait is normally used via operations on container types which support DSTs,
467/// so you should not typically need to call `.clone_to_uninit()` explicitly except when
468/// implementing such a container or otherwise performing explicit management of an allocation,
469/// or when implementing `CloneToUninit` itself.
470///
471/// # Safety
472///
473/// Implementations must ensure that when `.clone_to_uninit(dest)` returns normally rather than
474/// panicking, it always leaves `*dest` initialized as a valid value of type `Self`.
475///
476/// # Examples
477///
478// FIXME(#126799): when `Box::clone` allows use of `CloneToUninit`, rewrite these examples with it
479// since `Rc` is a distraction.
480///
481/// If you are defining a trait, you can add `CloneToUninit` as a supertrait to enable cloning of
482/// `dyn` values of your trait:
483///
484/// ```
485/// #![feature(clone_to_uninit)]
486/// use std::rc::Rc;
487///
488/// trait Foo: std::fmt::Debug + std::clone::CloneToUninit {
489/// fn modify(&mut self);
490/// fn value(&self) -> i32;
491/// }
492///
493/// impl Foo for i32 {
494/// fn modify(&mut self) {
495/// *self *= 10;
496/// }
497/// fn value(&self) -> i32 {
498/// *self
499/// }
500/// }
501///
502/// let first: Rc<dyn Foo> = Rc::new(1234);
503///
504/// let mut second = first.clone();
505/// Rc::make_mut(&mut second).modify(); // make_mut() will call clone_to_uninit()
506///
507/// assert_eq!(first.value(), 1234);
508/// assert_eq!(second.value(), 12340);
509/// ```
510///
511/// The following is an example of implementing `CloneToUninit` for a custom DST.
512/// (It is essentially a limited form of what `derive(CloneToUninit)` would do,
513/// if such a derive macro existed.)
514///
515/// ```
516/// #![feature(clone_to_uninit)]
517/// use std::clone::CloneToUninit;
518/// use std::mem::offset_of;
519/// use std::rc::Rc;
520///
521/// #[derive(PartialEq)]
522/// struct MyDst<T: ?Sized> {
523/// label: String,
524/// contents: T,
525/// }
526///
527/// unsafe impl<T: ?Sized + CloneToUninit> CloneToUninit for MyDst<T> {
528/// unsafe fn clone_to_uninit(&self, dest: *mut u8) {
529/// // The offset of `self.contents` is dynamic because it depends on the alignment of T
530/// // which can be dynamic (if `T = dyn SomeTrait`). Therefore, we have to obtain it
531/// // dynamically by examining `self`, rather than using `offset_of!`.
532/// //
533/// // SAFETY: `self` by definition points somewhere before `&self.contents` in the same
534/// // allocation.
535/// let offset_of_contents = unsafe {
536/// (&raw const self.contents).byte_offset_from_unsigned(self)
537/// };
538///
539/// // Clone the *sized* fields of `self` (just one, in this example).
540/// // (By cloning this first and storing it temporarily in a local variable, we avoid
541/// // leaking it in case of any panic, using the ordinary automatic cleanup of local
542/// // variables. Such a leak would be sound, but undesirable.)
543/// let label = self.label.clone();
544///
545/// // SAFETY: The caller must provide a `dest` such that these field offsets are valid
546/// // to write to.
547/// unsafe {
548/// // Clone the unsized field directly from `self` to `dest`.
549/// self.contents.clone_to_uninit(dest.add(offset_of_contents));
550///
551/// // Now write all the sized fields.
552/// //
553/// // Note that we only do this once all of the clone() and clone_to_uninit() calls
554/// // have completed, and therefore we know that there are no more possible panics;
555/// // this ensures no memory leaks in case of panic.
556/// dest.add(offset_of!(Self, label)).cast::<String>().write(label);
557/// }
558/// // All fields of the struct have been initialized; therefore, the struct is initialized,
559/// // and we have satisfied our `unsafe impl CloneToUninit` obligations.
560/// }
561/// }
562///
563/// fn main() {
564/// // Construct MyDst<[u8; 4]>, then coerce to MyDst<[u8]>.
565/// let first: Rc<MyDst<[u8]>> = Rc::new(MyDst {
566/// label: String::from("hello"),
567/// contents: [1, 2, 3, 4],
568/// });
569///
570/// let mut second = first.clone();
571/// // make_mut() will call clone_to_uninit().
572/// for elem in Rc::make_mut(&mut second).contents.iter_mut() {
573/// *elem *= 10;
574/// }
575///
576/// assert_eq!(first.contents, [1, 2, 3, 4]);
577/// assert_eq!(second.contents, [10, 20, 30, 40]);
578/// assert_eq!(second.label, "hello");
579/// }
580/// ```
581///
582/// # See Also
583///
584/// * [`Clone::clone_from`] is a safe function which may be used instead when [`Self: Sized`](Sized)
585/// and the destination is already initialized; it may be able to reuse allocations owned by
586/// the destination, whereas `clone_to_uninit` cannot, since its destination is assumed to be
587/// uninitialized.
588/// * [`ToOwned`], which allocates a new destination container.
589///
590/// [`ToOwned`]: ../../std/borrow/trait.ToOwned.html
591/// [DST]: https://doc.rust-lang.org/reference/dynamically-sized-types.html
592/// [trait object]: https://doc.rust-lang.org/reference/types/trait-object.html
593#[unstable(feature = "clone_to_uninit", issue = "126799")]
594pub unsafe trait CloneToUninit {
595 /// Performs copy-assignment from `self` to `dest`.
596 ///
597 /// This is analogous to `std::ptr::write(dest.cast(), self.clone())`,
598 /// except that `Self` may be a dynamically-sized type ([`!Sized`](Sized)).
599 ///
600 /// Before this function is called, `dest` may point to uninitialized memory.
601 /// After this function is called, `dest` will point to initialized memory; it will be
602 /// sound to create a `&Self` reference from the pointer with the [pointer metadata]
603 /// from `self`.
604 ///
605 /// # Safety
606 ///
607 /// Behavior is undefined if any of the following conditions are violated:
608 ///
609 /// * `dest` must be [valid] for writes for `size_of_val(self)` bytes.
610 /// * `dest` must be properly aligned to `align_of_val(self)`.
611 ///
612 /// [valid]: crate::ptr#safety
613 /// [pointer metadata]: crate::ptr::metadata()
614 ///
615 /// # Panics
616 ///
617 /// This function may panic. (For example, it might panic if memory allocation for a clone
618 /// of a value owned by `self` fails.)
619 /// If the call panics, then `*dest` should be treated as uninitialized memory; it must not be
620 /// read or dropped, because even if it was previously valid, it may have been partially
621 /// overwritten.
622 ///
623 /// The caller may wish to take care to deallocate the allocation pointed to by `dest`,
624 /// if applicable, to avoid a memory leak (but this is not a requirement).
625 ///
626 /// Implementors should avoid leaking values by, upon unwinding, dropping all component values
627 /// that might have already been created. (For example, if a `[Foo]` of length 3 is being
628 /// cloned, and the second of the three calls to `Foo::clone()` unwinds, then the first `Foo`
629 /// cloned should be dropped.)
630 unsafe fn clone_to_uninit(&self, dest: *mut u8);
631}
632
633#[unstable(feature = "clone_to_uninit", issue = "126799")]
634unsafe impl<T: Clone> CloneToUninit for T {
635 #[inline]
636 unsafe fn clone_to_uninit(&self, dest: *mut u8) {
637 // SAFETY: we're calling a specialization with the same contract
638 unsafe { <T as self::uninit::CopySpec>::clone_one(self, dest.cast::<T>()) }
639 }
640}
641
642#[unstable(feature = "clone_to_uninit", issue = "126799")]
643unsafe impl<T: Clone> CloneToUninit for [T] {
644 #[inline]
645 #[cfg_attr(debug_assertions, track_caller)]
646 unsafe fn clone_to_uninit(&self, dest: *mut u8) {
647 let dest: *mut [T] = dest.with_metadata_of(self);
648 // SAFETY: we're calling a specialization with the same contract
649 unsafe { <T as self::uninit::CopySpec>::clone_slice(self, dest) }
650 }
651}
652
653#[unstable(feature = "clone_to_uninit", issue = "126799")]
654unsafe impl CloneToUninit for str {
655 #[inline]
656 #[cfg_attr(debug_assertions, track_caller)]
657 unsafe fn clone_to_uninit(&self, dest: *mut u8) {
658 // SAFETY: str is just a [u8] with UTF-8 invariant
659 unsafe { self.as_bytes().clone_to_uninit(dest) }
660 }
661}
662
663#[unstable(feature = "clone_to_uninit", issue = "126799")]
664unsafe impl CloneToUninit for crate::ffi::CStr {
665 #[cfg_attr(debug_assertions, track_caller)]
666 unsafe fn clone_to_uninit(&self, dest: *mut u8) {
667 // SAFETY: For now, CStr is just a #[repr(trasnsparent)] [c_char] with some invariants.
668 // And we can cast [c_char] to [u8] on all supported platforms (see: to_bytes_with_nul).
669 // The pointer metadata properly preserves the length (so NUL is also copied).
670 // See: `cstr_metadata_is_length_with_nul` in tests.
671 unsafe { self.to_bytes_with_nul().clone_to_uninit(dest) }
672 }
673}
674
675#[unstable(feature = "bstr", issue = "134915")]
676unsafe impl CloneToUninit for crate::bstr::ByteStr {
677 #[inline]
678 #[cfg_attr(debug_assertions, track_caller)]
679 unsafe fn clone_to_uninit(&self, dst: *mut u8) {
680 // SAFETY: ByteStr is a `#[repr(transparent)]` wrapper around `[u8]`
681 unsafe { self.as_bytes().clone_to_uninit(dst) }
682 }
683}
684
685/// Implementations of `Clone` for primitive types.
686///
687/// Implementations that cannot be described in Rust
688/// are implemented in `traits::SelectionContext::copy_clone_conditions()`
689/// in `rustc_trait_selection`.
690mod impls {
691 use super::{Share, TrivialClone};
692 use crate::marker::PointeeSized;
693
694 macro_rules! impl_clone {
695 ($($t:ty)*) => {
696 $(
697 #[stable(feature = "rust1", since = "1.0.0")]
698 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
699 impl const Clone for $t {
700 #[inline(always)]
701 #[ferrocene::prevalidated]
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 const TrivialClone for $t {}
711 )*
712 }
713 }
714
715 impl_clone! {
716 usize u8 u16 u32 u64 u128
717 isize i8 i16 i32 i64 i128
718 f16 f32 f64 f128
719 bool char
720 }
721
722 #[unstable(feature = "never_type", issue = "35121")]
723 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
724 impl const Clone for ! {
725 #[inline]
726 #[ferrocene::annotation(
727 "This function cannot be executed because it is impossible to create a value of type `!`"
728 )]
729 #[ferrocene::prevalidated]
730 fn clone(&self) -> Self {
731 *self
732 }
733 }
734
735 #[doc(hidden)]
736 #[unstable(feature = "trivial_clone", issue = "none")]
737 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
738 unsafe impl const TrivialClone for ! {}
739
740 #[stable(feature = "rust1", since = "1.0.0")]
741 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
742 impl<T: PointeeSized> const Clone for *const T {
743 #[inline(always)]
744 #[ferrocene::annotation(
745 "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."
746 )]
747 #[ferrocene::prevalidated]
748 fn clone(&self) -> Self {
749 *self
750 }
751 }
752
753 #[doc(hidden)]
754 #[unstable(feature = "trivial_clone", issue = "none")]
755 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
756 unsafe impl<T: PointeeSized> const TrivialClone for *const T {}
757
758 #[stable(feature = "rust1", since = "1.0.0")]
759 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
760 impl<T: PointeeSized> const Clone for *mut T {
761 #[inline(always)]
762 #[ferrocene::annotation(
763 "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."
764 )]
765 #[ferrocene::prevalidated]
766 fn clone(&self) -> Self {
767 *self
768 }
769 }
770
771 #[doc(hidden)]
772 #[unstable(feature = "trivial_clone", issue = "none")]
773 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
774 unsafe impl<T: PointeeSized> const TrivialClone for *mut T {}
775
776 /// Shared references can be cloned, but mutable references *cannot*!
777 #[stable(feature = "rust1", since = "1.0.0")]
778 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
779 impl<T: PointeeSized> const Clone for &T {
780 #[inline(always)]
781 #[rustc_diagnostic_item = "noop_method_clone"]
782 #[ferrocene::prevalidated]
783 fn clone(&self) -> Self {
784 *self
785 }
786 }
787
788 #[doc(hidden)]
789 #[unstable(feature = "trivial_clone", issue = "none")]
790 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]
791 unsafe impl<T: PointeeSized> const TrivialClone for &T {}
792
793 #[unstable(feature = "share_trait", issue = "156756")]
794 impl<T: PointeeSized> Share for &T {}
795
796 /// Shared references can be cloned, but mutable references *cannot*!
797 #[stable(feature = "rust1", since = "1.0.0")]
798 impl<T: PointeeSized> !Clone for &mut T {}
799}