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// FIXME(aburka): these structs are used solely by #[derive] to
188// assert that every component of a type implements Clone or Copy.
189//
190// These structs should never appear in user code.
191#[doc(hidden)]
192#[allow(missing_debug_implementations)]
193#[unstable(
194    feature = "derive_clone_copy",
195    reason = "deriving hack, should not be public",
196    issue = "none"
197)]
198pub struct AssertParamIsClone<T: Clone + ?Sized> {
199    _field: crate::marker::PhantomData<T>,
200}
201#[doc(hidden)]
202#[allow(missing_debug_implementations)]
203#[unstable(
204    feature = "derive_clone_copy",
205    reason = "deriving hack, should not be public",
206    issue = "none"
207)]
208pub struct AssertParamIsCopy<T: Copy + ?Sized> {
209    _field: crate::marker::PhantomData<T>,
210}
211
212/// A generalization of [`Clone`] to dynamically-sized types stored in arbitrary containers.
213///
214/// This trait is implemented for all types implementing [`Clone`], and also [slices](slice) of all
215/// such types. You may also implement this trait to enable cloning trait objects and custom DSTs
216/// (structures containing dynamically-sized fields).
217///
218/// # Safety
219///
220/// Implementations must ensure that when `.clone_to_uninit(dst)` returns normally rather than
221/// panicking, it always leaves `*dst` initialized as a valid value of type `Self`.
222///
223/// # See also
224///
225/// * [`Clone::clone_from`] is a safe function which may be used instead when `Self` is a [`Sized`]
226///   and the destination is already initialized; it may be able to reuse allocations owned by
227///   the destination.
228/// * [`ToOwned`], which allocates a new destination container.
229///
230/// [`ToOwned`]: ../../std/borrow/trait.ToOwned.html
231#[unstable(feature = "clone_to_uninit", issue = "126799")]
232pub unsafe trait CloneToUninit {
233    /// Performs copy-assignment from `self` to `dst`.
234    ///
235    /// This is analogous to `std::ptr::write(dst.cast(), self.clone())`,
236    /// except that `self` may be a dynamically-sized type ([`!Sized`](Sized)).
237    ///
238    /// Before this function is called, `dst` may point to uninitialized memory.
239    /// After this function is called, `dst` will point to initialized memory; it will be
240    /// sound to create a `&Self` reference from the pointer with the [pointer metadata]
241    /// from `self`.
242    ///
243    /// # Safety
244    ///
245    /// Behavior is undefined if any of the following conditions are violated:
246    ///
247    /// * `dst` must be [valid] for writes for `std::mem::size_of_val(self)` bytes.
248    /// * `dst` must be properly aligned to `std::mem::align_of_val(self)`.
249    ///
250    /// [valid]: crate::ptr#safety
251    /// [pointer metadata]: crate::ptr::metadata()
252    ///
253    /// # Panics
254    ///
255    /// This function may panic. (For example, it might panic if memory allocation for a clone
256    /// of a value owned by `self` fails.)
257    /// If the call panics, then `*dst` should be treated as uninitialized memory; it must not be
258    /// read or dropped, because even if it was previously valid, it may have been partially
259    /// overwritten.
260    ///
261    /// The caller may also need to take care to deallocate the allocation pointed to by `dst`,
262    /// if applicable, to avoid a memory leak, and may need to take other precautions to ensure
263    /// soundness in the presence of unwinding.
264    ///
265    /// Implementors should avoid leaking values by, upon unwinding, dropping all component values
266    /// that might have already been created. (For example, if a `[Foo]` of length 3 is being
267    /// cloned, and the second of the three calls to `Foo::clone()` unwinds, then the first `Foo`
268    /// cloned should be dropped.)
269    unsafe fn clone_to_uninit(&self, dst: *mut u8);
270}
271
272#[unstable(feature = "clone_to_uninit", issue = "126799")]
273unsafe impl<T: Clone> CloneToUninit for T {
274    #[inline]
275    unsafe fn clone_to_uninit(&self, dst: *mut u8) {
276        // SAFETY: we're calling a specialization with the same contract
277        unsafe { <T as self::uninit::CopySpec>::clone_one(self, dst.cast::<T>()) }
278    }
279}
280
281#[unstable(feature = "clone_to_uninit", issue = "126799")]
282unsafe impl<T: Clone> CloneToUninit for [T] {
283    #[inline]
284    #[cfg_attr(debug_assertions, track_caller)]
285    unsafe fn clone_to_uninit(&self, dst: *mut u8) {
286        let dst: *mut [T] = dst.with_metadata_of(self);
287        // SAFETY: we're calling a specialization with the same contract
288        unsafe { <T as self::uninit::CopySpec>::clone_slice(self, dst) }
289    }
290}
291
292#[unstable(feature = "clone_to_uninit", issue = "126799")]
293unsafe impl CloneToUninit for str {
294    #[inline]
295    #[cfg_attr(debug_assertions, track_caller)]
296    unsafe fn clone_to_uninit(&self, dst: *mut u8) {
297        // SAFETY: str is just a [u8] with UTF-8 invariant
298        unsafe { self.as_bytes().clone_to_uninit(dst) }
299    }
300}
301
302#[unstable(feature = "clone_to_uninit", issue = "126799")]
303unsafe impl CloneToUninit for crate::ffi::CStr {
304    #[cfg_attr(debug_assertions, track_caller)]
305    unsafe fn clone_to_uninit(&self, dst: *mut u8) {
306        // SAFETY: For now, CStr is just a #[repr(trasnsparent)] [c_char] with some invariants.
307        // And we can cast [c_char] to [u8] on all supported platforms (see: to_bytes_with_nul).
308        // The pointer metadata properly preserves the length (so NUL is also copied).
309        // See: `cstr_metadata_is_length_with_nul` in tests.
310        unsafe { self.to_bytes_with_nul().clone_to_uninit(dst) }
311    }
312}
313
314#[unstable(feature = "bstr", issue = "134915")]
315unsafe impl CloneToUninit for crate::bstr::ByteStr {
316    #[inline]
317    #[cfg_attr(debug_assertions, track_caller)]
318    unsafe fn clone_to_uninit(&self, dst: *mut u8) {
319        // SAFETY: ByteStr is a `#[repr(transparent)]` wrapper around `[u8]`
320        unsafe { self.as_bytes().clone_to_uninit(dst) }
321    }
322}
323
324/// Implementations of `Clone` for primitive types.
325///
326/// Implementations that cannot be described in Rust
327/// are implemented in `traits::SelectionContext::copy_clone_conditions()`
328/// in `rustc_trait_selection`.
329mod impls {
330    macro_rules! impl_clone {
331        ($($t:ty)*) => {
332            $(
333                #[stable(feature = "rust1", since = "1.0.0")]
334                impl Clone for $t {
335                    #[inline(always)]
336                    fn clone(&self) -> Self {
337                        *self
338                    }
339                }
340            )*
341        }
342    }
343
344    impl_clone! {
345        usize u8 u16 u32 u64 u128
346        isize i8 i16 i32 i64 i128
347        f16 f32 f64 f128
348        bool char
349    }
350
351    #[unstable(feature = "never_type", issue = "35121")]
352    impl Clone for ! {
353        #[inline]
354        fn clone(&self) -> Self {
355            *self
356        }
357    }
358
359    #[stable(feature = "rust1", since = "1.0.0")]
360    impl<T: ?Sized> Clone for *const T {
361        #[inline(always)]
362        fn clone(&self) -> Self {
363            *self
364        }
365    }
366
367    #[stable(feature = "rust1", since = "1.0.0")]
368    impl<T: ?Sized> Clone for *mut T {
369        #[inline(always)]
370        fn clone(&self) -> Self {
371            *self
372        }
373    }
374
375    /// Shared references can be cloned, but mutable references *cannot*!
376    #[stable(feature = "rust1", since = "1.0.0")]
377    impl<T: ?Sized> Clone for &T {
378        #[inline(always)]
379        #[rustc_diagnostic_item = "noop_method_clone"]
380        fn clone(&self) -> Self {
381            *self
382        }
383    }
384
385    /// Shared references can be cloned, but mutable references *cannot*!
386    #[stable(feature = "rust1", since = "1.0.0")]
387    impl<T: ?Sized> !Clone for &mut T {}
388}