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 stored in arbitrary containers.
266///
267/// This trait is implemented for all types implementing [`Clone`], and also [slices](slice) of all
268/// such types. You may also implement this trait to enable cloning trait objects and custom DSTs
269/// (structures containing dynamically-sized fields).
270///
271/// # Safety
272///
273/// Implementations must ensure that when `.clone_to_uninit(dst)` returns normally rather than
274/// panicking, it always leaves `*dst` initialized as a valid value of type `Self`.
275///
276/// # See also
277///
278/// * [`Clone::clone_from`] is a safe function which may be used instead when `Self` is a [`Sized`]
279/// and the destination is already initialized; it may be able to reuse allocations owned by
280/// the destination.
281/// * [`ToOwned`], which allocates a new destination container.
282///
283/// [`ToOwned`]: ../../std/borrow/trait.ToOwned.html
284#[unstable(feature = "clone_to_uninit", issue = "126799")]
285pub unsafe trait CloneToUninit {
286 /// Performs copy-assignment from `self` to `dst`.
287 ///
288 /// This is analogous to `std::ptr::write(dst.cast(), self.clone())`,
289 /// except that `self` may be a dynamically-sized type ([`!Sized`](Sized)).
290 ///
291 /// Before this function is called, `dst` may point to uninitialized memory.
292 /// After this function is called, `dst` will point to initialized memory; it will be
293 /// sound to create a `&Self` reference from the pointer with the [pointer metadata]
294 /// from `self`.
295 ///
296 /// # Safety
297 ///
298 /// Behavior is undefined if any of the following conditions are violated:
299 ///
300 /// * `dst` must be [valid] for writes for `size_of_val(self)` bytes.
301 /// * `dst` must be properly aligned to `align_of_val(self)`.
302 ///
303 /// [valid]: crate::ptr#safety
304 /// [pointer metadata]: crate::ptr::metadata()
305 ///
306 /// # Panics
307 ///
308 /// This function may panic. (For example, it might panic if memory allocation for a clone
309 /// of a value owned by `self` fails.)
310 /// If the call panics, then `*dst` should be treated as uninitialized memory; it must not be
311 /// read or dropped, because even if it was previously valid, it may have been partially
312 /// overwritten.
313 ///
314 /// The caller may also need to take care to deallocate the allocation pointed to by `dst`,
315 /// if applicable, to avoid a memory leak, and may need to take other precautions to ensure
316 /// soundness in the presence of unwinding.
317 ///
318 /// Implementors should avoid leaking values by, upon unwinding, dropping all component values
319 /// that might have already been created. (For example, if a `[Foo]` of length 3 is being
320 /// cloned, and the second of the three calls to `Foo::clone()` unwinds, then the first `Foo`
321 /// cloned should be dropped.)
322 unsafe fn clone_to_uninit(&self, dst: *mut u8);
323}
324
325#[unstable(feature = "clone_to_uninit", issue = "126799")]
326unsafe impl<T: Clone> CloneToUninit for T {
327 #[inline]
328 unsafe fn clone_to_uninit(&self, dst: *mut u8) {
329 // SAFETY: we're calling a specialization with the same contract
330 unsafe { <T as self::uninit::CopySpec>::clone_one(self, dst.cast::<T>()) }
331 }
332}
333
334#[unstable(feature = "clone_to_uninit", issue = "126799")]
335unsafe impl<T: Clone> CloneToUninit for [T] {
336 #[inline]
337 #[cfg_attr(debug_assertions, track_caller)]
338 unsafe fn clone_to_uninit(&self, dst: *mut u8) {
339 let dst: *mut [T] = dst.with_metadata_of(self);
340 // SAFETY: we're calling a specialization with the same contract
341 unsafe { <T as self::uninit::CopySpec>::clone_slice(self, dst) }
342 }
343}
344
345#[unstable(feature = "clone_to_uninit", issue = "126799")]
346unsafe impl CloneToUninit for str {
347 #[inline]
348 #[cfg_attr(debug_assertions, track_caller)]
349 unsafe fn clone_to_uninit(&self, dst: *mut u8) {
350 // SAFETY: str is just a [u8] with UTF-8 invariant
351 unsafe { self.as_bytes().clone_to_uninit(dst) }
352 }
353}
354
355#[unstable(feature = "clone_to_uninit", issue = "126799")]
356unsafe impl CloneToUninit for crate::ffi::CStr {
357 #[cfg_attr(debug_assertions, track_caller)]
358 unsafe fn clone_to_uninit(&self, dst: *mut u8) {
359 // SAFETY: For now, CStr is just a #[repr(trasnsparent)] [c_char] with some invariants.
360 // And we can cast [c_char] to [u8] on all supported platforms (see: to_bytes_with_nul).
361 // The pointer metadata properly preserves the length (so NUL is also copied).
362 // See: `cstr_metadata_is_length_with_nul` in tests.
363 unsafe { self.to_bytes_with_nul().clone_to_uninit(dst) }
364 }
365}
366
367#[unstable(feature = "bstr", issue = "134915")]
368unsafe impl CloneToUninit for crate::bstr::ByteStr {
369 #[inline]
370 #[cfg_attr(debug_assertions, track_caller)]
371 unsafe fn clone_to_uninit(&self, dst: *mut u8) {
372 // SAFETY: ByteStr is a `#[repr(transparent)]` wrapper around `[u8]`
373 unsafe { self.as_bytes().clone_to_uninit(dst) }
374 }
375}
376
377/// Implementations of `Clone` for primitive types.
378///
379/// Implementations that cannot be described in Rust
380/// are implemented in `traits::SelectionContext::copy_clone_conditions()`
381/// in `rustc_trait_selection`.
382mod impls {
383 macro_rules! impl_clone {
384 ($($t:ty)*) => {
385 $(
386 #[stable(feature = "rust1", since = "1.0.0")]
387 impl Clone for $t {
388 #[inline(always)]
389 fn clone(&self) -> Self {
390 *self
391 }
392 }
393 )*
394 }
395 }
396
397 impl_clone! {
398 usize u8 u16 u32 u64 u128
399 isize i8 i16 i32 i64 i128
400 f16 f32 f64 f128
401 bool char
402 }
403
404 #[unstable(feature = "never_type", issue = "35121")]
405 impl Clone for ! {
406 #[inline]
407 fn clone(&self) -> Self {
408 *self
409 }
410 }
411
412 #[stable(feature = "rust1", since = "1.0.0")]
413 impl<T: ?Sized> Clone for *const T {
414 #[inline(always)]
415 fn clone(&self) -> Self {
416 *self
417 }
418 }
419
420 #[stable(feature = "rust1", since = "1.0.0")]
421 impl<T: ?Sized> Clone for *mut T {
422 #[inline(always)]
423 fn clone(&self) -> Self {
424 *self
425 }
426 }
427
428 /// Shared references can be cloned, but mutable references *cannot*!
429 #[stable(feature = "rust1", since = "1.0.0")]
430 impl<T: ?Sized> Clone for &T {
431 #[inline(always)]
432 #[rustc_diagnostic_item = "noop_method_clone"]
433 fn clone(&self) -> Self {
434 *self
435 }
436 }
437
438 /// Shared references can be cloned, but mutable references *cannot*!
439 #[stable(feature = "rust1", since = "1.0.0")]
440 impl<T: ?Sized> !Clone for &mut T {}
441}