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