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 64ec867

Browse files
committedFeb 27, 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 ac91805 commit 64ec867

File tree

1 file changed

+131
-28
lines changed

1 file changed

+131
-28
lines changed
 

‎library/core/src/clone.rs

+131-28
Original file line numberDiff line numberDiff line change
@@ -209,43 +209,146 @@ pub struct AssertParamIsCopy<T: Copy + ?Sized> {
209209
_field: crate::marker::PhantomData<T>,
210210
}
211211

212-
/// A generalization of [`Clone`] to dynamically-sized types stored in arbitrary containers.
212+
/// A generalization of [`Clone`] to [dynamically-sized types][DST] stored in arbitrary containers.
213213
///
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).
214+
/// This trait is implemented for all types implementing [`Clone`], [slices](slice) of all
215+
/// such types, and other dynamically-sized types in the standard library.
216+
/// You may also implement this trait to enable cloning custom DSTs
217+
/// (structures containing dynamically-sized fields), or use it as a supertrait to enable
218+
/// cloning a [trait object].
219+
///
220+
/// This trait is normally used via operations on container types which support DSTs,
221+
/// so you should not typically need to call `.clone_to_uninit()` explicitly except when
222+
/// implementing such a container or otherwise performing explicit management of an allocation,
223+
/// or when implementing `CloneToUninit` itself.
217224
///
218225
/// # Safety
219226
///
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`.
227+
/// Implementations must ensure that when `.clone_to_uninit()` returns normally rather than
228+
/// panicking, it always leaves `*dest` initialized as a valid value of type `Self`.
229+
///
230+
/// # Examples
231+
///
232+
// FIXME(#126799): when `Box::clone` allows use of `CloneToUninit`, rewrite these examples with it
233+
// since `Rc` is a distraction.
234+
///
235+
/// If you are defining a trait, you can add `CloneToUninit` as a supertrait to enable cloning of
236+
/// `dyn` values of your trait:
237+
///
238+
/// ```
239+
/// #![feature(clone_to_uninit)]
240+
/// use std::rc::Rc;
241+
///
242+
/// trait Foo: std::fmt::Debug + std::clone::CloneToUninit {
243+
/// fn modify(&mut self);
244+
/// fn value(&self) -> i32;
245+
/// }
246+
///
247+
/// impl Foo for i32 {
248+
/// fn modify(&mut self) {
249+
/// *self *= 10;
250+
/// }
251+
/// fn value(&self) -> i32 {
252+
/// *self
253+
/// }
254+
/// }
255+
///
256+
/// let first: Rc<dyn Foo> = Rc::new(1234);
257+
///
258+
/// let mut second = first.clone();
259+
/// Rc::make_mut(&mut second).modify(); // make_mut() will call clone_to_uninit()
260+
///
261+
/// assert_eq!(first.value(), 1234);
262+
/// assert_eq!(second.value(), 12340);
263+
/// ```
264+
///
265+
/// The following is an example of implementing `CloneToUninit` for a custom DST.
266+
/// (It is essentially a limited form of what `derive(CloneToUninit)` would do,
267+
/// if such a derive macro existed.)
222268
///
223-
/// # See also
269+
/// ```
270+
/// #![feature(clone_to_uninit)]
271+
/// use std::clone::CloneToUninit;
272+
/// use std::mem::offset_of;
273+
/// use std::rc::Rc;
274+
///
275+
/// #[derive(PartialEq)]
276+
/// struct MyDst<T: ?Sized> {
277+
/// flag: bool,
278+
/// contents: T,
279+
/// }
224280
///
225-
/// * [`Clone::clone_from`] is a safe function which may be used instead when `Self` is a [`Sized`]
281+
/// unsafe impl<T: ?Sized + CloneToUninit> CloneToUninit for MyDst<T> {
282+
/// unsafe fn clone_to_uninit(&self, dest: *mut u8) {
283+
/// // The offset of `self.contents` is dynamic because it depends on the alignment of T
284+
/// // which can be dynamic (if `T = dyn SomeTrait`). Therefore, we have to obtain it
285+
/// // dynamically by examining `self`, rather than using `offset_of!`.
286+
/// let offset_of_contents =
287+
/// (&raw const self.contents).byte_offset_from_unsigned(&raw const *self);
288+
///
289+
/// // Since `flag` implements `Copy`, we can just copy it.
290+
/// // We use `pointer::write()` instead of assignment because the destination must be
291+
/// // assumed to be uninitialized, whereas an assignment assumes it is initialized.
292+
/// dest.add(offset_of!(Self, flag)).cast::<bool>().write(self.flag);
293+
///
294+
/// // Note: if `flag` owned any resources (i.e. had a `Drop` implementation), then we
295+
/// // must prepare to drop it in case `self.contents.clone_to_uninit()` panics.
296+
/// // In this simple case, where we have exactly one field for which `mem::needs_drop()`
297+
/// // might be true (`contents`), we don’t need to care about cleanup or ordering.
298+
/// self.contents.clone_to_uninit(dest.add(offset_of_contents));
299+
///
300+
/// // All fields of the struct have been initialized, therefore the struct is initialized,
301+
/// // and we have satisfied our `unsafe impl CloneToUninit` obligations.
302+
/// }
303+
/// }
304+
///
305+
/// fn main() {
306+
/// // Construct MyDst<[u8; 4]>, then coerce to MyDst<[u8]>.
307+
/// let first: Rc<MyDst<[u8]>> = Rc::new(MyDst {
308+
/// flag: true,
309+
/// contents: [1, 2, 3, 4],
310+
/// });
311+
///
312+
/// let mut second = first.clone();
313+
/// // make_mut() will call clone_to_uninit().
314+
/// for elem in Rc::make_mut(&mut second).contents.iter_mut() {
315+
/// *elem *= 10;
316+
/// }
317+
///
318+
/// assert_eq!(first.contents, [1, 2, 3, 4]);
319+
/// assert_eq!(second.contents, [10, 20, 30, 40]);
320+
/// }
321+
/// ```
322+
///
323+
/// # See Also
324+
///
325+
/// * [`Clone::clone_from`] is a safe function which may be used instead when [`Self: Sized`](Sized)
226326
/// and the destination is already initialized; it may be able to reuse allocations owned by
227-
/// the destination.
327+
/// the destination, whereas `clone_to_uninit` cannot, since its destination is assumed to be
328+
/// uninitialized.
228329
/// * [`ToOwned`], which allocates a new destination container.
229330
///
230331
/// [`ToOwned`]: ../../std/borrow/trait.ToOwned.html
332+
/// [DST]: https://doc.rust-lang.org/reference/dynamically-sized-types.html
333+
/// [trait object]: https://doc.rust-lang.org/reference/types/trait-object.html
231334
#[unstable(feature = "clone_to_uninit", issue = "126799")]
232335
pub unsafe trait CloneToUninit {
233-
/// Performs copy-assignment from `self` to `dst`.
336+
/// Performs copy-assignment from `self` to `dest`.
234337
///
235-
/// This is analogous to `std::ptr::write(dst.cast(), self.clone())`,
236-
/// except that `self` may be a dynamically-sized type ([`!Sized`](Sized)).
338+
/// This is analogous to `std::ptr::write(dest.cast(), self.clone())`,
339+
/// except that `Self` may be a dynamically-sized type ([`!Sized`](Sized)).
237340
///
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
341+
/// Before this function is called, `dest` may point to uninitialized memory.
342+
/// After this function is called, `dest` will point to initialized memory; it will be
240343
/// sound to create a `&Self` reference from the pointer with the [pointer metadata]
241344
/// from `self`.
242345
///
243346
/// # Safety
244347
///
245348
/// Behavior is undefined if any of the following conditions are violated:
246349
///
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)`.
350+
/// * `dest` must be [valid] for writes for `std::mem::size_of_val(self)` bytes.
351+
/// * `dest` must be properly aligned to `std::mem::align_of_val(self)`.
249352
///
250353
/// [valid]: crate::ptr#safety
251354
/// [pointer metadata]: crate::ptr::metadata()
@@ -254,60 +357,60 @@ pub unsafe trait CloneToUninit {
254357
///
255358
/// This function may panic. (For example, it might panic if memory allocation for a clone
256359
/// of a value owned by `self` fails.)
257-
/// If the call panics, then `*dst` should be treated as uninitialized memory; it must not be
360+
/// If the call panics, then `*dest` should be treated as uninitialized memory; it must not be
258361
/// read or dropped, because even if it was previously valid, it may have been partially
259362
/// overwritten.
260363
///
261-
/// The caller may also need to take care to deallocate the allocation pointed to by `dst`,
364+
/// The caller may also need to take care to deallocate the allocation pointed to by `dest`,
262365
/// if applicable, to avoid a memory leak, and may need to take other precautions to ensure
263366
/// soundness in the presence of unwinding.
264367
///
265368
/// Implementors should avoid leaking values by, upon unwinding, dropping all component values
266369
/// that might have already been created. (For example, if a `[Foo]` of length 3 is being
267370
/// cloned, and the second of the three calls to `Foo::clone()` unwinds, then the first `Foo`
268371
/// cloned should be dropped.)
269-
unsafe fn clone_to_uninit(&self, dst: *mut u8);
372+
unsafe fn clone_to_uninit(&self, dest: *mut u8);
270373
}
271374

272375
#[unstable(feature = "clone_to_uninit", issue = "126799")]
273376
unsafe impl<T: Clone> CloneToUninit for T {
274377
#[inline]
275-
unsafe fn clone_to_uninit(&self, dst: *mut u8) {
378+
unsafe fn clone_to_uninit(&self, dest: *mut u8) {
276379
// SAFETY: we're calling a specialization with the same contract
277-
unsafe { <T as self::uninit::CopySpec>::clone_one(self, dst.cast::<T>()) }
380+
unsafe { <T as self::uninit::CopySpec>::clone_one(self, dest.cast::<T>()) }
278381
}
279382
}
280383

281384
#[unstable(feature = "clone_to_uninit", issue = "126799")]
282385
unsafe impl<T: Clone> CloneToUninit for [T] {
283386
#[inline]
284387
#[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);
388+
unsafe fn clone_to_uninit(&self, dest: *mut u8) {
389+
let dest: *mut [T] = dest.with_metadata_of(self);
287390
// SAFETY: we're calling a specialization with the same contract
288-
unsafe { <T as self::uninit::CopySpec>::clone_slice(self, dst) }
391+
unsafe { <T as self::uninit::CopySpec>::clone_slice(self, dest) }
289392
}
290393
}
291394

292395
#[unstable(feature = "clone_to_uninit", issue = "126799")]
293396
unsafe impl CloneToUninit for str {
294397
#[inline]
295398
#[cfg_attr(debug_assertions, track_caller)]
296-
unsafe fn clone_to_uninit(&self, dst: *mut u8) {
399+
unsafe fn clone_to_uninit(&self, dest: *mut u8) {
297400
// SAFETY: str is just a [u8] with UTF-8 invariant
298-
unsafe { self.as_bytes().clone_to_uninit(dst) }
401+
unsafe { self.as_bytes().clone_to_uninit(dest) }
299402
}
300403
}
301404

302405
#[unstable(feature = "clone_to_uninit", issue = "126799")]
303406
unsafe impl CloneToUninit for crate::ffi::CStr {
304407
#[cfg_attr(debug_assertions, track_caller)]
305-
unsafe fn clone_to_uninit(&self, dst: *mut u8) {
408+
unsafe fn clone_to_uninit(&self, dest: *mut u8) {
306409
// SAFETY: For now, CStr is just a #[repr(trasnsparent)] [c_char] with some invariants.
307410
// And we can cast [c_char] to [u8] on all supported platforms (see: to_bytes_with_nul).
308411
// The pointer metadata properly preserves the length (so NUL is also copied).
309412
// See: `cstr_metadata_is_length_with_nul` in tests.
310-
unsafe { self.to_bytes_with_nul().clone_to_uninit(dst) }
413+
unsafe { self.to_bytes_with_nul().clone_to_uninit(dest) }
311414
}
312415
}
313416

0 commit comments

Comments
 (0)
Failed to load comments.