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

            
39
use crate::marker::{Destruct, PointeeSized};
40

            
41
#[cfg(not(feature = "ferrocene_certified"))]
42
mod uninit;
43

            
44
/// A common trait that allows explicit creation of a duplicate value.
45
///
46
/// Calling [`clone`] always produces a new value.
47
/// However, for types that are references to other data (such as smart pointers or references),
48
/// the new value may still point to the same underlying data, rather than duplicating it.
49
/// See [`Clone::clone`] for more details.
50
///
51
/// This distinction is especially important when using `#[derive(Clone)]` on structs containing
52
/// smart pointers like `Arc<Mutex<T>>` - the cloned struct will share mutable state with the
53
/// original.
54
///
55
/// Differs from [`Copy`] in that [`Copy`] is implicit and an inexpensive bit-wise copy, while
56
/// `Clone` is always explicit and may or may not be expensive. In order to enforce
57
/// these characteristics, Rust does not allow you to reimplement [`Copy`], but you
58
/// may reimplement `Clone` and run arbitrary code.
59
///
60
/// Since `Clone` is more general than [`Copy`], you can automatically make anything
61
/// [`Copy`] be `Clone` as well.
62
///
63
/// ## Derivable
64
///
65
/// This trait can be used with `#[derive]` if all fields are `Clone`. The `derive`d
66
/// implementation of [`Clone`] calls [`clone`] on each field.
67
///
68
/// [`clone`]: Clone::clone
69
///
70
/// For a generic struct, `#[derive]` implements `Clone` conditionally by adding bound `Clone` on
71
/// generic parameters.
72
///
73
/// ```
74
/// // `derive` implements Clone for Reading<T> when T is Clone.
75
/// #[derive(Clone)]
76
/// struct Reading<T> {
77
///     frequency: T,
78
/// }
79
/// ```
80
///
81
/// ## How can I implement `Clone`?
82
///
83
/// Types that are [`Copy`] should have a trivial implementation of `Clone`. More formally:
84
/// if `T: Copy`, `x: T`, and `y: &T`, then `let x = y.clone();` is equivalent to `let x = *y;`.
85
/// Manual implementations should be careful to uphold this invariant; however, unsafe code
86
/// must not rely on it to ensure memory safety.
87
///
88
/// An example is a generic struct holding a function pointer. In this case, the
89
/// implementation of `Clone` cannot be `derive`d, but can be implemented as:
90
///
91
/// ```
92
/// struct Generate<T>(fn() -> T);
93
///
94
/// impl<T> Copy for Generate<T> {}
95
///
96
/// impl<T> Clone for Generate<T> {
97
///     fn clone(&self) -> Self {
98
///         *self
99
///     }
100
/// }
101
/// ```
102
///
103
/// If we `derive`:
104
///
105
/// ```
106
/// #[derive(Copy, Clone)]
107
/// struct Generate<T>(fn() -> T);
108
/// ```
109
///
110
/// the auto-derived implementations will have unnecessary `T: Copy` and `T: Clone` bounds:
111
///
112
/// ```
113
/// # struct Generate<T>(fn() -> T);
114
///
115
/// // Automatically derived
116
/// impl<T: Copy> Copy for Generate<T> { }
117
///
118
/// // Automatically derived
119
/// impl<T: Clone> Clone for Generate<T> {
120
///     fn clone(&self) -> Generate<T> {
121
///         Generate(Clone::clone(&self.0))
122
///     }
123
/// }
124
/// ```
125
///
126
/// The bounds are unnecessary because clearly the function itself should be
127
/// copy- and cloneable even if its return type is not:
128
///
129
/// ```compile_fail,E0599
130
/// #[derive(Copy, Clone)]
131
/// struct Generate<T>(fn() -> T);
132
///
133
/// struct NotCloneable;
134
///
135
/// fn generate_not_cloneable() -> NotCloneable {
136
///     NotCloneable
137
/// }
138
///
139
/// Generate(generate_not_cloneable).clone(); // error: trait bounds were not satisfied
140
/// // Note: With the manual implementations the above line will compile.
141
/// ```
142
///
143
/// ## `Clone` and `PartialEq`/`Eq`
144
/// `Clone` is intended for the duplication of objects. Consequently, when implementing
145
/// both `Clone` and [`PartialEq`], the following property is expected to hold:
146
/// ```text
147
/// x == x -> x.clone() == x
148
/// ```
149
/// In other words, if an object compares equal to itself,
150
/// its clone must also compare equal to the original.
151
///
152
/// For types that also implement [`Eq`] – for which `x == x` always holds –
153
/// this implies that `x.clone() == x` must always be true.
154
/// Standard library collections such as
155
/// [`HashMap`], [`HashSet`], [`BTreeMap`], [`BTreeSet`] and [`BinaryHeap`]
156
/// rely on their keys respecting this property for correct behavior.
157
/// Furthermore, these collections require that cloning a key preserves the outcome of the
158
/// [`Hash`] and [`Ord`] methods. Thankfully, this follows automatically from `x.clone() == x`
159
/// if `Hash` and `Ord` are correctly implemented according to their own requirements.
160
///
161
/// When deriving both `Clone` and [`PartialEq`] using `#[derive(Clone, PartialEq)]`
162
/// or when additionally deriving [`Eq`] using `#[derive(Clone, PartialEq, Eq)]`,
163
/// then this property is automatically upheld – provided that it is satisfied by
164
/// the underlying types.
165
///
166
/// Violating this property is a logic error. The behavior resulting from a logic error is not
167
/// specified, but users of the trait must ensure that such logic errors do *not* result in
168
/// undefined behavior. This means that `unsafe` code **must not** rely on this property
169
/// being satisfied.
170
///
171
/// ## Additional implementors
172
///
173
/// In addition to the [implementors listed below][impls],
174
/// the following types also implement `Clone`:
175
///
176
/// * Function item types (i.e., the distinct types defined for each function)
177
/// * Function pointer types (e.g., `fn() -> i32`)
178
/// * Closure types, if they capture no value from the environment
179
///   or if all such captured values implement `Clone` themselves.
180
///   Note that variables captured by shared reference always implement `Clone`
181
///   (even if the referent doesn't),
182
///   while variables captured by mutable reference never implement `Clone`.
183
///
184
/// [`HashMap`]: ../../std/collections/struct.HashMap.html
185
/// [`HashSet`]: ../../std/collections/struct.HashSet.html
186
/// [`BTreeMap`]: ../../std/collections/struct.BTreeMap.html
187
/// [`BTreeSet`]: ../../std/collections/struct.BTreeSet.html
188
/// [`BinaryHeap`]: ../../std/collections/struct.BinaryHeap.html
189
/// [impls]: #implementors
190
#[stable(feature = "rust1", since = "1.0.0")]
191
#[lang = "clone"]
192
#[rustc_diagnostic_item = "Clone"]
193
#[rustc_trivial_field_reads]
194
#[rustc_const_unstable(feature = "const_clone", issue = "142757")]
195
#[const_trait]
196
pub trait Clone: Sized {
197
    /// Returns a duplicate of the value.
198
    ///
199
    /// Note that what "duplicate" means varies by type:
200
    /// - For most types, this creates a deep, independent copy
201
    /// - For reference types like `&T`, this creates another reference to the same value
202
    /// - For smart pointers like [`Arc`] or [`Rc`], this increments the reference count
203
    ///   but still points to the same underlying data
204
    ///
205
    /// [`Arc`]: ../../std/sync/struct.Arc.html
206
    /// [`Rc`]: ../../std/rc/struct.Rc.html
207
    ///
208
    /// # Examples
209
    ///
210
    /// ```
211
    /// # #![allow(noop_method_call)]
212
    /// let hello = "Hello"; // &str implements Clone
213
    ///
214
    /// assert_eq!("Hello", hello.clone());
215
    /// ```
216
    ///
217
    /// Example with a reference-counted type:
218
    ///
219
    /// ```
220
    /// use std::sync::{Arc, Mutex};
221
    ///
222
    /// let data = Arc::new(Mutex::new(vec![1, 2, 3]));
223
    /// let data_clone = data.clone(); // Creates another Arc pointing to the same Mutex
224
    ///
225
    /// {
226
    ///     let mut lock = data.lock().unwrap();
227
    ///     lock.push(4);
228
    /// }
229
    ///
230
    /// // Changes are visible through the clone because they share the same underlying data
231
    /// assert_eq!(*data_clone.lock().unwrap(), vec![1, 2, 3, 4]);
232
    /// ```
233
    #[stable(feature = "rust1", since = "1.0.0")]
234
    #[must_use = "cloning is often expensive and is not expected to have side effects"]
235
    // Clone::clone is special because the compiler generates MIR to implement it for some types.
236
    // See InstanceKind::CloneShim.
237
    #[lang = "clone_fn"]
238
    fn clone(&self) -> Self;
239

            
240
    /// Performs copy-assignment from `source`.
241
    ///
242
    /// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality,
243
    /// but can be overridden to reuse the resources of `a` to avoid unnecessary
244
    /// allocations.
245
    #[inline]
246
    #[stable(feature = "rust1", since = "1.0.0")]
247
    fn clone_from(&mut self, source: &Self)
248
    where
249
        Self: [const] Destruct,
250
    {
251
        *self = source.clone()
252
    }
253
}
254

            
255
/// Derive macro generating an impl of the trait `Clone`.
256
#[rustc_builtin_macro]
257
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
258
#[allow_internal_unstable(core_intrinsics, derive_clone_copy)]
259
pub macro Clone($item:item) {
260
    /* compiler built-in */
261
}
262

            
263
/// Trait for objects whose [`Clone`] impl is lightweight (e.g. reference-counted)
264
///
265
/// Cloning an object implementing this trait should in general:
266
/// - be O(1) (constant) time regardless of the amount of data managed by the object,
267
/// - not require a memory allocation,
268
/// - not require copying more than roughly 64 bytes (a typical cache line size),
269
/// - not block the current thread,
270
/// - not have any semantic side effects (e.g. allocating a file descriptor), and
271
/// - not have overhead larger than a couple of atomic operations.
272
///
273
/// The `UseCloned` trait does not provide a method; instead, it indicates that
274
/// `Clone::clone` is lightweight, and allows the use of the `.use` syntax.
275
///
276
/// ## .use postfix syntax
277
///
278
/// Values can be `.use`d by adding `.use` postfix to the value you want to use.
279
///
280
/// ```ignore (this won't work until we land use)
281
/// fn foo(f: Foo) {
282
///     // if `Foo` implements `Copy` f would be copied into x.
283
///     // if `Foo` implements `UseCloned` f would be cloned into x.
284
///     // otherwise f would be moved into x.
285
///     let x = f.use;
286
///     // ...
287
/// }
288
/// ```
289
///
290
/// ## use closures
291
///
292
/// Use closures allow captured values to be automatically used.
293
/// This is similar to have a closure that you would call `.use` over each captured value.
294
#[unstable(feature = "ergonomic_clones", issue = "132290")]
295
#[lang = "use_cloned"]
296
#[cfg(not(feature = "ferrocene_certified"))]
297
pub trait UseCloned: Clone {
298
    // Empty.
299
}
300

            
301
#[cfg(not(feature = "ferrocene_certified"))]
302
macro_rules! impl_use_cloned {
303
    ($($t:ty)*) => {
304
        $(
305
            #[unstable(feature = "ergonomic_clones", issue = "132290")]
306
            impl UseCloned for $t {}
307
        )*
308
    }
309
}
310

            
311
#[cfg(not(feature = "ferrocene_certified"))]
312
impl_use_cloned! {
313
    usize u8 u16 u32 u64 u128
314
    isize i8 i16 i32 i64 i128
315
             f16 f32 f64 f128
316
    bool char
317
}
318

            
319
// FIXME(aburka): these structs are used solely by #[derive] to
320
// assert that every component of a type implements Clone or Copy.
321
//
322
// These structs should never appear in user code.
323
#[doc(hidden)]
324
#[allow(missing_debug_implementations)]
325
#[unstable(
326
    feature = "derive_clone_copy",
327
    reason = "deriving hack, should not be public",
328
    issue = "none"
329
)]
330
pub struct AssertParamIsClone<T: Clone + PointeeSized> {
331
    _field: crate::marker::PhantomData<T>,
332
}
333
#[doc(hidden)]
334
#[allow(missing_debug_implementations)]
335
#[unstable(
336
    feature = "derive_clone_copy",
337
    reason = "deriving hack, should not be public",
338
    issue = "none"
339
)]
340
#[cfg(not(feature = "ferrocene_certified"))]
341
pub struct AssertParamIsCopy<T: Copy + PointeeSized> {
342
    _field: crate::marker::PhantomData<T>,
343
}
344

            
345
/// A generalization of [`Clone`] to [dynamically-sized types][DST] stored in arbitrary containers.
346
///
347
/// This trait is implemented for all types implementing [`Clone`], [slices](slice) of all
348
/// such types, and other dynamically-sized types in the standard library.
349
/// You may also implement this trait to enable cloning custom DSTs
350
/// (structures containing dynamically-sized fields), or use it as a supertrait to enable
351
/// cloning a [trait object].
352
///
353
/// This trait is normally used via operations on container types which support DSTs,
354
/// so you should not typically need to call `.clone_to_uninit()` explicitly except when
355
/// implementing such a container or otherwise performing explicit management of an allocation,
356
/// or when implementing `CloneToUninit` itself.
357
///
358
/// # Safety
359
///
360
/// Implementations must ensure that when `.clone_to_uninit(dest)` returns normally rather than
361
/// panicking, it always leaves `*dest` initialized as a valid value of type `Self`.
362
///
363
/// # Examples
364
///
365
// FIXME(#126799): when `Box::clone` allows use of `CloneToUninit`, rewrite these examples with it
366
// since `Rc` is a distraction.
367
///
368
/// If you are defining a trait, you can add `CloneToUninit` as a supertrait to enable cloning of
369
/// `dyn` values of your trait:
370
///
371
/// ```
372
/// #![feature(clone_to_uninit)]
373
/// use std::rc::Rc;
374
///
375
/// trait Foo: std::fmt::Debug + std::clone::CloneToUninit {
376
///     fn modify(&mut self);
377
///     fn value(&self) -> i32;
378
/// }
379
///
380
/// impl Foo for i32 {
381
///     fn modify(&mut self) {
382
///         *self *= 10;
383
///     }
384
///     fn value(&self) -> i32 {
385
///         *self
386
///     }
387
/// }
388
///
389
/// let first: Rc<dyn Foo> = Rc::new(1234);
390
///
391
/// let mut second = first.clone();
392
/// Rc::make_mut(&mut second).modify(); // make_mut() will call clone_to_uninit()
393
///
394
/// assert_eq!(first.value(), 1234);
395
/// assert_eq!(second.value(), 12340);
396
/// ```
397
///
398
/// The following is an example of implementing `CloneToUninit` for a custom DST.
399
/// (It is essentially a limited form of what `derive(CloneToUninit)` would do,
400
/// if such a derive macro existed.)
401
///
402
/// ```
403
/// #![feature(clone_to_uninit)]
404
/// use std::clone::CloneToUninit;
405
/// use std::mem::offset_of;
406
/// use std::rc::Rc;
407
///
408
/// #[derive(PartialEq)]
409
/// struct MyDst<T: ?Sized> {
410
///     label: String,
411
///     contents: T,
412
/// }
413
///
414
/// unsafe impl<T: ?Sized + CloneToUninit> CloneToUninit for MyDst<T> {
415
///     unsafe fn clone_to_uninit(&self, dest: *mut u8) {
416
///         // The offset of `self.contents` is dynamic because it depends on the alignment of T
417
///         // which can be dynamic (if `T = dyn SomeTrait`). Therefore, we have to obtain it
418
///         // dynamically by examining `self`, rather than using `offset_of!`.
419
///         //
420
///         // SAFETY: `self` by definition points somewhere before `&self.contents` in the same
421
///         // allocation.
422
///         let offset_of_contents = unsafe {
423
///             (&raw const self.contents).byte_offset_from_unsigned(self)
424
///         };
425
///
426
///         // Clone the *sized* fields of `self` (just one, in this example).
427
///         // (By cloning this first and storing it temporarily in a local variable, we avoid
428
///         // leaking it in case of any panic, using the ordinary automatic cleanup of local
429
///         // variables. Such a leak would be sound, but undesirable.)
430
///         let label = self.label.clone();
431
///
432
///         // SAFETY: The caller must provide a `dest` such that these field offsets are valid
433
///         // to write to.
434
///         unsafe {
435
///             // Clone the unsized field directly from `self` to `dest`.
436
///             self.contents.clone_to_uninit(dest.add(offset_of_contents));
437
///
438
///             // Now write all the sized fields.
439
///             //
440
///             // Note that we only do this once all of the clone() and clone_to_uninit() calls
441
///             // have completed, and therefore we know that there are no more possible panics;
442
///             // this ensures no memory leaks in case of panic.
443
///             dest.add(offset_of!(Self, label)).cast::<String>().write(label);
444
///         }
445
///         // All fields of the struct have been initialized; therefore, the struct is initialized,
446
///         // and we have satisfied our `unsafe impl CloneToUninit` obligations.
447
///     }
448
/// }
449
///
450
/// fn main() {
451
///     // Construct MyDst<[u8; 4]>, then coerce to MyDst<[u8]>.
452
///     let first: Rc<MyDst<[u8]>> = Rc::new(MyDst {
453
///         label: String::from("hello"),
454
///         contents: [1, 2, 3, 4],
455
///     });
456
///
457
///     let mut second = first.clone();
458
///     // make_mut() will call clone_to_uninit().
459
///     for elem in Rc::make_mut(&mut second).contents.iter_mut() {
460
///         *elem *= 10;
461
///     }
462
///
463
///     assert_eq!(first.contents, [1, 2, 3, 4]);
464
///     assert_eq!(second.contents, [10, 20, 30, 40]);
465
///     assert_eq!(second.label, "hello");
466
/// }
467
/// ```
468
///
469
/// # See Also
470
///
471
/// * [`Clone::clone_from`] is a safe function which may be used instead when [`Self: Sized`](Sized)
472
///   and the destination is already initialized; it may be able to reuse allocations owned by
473
///   the destination, whereas `clone_to_uninit` cannot, since its destination is assumed to be
474
///   uninitialized.
475
/// * [`ToOwned`], which allocates a new destination container.
476
///
477
/// [`ToOwned`]: ../../std/borrow/trait.ToOwned.html
478
/// [DST]: https://doc.rust-lang.org/reference/dynamically-sized-types.html
479
/// [trait object]: https://doc.rust-lang.org/reference/types/trait-object.html
480
#[unstable(feature = "clone_to_uninit", issue = "126799")]
481
#[cfg(not(feature = "ferrocene_certified"))]
482
pub unsafe trait CloneToUninit {
483
    /// Performs copy-assignment from `self` to `dest`.
484
    ///
485
    /// This is analogous to `std::ptr::write(dest.cast(), self.clone())`,
486
    /// except that `Self` may be a dynamically-sized type ([`!Sized`](Sized)).
487
    ///
488
    /// Before this function is called, `dest` may point to uninitialized memory.
489
    /// After this function is called, `dest` will point to initialized memory; it will be
490
    /// sound to create a `&Self` reference from the pointer with the [pointer metadata]
491
    /// from `self`.
492
    ///
493
    /// # Safety
494
    ///
495
    /// Behavior is undefined if any of the following conditions are violated:
496
    ///
497
    /// * `dest` must be [valid] for writes for `size_of_val(self)` bytes.
498
    /// * `dest` must be properly aligned to `align_of_val(self)`.
499
    ///
500
    /// [valid]: crate::ptr#safety
501
    /// [pointer metadata]: crate::ptr::metadata()
502
    ///
503
    /// # Panics
504
    ///
505
    /// This function may panic. (For example, it might panic if memory allocation for a clone
506
    /// of a value owned by `self` fails.)
507
    /// If the call panics, then `*dest` should be treated as uninitialized memory; it must not be
508
    /// read or dropped, because even if it was previously valid, it may have been partially
509
    /// overwritten.
510
    ///
511
    /// The caller may wish to take care to deallocate the allocation pointed to by `dest`,
512
    /// if applicable, to avoid a memory leak (but this is not a requirement).
513
    ///
514
    /// Implementors should avoid leaking values by, upon unwinding, dropping all component values
515
    /// that might have already been created. (For example, if a `[Foo]` of length 3 is being
516
    /// cloned, and the second of the three calls to `Foo::clone()` unwinds, then the first `Foo`
517
    /// cloned should be dropped.)
518
    unsafe fn clone_to_uninit(&self, dest: *mut u8);
519
}
520

            
521
#[unstable(feature = "clone_to_uninit", issue = "126799")]
522
#[cfg(not(feature = "ferrocene_certified"))]
523
unsafe impl<T: Clone> CloneToUninit for T {
524
    #[inline]
525
    unsafe fn clone_to_uninit(&self, dest: *mut u8) {
526
        // SAFETY: we're calling a specialization with the same contract
527
        unsafe { <T as self::uninit::CopySpec>::clone_one(self, dest.cast::<T>()) }
528
    }
529
}
530

            
531
#[unstable(feature = "clone_to_uninit", issue = "126799")]
532
#[cfg(not(feature = "ferrocene_certified"))]
533
unsafe impl<T: Clone> CloneToUninit for [T] {
534
    #[inline]
535
    #[cfg_attr(debug_assertions, track_caller)]
536
    unsafe fn clone_to_uninit(&self, dest: *mut u8) {
537
        let dest: *mut [T] = dest.with_metadata_of(self);
538
        // SAFETY: we're calling a specialization with the same contract
539
        unsafe { <T as self::uninit::CopySpec>::clone_slice(self, dest) }
540
    }
541
}
542

            
543
#[unstable(feature = "clone_to_uninit", issue = "126799")]
544
#[cfg(not(feature = "ferrocene_certified"))]
545
unsafe impl CloneToUninit for str {
546
    #[inline]
547
    #[cfg_attr(debug_assertions, track_caller)]
548
    unsafe fn clone_to_uninit(&self, dest: *mut u8) {
549
        // SAFETY: str is just a [u8] with UTF-8 invariant
550
        unsafe { self.as_bytes().clone_to_uninit(dest) }
551
    }
552
}
553

            
554
#[unstable(feature = "clone_to_uninit", issue = "126799")]
555
#[cfg(not(feature = "ferrocene_certified"))]
556
unsafe impl CloneToUninit for crate::ffi::CStr {
557
    #[cfg_attr(debug_assertions, track_caller)]
558
    unsafe fn clone_to_uninit(&self, dest: *mut u8) {
559
        // SAFETY: For now, CStr is just a #[repr(trasnsparent)] [c_char] with some invariants.
560
        // And we can cast [c_char] to [u8] on all supported platforms (see: to_bytes_with_nul).
561
        // The pointer metadata properly preserves the length (so NUL is also copied).
562
        // See: `cstr_metadata_is_length_with_nul` in tests.
563
        unsafe { self.to_bytes_with_nul().clone_to_uninit(dest) }
564
    }
565
}
566

            
567
#[unstable(feature = "bstr", issue = "134915")]
568
#[cfg(not(feature = "ferrocene_certified"))]
569
unsafe impl CloneToUninit for crate::bstr::ByteStr {
570
    #[inline]
571
    #[cfg_attr(debug_assertions, track_caller)]
572
    unsafe fn clone_to_uninit(&self, dst: *mut u8) {
573
        // SAFETY: ByteStr is a `#[repr(transparent)]` wrapper around `[u8]`
574
        unsafe { self.as_bytes().clone_to_uninit(dst) }
575
    }
576
}
577

            
578
/// Implementations of `Clone` for primitive types.
579
///
580
/// Implementations that cannot be described in Rust
581
/// are implemented in `traits::SelectionContext::copy_clone_conditions()`
582
/// in `rustc_trait_selection`.
583
mod impls {
584
    use crate::marker::PointeeSized;
585

            
586
    macro_rules! impl_clone {
587
        ($($t:ty)*) => {
588
            $(
589
                #[stable(feature = "rust1", since = "1.0.0")]
590
                impl Clone for $t {
591
                    #[inline(always)]
592
3483129
                    fn clone(&self) -> Self {
593
3483129
                        *self
594
3483129
                    }
595
                }
596
            )*
597
        }
598
    }
599

            
600
    #[cfg(not(feature = "ferrocene_certified"))]
601
    impl_clone! {
602
        usize u8 u16 u32 u64 u128
603
        isize i8 i16 i32 i64 i128
604
        f16 f32 f64 f128
605
        bool char
606
    }
607

            
608
    #[cfg(feature = "ferrocene_certified")]
609
    impl_clone! {
610
        usize u8 u16 u32 u64 u128
611
        isize i8 i16 i32 i64 i128
612
        f32 f64
613
        bool
614
    }
615

            
616
    #[unstable(feature = "never_type", issue = "35121")]
617
    #[cfg(not(feature = "ferrocene_certified"))]
618
    impl Clone for ! {
619
        #[inline]
620
        fn clone(&self) -> Self {
621
            *self
622
        }
623
    }
624

            
625
    #[stable(feature = "rust1", since = "1.0.0")]
626
    impl<T: PointeeSized> Clone for *const T {
627
        #[inline(always)]
628
        fn clone(&self) -> Self {
629
            *self
630
        }
631
    }
632

            
633
    #[stable(feature = "rust1", since = "1.0.0")]
634
    impl<T: PointeeSized> Clone for *mut T {
635
        #[inline(always)]
636
        fn clone(&self) -> Self {
637
            *self
638
        }
639
    }
640

            
641
    /// Shared references can be cloned, but mutable references *cannot*!
642
    #[stable(feature = "rust1", since = "1.0.0")]
643
    impl<T: PointeeSized> Clone for &T {
644
        #[inline(always)]
645
        #[rustc_diagnostic_item = "noop_method_clone"]
646
185
        fn clone(&self) -> Self {
647
185
            self
648
185
        }
649
    }
650

            
651
    /// Shared references can be cloned, but mutable references *cannot*!
652
    #[stable(feature = "rust1", since = "1.0.0")]
653
    #[cfg(not(feature = "ferrocene_certified"))]
654
    impl<T: PointeeSized> !Clone for &mut T {}
655
}