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/// ## Additional implementors
144///
145/// In addition to the [implementors listed below][impls],
146/// the following types also implement `Clone`:
147///
148/// * Function item types (i.e., the distinct types defined for each function)
149/// * Function pointer types (e.g., `fn() -> i32`)
150/// * Closure types, if they capture no value from the environment
151/// or if all such captured values implement `Clone` themselves.
152/// Note that variables captured by shared reference always implement `Clone`
153/// (even if the referent doesn't),
154/// while variables captured by mutable reference never implement `Clone`.
155///
156/// [impls]: #implementors
157#[stable(feature = "rust1", since = "1.0.0")]
158#[lang = "clone"]
159#[rustc_diagnostic_item = "Clone"]
160#[rustc_trivial_field_reads]
161#[rustc_const_unstable(feature = "const_clone", issue = "142757")]
162#[const_trait]
163pub trait Clone: Sized {
164 /// Returns a duplicate of the value.
165 ///
166 /// Note that what "duplicate" means varies by type:
167 /// - For most types, this creates a deep, independent copy
168 /// - For reference types like `&T`, this creates another reference to the same value
169 /// - For smart pointers like [`Arc`] or [`Rc`], this increments the reference count
170 /// but still points to the same underlying data
171 ///
172 /// [`Arc`]: ../../std/sync/struct.Arc.html
173 /// [`Rc`]: ../../std/rc/struct.Rc.html
174 ///
175 /// # Examples
176 ///
177 /// ```
178 /// # #![allow(noop_method_call)]
179 /// let hello = "Hello"; // &str implements Clone
180 ///
181 /// assert_eq!("Hello", hello.clone());
182 /// ```
183 ///
184 /// Example with a reference-counted type:
185 ///
186 /// ```
187 /// use std::sync::{Arc, Mutex};
188 ///
189 /// let data = Arc::new(Mutex::new(vec![1, 2, 3]));
190 /// let data_clone = data.clone(); // Creates another Arc pointing to the same Mutex
191 ///
192 /// {
193 /// let mut lock = data.lock().unwrap();
194 /// lock.push(4);
195 /// }
196 ///
197 /// // Changes are visible through the clone because they share the same underlying data
198 /// assert_eq!(*data_clone.lock().unwrap(), vec![1, 2, 3, 4]);
199 /// ```
200 #[stable(feature = "rust1", since = "1.0.0")]
201 #[must_use = "cloning is often expensive and is not expected to have side effects"]
202 // Clone::clone is special because the compiler generates MIR to implement it for some types.
203 // See InstanceKind::CloneShim.
204 #[lang = "clone_fn"]
205 fn clone(&self) -> Self;
206
207 /// Performs copy-assignment from `source`.
208 ///
209 /// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality,
210 /// but can be overridden to reuse the resources of `a` to avoid unnecessary
211 /// allocations.
212 #[inline]
213 #[stable(feature = "rust1", since = "1.0.0")]
214 fn clone_from(&mut self, source: &Self)
215 where
216 Self: ~const Destruct,
217 {
218 *self = source.clone()
219 }
220}
221
222/// Derive macro generating an impl of the trait `Clone`.
223#[rustc_builtin_macro]
224#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
225#[allow_internal_unstable(core_intrinsics, derive_clone_copy)]
226pub macro Clone($item:item) {
227 /* compiler built-in */
228}
229
230/// Trait for objects whose [`Clone`] impl is lightweight (e.g. reference-counted)
231///
232/// Cloning an object implementing this trait should in general:
233/// - be O(1) (constant) time regardless of the amount of data managed by the object,
234/// - not require a memory allocation,
235/// - not require copying more than roughly 64 bytes (a typical cache line size),
236/// - not block the current thread,
237/// - not have any semantic side effects (e.g. allocating a file descriptor), and
238/// - not have overhead larger than a couple of atomic operations.
239///
240/// The `UseCloned` trait does not provide a method; instead, it indicates that
241/// `Clone::clone` is lightweight, and allows the use of the `.use` syntax.
242///
243/// ## .use postfix syntax
244///
245/// Values can be `.use`d by adding `.use` postfix to the value you want to use.
246///
247/// ```ignore (this won't work until we land use)
248/// fn foo(f: Foo) {
249/// // if `Foo` implements `Copy` f would be copied into x.
250/// // if `Foo` implements `UseCloned` f would be cloned into x.
251/// // otherwise f would be moved into x.
252/// let x = f.use;
253/// // ...
254/// }
255/// ```
256///
257/// ## use closures
258///
259/// Use closures allow captured values to be automatically used.
260/// This is similar to have a closure that you would call `.use` over each captured value.
261#[unstable(feature = "ergonomic_clones", issue = "132290")]
262#[lang = "use_cloned"]
263#[cfg(not(feature = "ferrocene_certified"))]
264pub trait UseCloned: Clone {
265 // Empty.
266}
267
268#[cfg(not(feature = "ferrocene_certified"))]
269macro_rules! impl_use_cloned {
270 ($($t:ty)*) => {
271 $(
272 #[unstable(feature = "ergonomic_clones", issue = "132290")]
273 impl UseCloned for $t {}
274 )*
275 }
276}
277
278#[cfg(not(feature = "ferrocene_certified"))]
279impl_use_cloned! {
280 usize u8 u16 u32 u64 u128
281 isize i8 i16 i32 i64 i128
282 f16 f32 f64 f128
283 bool char
284}
285
286// FIXME(aburka): these structs are used solely by #[derive] to
287// assert that every component of a type implements Clone or Copy.
288//
289// These structs should never appear in user code.
290#[doc(hidden)]
291#[allow(missing_debug_implementations)]
292#[unstable(
293 feature = "derive_clone_copy",
294 reason = "deriving hack, should not be public",
295 issue = "none"
296)]
297pub struct AssertParamIsClone<T: Clone + PointeeSized> {
298 _field: crate::marker::PhantomData<T>,
299}
300#[doc(hidden)]
301#[allow(missing_debug_implementations)]
302#[unstable(
303 feature = "derive_clone_copy",
304 reason = "deriving hack, should not be public",
305 issue = "none"
306)]
307#[cfg(not(feature = "ferrocene_certified"))]
308pub struct AssertParamIsCopy<T: Copy + PointeeSized> {
309 _field: crate::marker::PhantomData<T>,
310}
311
312/// A generalization of [`Clone`] to [dynamically-sized types][DST] stored in arbitrary containers.
313///
314/// This trait is implemented for all types implementing [`Clone`], [slices](slice) of all
315/// such types, and other dynamically-sized types in the standard library.
316/// You may also implement this trait to enable cloning custom DSTs
317/// (structures containing dynamically-sized fields), or use it as a supertrait to enable
318/// cloning a [trait object].
319///
320/// This trait is normally used via operations on container types which support DSTs,
321/// so you should not typically need to call `.clone_to_uninit()` explicitly except when
322/// implementing such a container or otherwise performing explicit management of an allocation,
323/// or when implementing `CloneToUninit` itself.
324///
325/// # Safety
326///
327/// Implementations must ensure that when `.clone_to_uninit(dest)` returns normally rather than
328/// panicking, it always leaves `*dest` initialized as a valid value of type `Self`.
329///
330/// # Examples
331///
332// FIXME(#126799): when `Box::clone` allows use of `CloneToUninit`, rewrite these examples with it
333// since `Rc` is a distraction.
334///
335/// If you are defining a trait, you can add `CloneToUninit` as a supertrait to enable cloning of
336/// `dyn` values of your trait:
337///
338/// ```
339/// #![feature(clone_to_uninit)]
340/// use std::rc::Rc;
341///
342/// trait Foo: std::fmt::Debug + std::clone::CloneToUninit {
343/// fn modify(&mut self);
344/// fn value(&self) -> i32;
345/// }
346///
347/// impl Foo for i32 {
348/// fn modify(&mut self) {
349/// *self *= 10;
350/// }
351/// fn value(&self) -> i32 {
352/// *self
353/// }
354/// }
355///
356/// let first: Rc<dyn Foo> = Rc::new(1234);
357///
358/// let mut second = first.clone();
359/// Rc::make_mut(&mut second).modify(); // make_mut() will call clone_to_uninit()
360///
361/// assert_eq!(first.value(), 1234);
362/// assert_eq!(second.value(), 12340);
363/// ```
364///
365/// The following is an example of implementing `CloneToUninit` for a custom DST.
366/// (It is essentially a limited form of what `derive(CloneToUninit)` would do,
367/// if such a derive macro existed.)
368///
369/// ```
370/// #![feature(clone_to_uninit)]
371/// use std::clone::CloneToUninit;
372/// use std::mem::offset_of;
373/// use std::rc::Rc;
374///
375/// #[derive(PartialEq)]
376/// struct MyDst<T: ?Sized> {
377/// label: String,
378/// contents: T,
379/// }
380///
381/// unsafe impl<T: ?Sized + CloneToUninit> CloneToUninit for MyDst<T> {
382/// unsafe fn clone_to_uninit(&self, dest: *mut u8) {
383/// // The offset of `self.contents` is dynamic because it depends on the alignment of T
384/// // which can be dynamic (if `T = dyn SomeTrait`). Therefore, we have to obtain it
385/// // dynamically by examining `self`, rather than using `offset_of!`.
386/// //
387/// // SAFETY: `self` by definition points somewhere before `&self.contents` in the same
388/// // allocation.
389/// let offset_of_contents = unsafe {
390/// (&raw const self.contents).byte_offset_from_unsigned(self)
391/// };
392///
393/// // Clone the *sized* fields of `self` (just one, in this example).
394/// // (By cloning this first and storing it temporarily in a local variable, we avoid
395/// // leaking it in case of any panic, using the ordinary automatic cleanup of local
396/// // variables. Such a leak would be sound, but undesirable.)
397/// let label = self.label.clone();
398///
399/// // SAFETY: The caller must provide a `dest` such that these field offsets are valid
400/// // to write to.
401/// unsafe {
402/// // Clone the unsized field directly from `self` to `dest`.
403/// self.contents.clone_to_uninit(dest.add(offset_of_contents));
404///
405/// // Now write all the sized fields.
406/// //
407/// // Note that we only do this once all of the clone() and clone_to_uninit() calls
408/// // have completed, and therefore we know that there are no more possible panics;
409/// // this ensures no memory leaks in case of panic.
410/// dest.add(offset_of!(Self, label)).cast::<String>().write(label);
411/// }
412/// // All fields of the struct have been initialized; therefore, the struct is initialized,
413/// // and we have satisfied our `unsafe impl CloneToUninit` obligations.
414/// }
415/// }
416///
417/// fn main() {
418/// // Construct MyDst<[u8; 4]>, then coerce to MyDst<[u8]>.
419/// let first: Rc<MyDst<[u8]>> = Rc::new(MyDst {
420/// label: String::from("hello"),
421/// contents: [1, 2, 3, 4],
422/// });
423///
424/// let mut second = first.clone();
425/// // make_mut() will call clone_to_uninit().
426/// for elem in Rc::make_mut(&mut second).contents.iter_mut() {
427/// *elem *= 10;
428/// }
429///
430/// assert_eq!(first.contents, [1, 2, 3, 4]);
431/// assert_eq!(second.contents, [10, 20, 30, 40]);
432/// assert_eq!(second.label, "hello");
433/// }
434/// ```
435///
436/// # See Also
437///
438/// * [`Clone::clone_from`] is a safe function which may be used instead when [`Self: Sized`](Sized)
439/// and the destination is already initialized; it may be able to reuse allocations owned by
440/// the destination, whereas `clone_to_uninit` cannot, since its destination is assumed to be
441/// uninitialized.
442/// * [`ToOwned`], which allocates a new destination container.
443///
444/// [`ToOwned`]: ../../std/borrow/trait.ToOwned.html
445/// [DST]: https://doc.rust-lang.org/reference/dynamically-sized-types.html
446/// [trait object]: https://doc.rust-lang.org/reference/types/trait-object.html
447#[unstable(feature = "clone_to_uninit", issue = "126799")]
448#[cfg(not(feature = "ferrocene_certified"))]
449pub unsafe trait CloneToUninit {
450 /// Performs copy-assignment from `self` to `dest`.
451 ///
452 /// This is analogous to `std::ptr::write(dest.cast(), self.clone())`,
453 /// except that `Self` may be a dynamically-sized type ([`!Sized`](Sized)).
454 ///
455 /// Before this function is called, `dest` may point to uninitialized memory.
456 /// After this function is called, `dest` will point to initialized memory; it will be
457 /// sound to create a `&Self` reference from the pointer with the [pointer metadata]
458 /// from `self`.
459 ///
460 /// # Safety
461 ///
462 /// Behavior is undefined if any of the following conditions are violated:
463 ///
464 /// * `dest` must be [valid] for writes for `size_of_val(self)` bytes.
465 /// * `dest` must be properly aligned to `align_of_val(self)`.
466 ///
467 /// [valid]: crate::ptr#safety
468 /// [pointer metadata]: crate::ptr::metadata()
469 ///
470 /// # Panics
471 ///
472 /// This function may panic. (For example, it might panic if memory allocation for a clone
473 /// of a value owned by `self` fails.)
474 /// If the call panics, then `*dest` should be treated as uninitialized memory; it must not be
475 /// read or dropped, because even if it was previously valid, it may have been partially
476 /// overwritten.
477 ///
478 /// The caller may wish to take care to deallocate the allocation pointed to by `dest`,
479 /// if applicable, to avoid a memory leak (but this is not a requirement).
480 ///
481 /// Implementors should avoid leaking values by, upon unwinding, dropping all component values
482 /// that might have already been created. (For example, if a `[Foo]` of length 3 is being
483 /// cloned, and the second of the three calls to `Foo::clone()` unwinds, then the first `Foo`
484 /// cloned should be dropped.)
485 unsafe fn clone_to_uninit(&self, dest: *mut u8);
486}
487
488#[unstable(feature = "clone_to_uninit", issue = "126799")]
489#[cfg(not(feature = "ferrocene_certified"))]
490unsafe impl<T: Clone> CloneToUninit for T {
491 #[inline]
492 unsafe fn clone_to_uninit(&self, dest: *mut u8) {
493 // SAFETY: we're calling a specialization with the same contract
494 unsafe { <T as self::uninit::CopySpec>::clone_one(self, dest.cast::<T>()) }
495 }
496}
497
498#[unstable(feature = "clone_to_uninit", issue = "126799")]
499#[cfg(not(feature = "ferrocene_certified"))]
500unsafe impl<T: Clone> CloneToUninit for [T] {
501 #[inline]
502 #[cfg_attr(debug_assertions, track_caller)]
503 unsafe fn clone_to_uninit(&self, dest: *mut u8) {
504 let dest: *mut [T] = dest.with_metadata_of(self);
505 // SAFETY: we're calling a specialization with the same contract
506 unsafe { <T as self::uninit::CopySpec>::clone_slice(self, dest) }
507 }
508}
509
510#[unstable(feature = "clone_to_uninit", issue = "126799")]
511#[cfg(not(feature = "ferrocene_certified"))]
512unsafe impl CloneToUninit for str {
513 #[inline]
514 #[cfg_attr(debug_assertions, track_caller)]
515 unsafe fn clone_to_uninit(&self, dest: *mut u8) {
516 // SAFETY: str is just a [u8] with UTF-8 invariant
517 unsafe { self.as_bytes().clone_to_uninit(dest) }
518 }
519}
520
521#[unstable(feature = "clone_to_uninit", issue = "126799")]
522#[cfg(not(feature = "ferrocene_certified"))]
523unsafe impl CloneToUninit for crate::ffi::CStr {
524 #[cfg_attr(debug_assertions, track_caller)]
525 unsafe fn clone_to_uninit(&self, dest: *mut u8) {
526 // SAFETY: For now, CStr is just a #[repr(trasnsparent)] [c_char] with some invariants.
527 // And we can cast [c_char] to [u8] on all supported platforms (see: to_bytes_with_nul).
528 // The pointer metadata properly preserves the length (so NUL is also copied).
529 // See: `cstr_metadata_is_length_with_nul` in tests.
530 unsafe { self.to_bytes_with_nul().clone_to_uninit(dest) }
531 }
532}
533
534#[unstable(feature = "bstr", issue = "134915")]
535#[cfg(not(feature = "ferrocene_certified"))]
536unsafe impl CloneToUninit for crate::bstr::ByteStr {
537 #[inline]
538 #[cfg_attr(debug_assertions, track_caller)]
539 unsafe fn clone_to_uninit(&self, dst: *mut u8) {
540 // SAFETY: ByteStr is a `#[repr(transparent)]` wrapper around `[u8]`
541 unsafe { self.as_bytes().clone_to_uninit(dst) }
542 }
543}
544
545/// Implementations of `Clone` for primitive types.
546///
547/// Implementations that cannot be described in Rust
548/// are implemented in `traits::SelectionContext::copy_clone_conditions()`
549/// in `rustc_trait_selection`.
550mod impls {
551 use crate::marker::PointeeSized;
552
553 macro_rules! impl_clone {
554 ($($t:ty)*) => {
555 $(
556 #[stable(feature = "rust1", since = "1.0.0")]
557 impl Clone for $t {
558 #[inline(always)]
559 fn clone(&self) -> Self {
560 *self
561 }
562 }
563 )*
564 }
565 }
566
567 #[cfg(not(feature = "ferrocene_certified"))]
568 impl_clone! {
569 usize u8 u16 u32 u64 u128
570 isize i8 i16 i32 i64 i128
571 f16 f32 f64 f128
572 bool char
573 }
574
575 #[cfg(feature = "ferrocene_certified")]
576 impl_clone! {
577 usize u8 u16 u32 u64 u128
578 isize i8 i16 i32 i64 i128
579 f32 f64
580 bool
581 }
582
583 #[unstable(feature = "never_type", issue = "35121")]
584 #[cfg(not(feature = "ferrocene_certified"))]
585 impl Clone for ! {
586 #[inline]
587 fn clone(&self) -> Self {
588 *self
589 }
590 }
591
592 #[stable(feature = "rust1", since = "1.0.0")]
593 impl<T: PointeeSized> Clone for *const T {
594 #[inline(always)]
595 fn clone(&self) -> Self {
596 *self
597 }
598 }
599
600 #[stable(feature = "rust1", since = "1.0.0")]
601 impl<T: PointeeSized> Clone for *mut T {
602 #[inline(always)]
603 fn clone(&self) -> Self {
604 *self
605 }
606 }
607
608 /// Shared references can be cloned, but mutable references *cannot*!
609 #[stable(feature = "rust1", since = "1.0.0")]
610 impl<T: PointeeSized> Clone for &T {
611 #[inline(always)]
612 #[rustc_diagnostic_item = "noop_method_clone"]
613 fn clone(&self) -> Self {
614 self
615 }
616 }
617
618 /// Shared references can be cloned, but mutable references *cannot*!
619 #[stable(feature = "rust1", since = "1.0.0")]
620 #[cfg(not(feature = "ferrocene_certified"))]
621 impl<T: PointeeSized> !Clone for &mut T {}
622}