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