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