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 76b565f

Browse files
committedNov 14, 2024
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. * Various small corrections.
1 parent a4cedec commit 76b565f

File tree

1 file changed

+116
-9
lines changed

1 file changed

+116
-9
lines changed
 

‎library/core/src/clone.rs

+116-9
Original file line numberDiff line numberDiff line change
@@ -209,31 +209,138 @@ 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
227+
/// Implementations must ensure that when `.clone_to_uninit()` returns normally rather than
221228
/// panicking, it always leaves `*dst` initialized as a valid value of type `Self`.
222229
///
223-
/// # See also
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.)
268+
///
269+
/// ```
270+
/// #![feature(clone_to_uninit)]
271+
/// #![feature(ptr_sub_ptr)]
272+
/// use std::clone::CloneToUninit;
273+
/// use std::mem::offset_of;
274+
/// use std::rc::Rc;
275+
///
276+
/// #[derive(PartialEq)]
277+
/// struct MyDst<T: ?Sized> {
278+
/// flag: bool,
279+
/// contents: T,
280+
/// }
281+
///
282+
/// unsafe impl<T: ?Sized + CloneToUninit> CloneToUninit for MyDst<T> {
283+
/// unsafe fn clone_to_uninit(&self, dst: *mut u8) {
284+
/// let offset_of_flag = offset_of!(Self, flag);
285+
/// // The offset of `self.contents` is dynamic because it depends on the alignment of T
286+
/// // which can be dynamic (if `T = dyn SomeTrait`). Therefore, we have to obtain it
287+
/// // dynamically by examining `self`.
288+
/// let offset_of_contents =
289+
/// (&raw const self.contents)
290+
/// .cast::<u8>()
291+
/// .sub_ptr((&raw const *self).cast::<u8>());
292+
///
293+
/// // Since `flag` implements `Copy`, we can just copy it.
294+
/// // We use `pointer::write()` instead of assignment because the destination may be
295+
/// // uninitialized.
296+
/// dst.add(offset_of_flag).cast::<bool>().write(self.flag);
297+
///
298+
/// // Note: if `flag` owned any resources (i.e. had a `Drop` implementation), then we
299+
/// // must prepare to drop it in case `self.contents.clone_to_uninit()` panics.
300+
/// // In this simple case, where we have exactly one field for which `mem::needs_drop()`
301+
/// // might be true (`contents`), we don’t need to care about cleanup or ordering.
302+
/// self.contents.clone_to_uninit(dst.add(offset_of_contents));
303+
///
304+
/// // All fields of the struct have been initialized, therefore the struct is initialized,
305+
/// // and we have satisfied our `unsafe impl CloneToUninit` obligations.
306+
/// }
307+
/// }
308+
///
309+
/// fn main() {
310+
/// // Construct MyDst<[u8; 4]>, then coerce to MyDst<[u8]>.
311+
/// let first: Rc<MyDst<[u8]>> = Rc::new(MyDst {
312+
/// flag: true,
313+
/// contents: [1, 2, 3, 4],
314+
/// });
315+
///
316+
/// let mut second = first.clone();
317+
/// // make_mut() will call clone_to_uninit().
318+
/// for elem in Rc::make_mut(&mut second).contents.iter_mut() {
319+
/// *elem *= 10;
320+
/// }
321+
///
322+
/// assert_eq!(first.contents, [1, 2, 3, 4]);
323+
/// assert_eq!(second.contents, [10, 20, 30, 40]);
324+
/// }
325+
/// ```
326+
///
327+
/// # See Also
224328
///
225-
/// * [`Clone::clone_from`] is a safe function which may be used instead when `Self` is a [`Sized`]
329+
/// * [`Clone::clone_from`] is a safe function which may be used instead when [`Self: Sized`](Sized)
226330
/// and the destination is already initialized; it may be able to reuse allocations owned by
227-
/// the destination.
331+
/// the destination, whereas `clone_to_uninit` cannot, since its destination is assumed to be
332+
/// uninitialized.
228333
/// * [`ToOwned`], which allocates a new destination container.
229334
///
230335
/// [`ToOwned`]: ../../std/borrow/trait.ToOwned.html
336+
/// [DST]: https://doc.rust-lang.org/reference/dynamically-sized-types.html
337+
/// [trait object]: https://doc.rust-lang.org/reference/types/trait-object.html
231338
#[unstable(feature = "clone_to_uninit", issue = "126799")]
232339
pub unsafe trait CloneToUninit {
233340
/// Performs copy-assignment from `self` to `dst`.
234341
///
235342
/// This is analogous to `std::ptr::write(dst.cast(), self.clone())`,
236-
/// except that `self` may be a dynamically-sized type ([`!Sized`](Sized)).
343+
/// except that `Self` may be a dynamically-sized type ([`!Sized`](Sized)).
237344
///
238345
/// Before this function is called, `dst` may point to uninitialized memory.
239346
/// After this function is called, `dst` will point to initialized memory; it will be

0 commit comments

Comments
 (0)
Failed to load comments.