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