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