Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 62c22e3

Browse files
kpreidtautschnig
authored andcommittedMar 19, 2025
Expand CloneToUninit documentation.
* Clarify relationship to `dyn` after rust-lang#133003. * Add an example of using it with `dyn` as rust-lang#133003 enabled. * Add an example of implementing it. * Add links to Rust Reference for the mentioned concepts. * Mention that its method should rarely be called. * Replace parameter name `dst` with `dest` to avoids confusion between “DeSTination” and “Dynamically-Sized Type”. * Various small corrections.
1 parent 7b4656e commit 62c22e3

File tree

1 file changed

+131
-28
lines changed

1 file changed

+131
-28
lines changed
 

‎core/src/clone.rs

+131-28
Original file line numberDiff line numberDiff line change
@@ -262,43 +262,146 @@ pub struct AssertParamIsCopy<T: Copy + ?Sized> {
262262
_field: crate::marker::PhantomData<T>,
263263
}
264264

265-
/// A generalization of [`Clone`] to dynamically-sized types stored in arbitrary containers.
265+
/// A generalization of [`Clone`] to [dynamically-sized types][DST] stored in arbitrary containers.
266266
///
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).
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.
270277
///
271278
/// # Safety
272279
///
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`.
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.)
275321
///
276-
/// # See also
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+
/// flag: bool,
331+
/// contents: T,
332+
/// }
277333
///
278-
/// * [`Clone::clone_from`] is a safe function which may be used instead when `Self` is a [`Sized`]
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+
/// let offset_of_contents =
340+
/// (&raw const self.contents).byte_offset_from_unsigned(&raw const *self);
341+
///
342+
/// // Since `flag` implements `Copy`, we can just copy it.
343+
/// // We use `pointer::write()` instead of assignment because the destination must be
344+
/// // assumed to be uninitialized, whereas an assignment assumes it is initialized.
345+
/// dest.add(offset_of!(Self, flag)).cast::<bool>().write(self.flag);
346+
///
347+
/// // Note: if `flag` owned any resources (i.e. had a `Drop` implementation), then we
348+
/// // must prepare to drop it in case `self.contents.clone_to_uninit()` panics.
349+
/// // In this simple case, where we have exactly one field for which `mem::needs_drop()`
350+
/// // might be true (`contents`), we don’t need to care about cleanup or ordering.
351+
/// self.contents.clone_to_uninit(dest.add(offset_of_contents));
352+
///
353+
/// // All fields of the struct have been initialized, therefore the struct is initialized,
354+
/// // and we have satisfied our `unsafe impl CloneToUninit` obligations.
355+
/// }
356+
/// }
357+
///
358+
/// fn main() {
359+
/// // Construct MyDst<[u8; 4]>, then coerce to MyDst<[u8]>.
360+
/// let first: Rc<MyDst<[u8]>> = Rc::new(MyDst {
361+
/// flag: true,
362+
/// contents: [1, 2, 3, 4],
363+
/// });
364+
///
365+
/// let mut second = first.clone();
366+
/// // make_mut() will call clone_to_uninit().
367+
/// for elem in Rc::make_mut(&mut second).contents.iter_mut() {
368+
/// *elem *= 10;
369+
/// }
370+
///
371+
/// assert_eq!(first.contents, [1, 2, 3, 4]);
372+
/// assert_eq!(second.contents, [10, 20, 30, 40]);
373+
/// }
374+
/// ```
375+
///
376+
/// # See Also
377+
///
378+
/// * [`Clone::clone_from`] is a safe function which may be used instead when [`Self: Sized`](Sized)
279379
/// and the destination is already initialized; it may be able to reuse allocations owned by
280-
/// the destination.
380+
/// the destination, whereas `clone_to_uninit` cannot, since its destination is assumed to be
381+
/// uninitialized.
281382
/// * [`ToOwned`], which allocates a new destination container.
282383
///
283384
/// [`ToOwned`]: ../../std/borrow/trait.ToOwned.html
385+
/// [DST]: https://doc.rust-lang.org/reference/dynamically-sized-types.html
386+
/// [trait object]: https://doc.rust-lang.org/reference/types/trait-object.html
284387
#[unstable(feature = "clone_to_uninit", issue = "126799")]
285388
pub unsafe trait CloneToUninit {
286-
/// Performs copy-assignment from `self` to `dst`.
389+
/// Performs copy-assignment from `self` to `dest`.
287390
///
288-
/// This is analogous to `std::ptr::write(dst.cast(), self.clone())`,
289-
/// except that `self` may be a dynamically-sized type ([`!Sized`](Sized)).
391+
/// This is analogous to `std::ptr::write(dest.cast(), self.clone())`,
392+
/// except that `Self` may be a dynamically-sized type ([`!Sized`](Sized)).
290393
///
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
394+
/// Before this function is called, `dest` may point to uninitialized memory.
395+
/// After this function is called, `dest` will point to initialized memory; it will be
293396
/// sound to create a `&Self` reference from the pointer with the [pointer metadata]
294397
/// from `self`.
295398
///
296399
/// # Safety
297400
///
298401
/// Behavior is undefined if any of the following conditions are violated:
299402
///
300-
/// * `dst` must be [valid] for writes for `size_of_val(self)` bytes.
301-
/// * `dst` must be properly aligned to `align_of_val(self)`.
403+
/// * `dest` must be [valid] for writes for `size_of_val(self)` bytes.
404+
/// * `dest` must be properly aligned to `align_of_val(self)`.
302405
///
303406
/// [valid]: crate::ptr#safety
304407
/// [pointer metadata]: crate::ptr::metadata()
@@ -307,60 +410,60 @@ pub unsafe trait CloneToUninit {
307410
///
308411
/// This function may panic. (For example, it might panic if memory allocation for a clone
309412
/// of a value owned by `self` fails.)
310-
/// If the call panics, then `*dst` should be treated as uninitialized memory; it must not be
413+
/// If the call panics, then `*dest` should be treated as uninitialized memory; it must not be
311414
/// read or dropped, because even if it was previously valid, it may have been partially
312415
/// overwritten.
313416
///
314-
/// The caller may also need to take care to deallocate the allocation pointed to by `dst`,
417+
/// The caller may also need to take care to deallocate the allocation pointed to by `dest`,
315418
/// if applicable, to avoid a memory leak, and may need to take other precautions to ensure
316419
/// soundness in the presence of unwinding.
317420
///
318421
/// Implementors should avoid leaking values by, upon unwinding, dropping all component values
319422
/// that might have already been created. (For example, if a `[Foo]` of length 3 is being
320423
/// cloned, and the second of the three calls to `Foo::clone()` unwinds, then the first `Foo`
321424
/// cloned should be dropped.)
322-
unsafe fn clone_to_uninit(&self, dst: *mut u8);
425+
unsafe fn clone_to_uninit(&self, dest: *mut u8);
323426
}
324427

325428
#[unstable(feature = "clone_to_uninit", issue = "126799")]
326429
unsafe impl<T: Clone> CloneToUninit for T {
327430
#[inline]
328-
unsafe fn clone_to_uninit(&self, dst: *mut u8) {
431+
unsafe fn clone_to_uninit(&self, dest: *mut u8) {
329432
// SAFETY: we're calling a specialization with the same contract
330-
unsafe { <T as self::uninit::CopySpec>::clone_one(self, dst.cast::<T>()) }
433+
unsafe { <T as self::uninit::CopySpec>::clone_one(self, dest.cast::<T>()) }
331434
}
332435
}
333436

334437
#[unstable(feature = "clone_to_uninit", issue = "126799")]
335438
unsafe impl<T: Clone> CloneToUninit for [T] {
336439
#[inline]
337440
#[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);
441+
unsafe fn clone_to_uninit(&self, dest: *mut u8) {
442+
let dest: *mut [T] = dest.with_metadata_of(self);
340443
// SAFETY: we're calling a specialization with the same contract
341-
unsafe { <T as self::uninit::CopySpec>::clone_slice(self, dst) }
444+
unsafe { <T as self::uninit::CopySpec>::clone_slice(self, dest) }
342445
}
343446
}
344447

345448
#[unstable(feature = "clone_to_uninit", issue = "126799")]
346449
unsafe impl CloneToUninit for str {
347450
#[inline]
348451
#[cfg_attr(debug_assertions, track_caller)]
349-
unsafe fn clone_to_uninit(&self, dst: *mut u8) {
452+
unsafe fn clone_to_uninit(&self, dest: *mut u8) {
350453
// SAFETY: str is just a [u8] with UTF-8 invariant
351-
unsafe { self.as_bytes().clone_to_uninit(dst) }
454+
unsafe { self.as_bytes().clone_to_uninit(dest) }
352455
}
353456
}
354457

355458
#[unstable(feature = "clone_to_uninit", issue = "126799")]
356459
unsafe impl CloneToUninit for crate::ffi::CStr {
357460
#[cfg_attr(debug_assertions, track_caller)]
358-
unsafe fn clone_to_uninit(&self, dst: *mut u8) {
461+
unsafe fn clone_to_uninit(&self, dest: *mut u8) {
359462
// SAFETY: For now, CStr is just a #[repr(trasnsparent)] [c_char] with some invariants.
360463
// And we can cast [c_char] to [u8] on all supported platforms (see: to_bytes_with_nul).
361464
// The pointer metadata properly preserves the length (so NUL is also copied).
362465
// See: `cstr_metadata_is_length_with_nul` in tests.
363-
unsafe { self.to_bytes_with_nul().clone_to_uninit(dst) }
466+
unsafe { self.to_bytes_with_nul().clone_to_uninit(dest) }
364467
}
365468
}
366469

0 commit comments

Comments
 (0)
Failed to load comments.