Skip to content

Commit e5d337a

Browse files
committed
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. * Various small corrections.
1 parent a4cedec commit e5d337a

File tree

1 file changed

+109
-8
lines changed

1 file changed

+109
-8
lines changed

library/core/src/clone.rs

Lines changed: 109 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -209,31 +209,132 @@ 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].
217219
///
218220
/// # Safety
219221
///
220222
/// Implementations must ensure that when `.clone_to_uninit(dst)` returns normally rather than
221223
/// panicking, it always leaves `*dst` initialized as a valid value of type `Self`.
222224
///
223-
/// # See also
225+
/// # Examples
224226
///
225-
/// * [`Clone::clone_from`] is a safe function which may be used instead when `Self` is a [`Sized`]
227+
// FIXME(#126799): when `Box::clone` allows use of `CloneToUninit`, rewrite these examples with it
228+
// since `Rc` is a distraction.
229+
///
230+
/// Using `CloneToUninit` as a supertrait to enable cloning of `dyn` values:
231+
///
232+
/// ```
233+
/// #![feature(clone_to_uninit)]
234+
/// use std::rc::Rc;
235+
///
236+
/// trait Foo: std::fmt::Debug + std::clone::CloneToUninit {
237+
/// fn modify(&mut self);
238+
/// fn value(&self) -> i32;
239+
/// }
240+
///
241+
/// impl Foo for i32 {
242+
/// fn modify(&mut self) {
243+
/// *self *= 10;
244+
/// }
245+
/// fn value(&self) -> i32 {
246+
/// *self
247+
/// }
248+
/// }
249+
///
250+
/// let first: Rc<dyn Foo> = Rc::new(1234);
251+
///
252+
/// let mut second = first.clone();
253+
/// Rc::make_mut(&mut second).modify(); // make_mut() will call clone_to_uninit()
254+
///
255+
/// assert_eq!(first.value(), 1234);
256+
/// assert_eq!(second.value(), 12340);
257+
/// ```
258+
///
259+
/// The following is an example of implementing `CloneToUninit` for a custom DST.
260+
/// (It is essentially a limited form of what `derive(CloneToUninit)` would do,
261+
/// if such a derive macro existed.)
262+
///
263+
/// ```
264+
/// #![feature(clone_to_uninit)]
265+
/// #![feature(ptr_sub_ptr)]
266+
/// use std::clone::CloneToUninit;
267+
/// use std::mem::offset_of;
268+
/// use std::rc::Rc;
269+
///
270+
/// #[derive(PartialEq)]
271+
/// struct MyDst<T: ?Sized> {
272+
/// flag: bool,
273+
/// contents: T,
274+
/// }
275+
///
276+
/// unsafe impl<T: ?Sized + CloneToUninit> CloneToUninit for MyDst<T> {
277+
/// unsafe fn clone_to_uninit(&self, dst: *mut u8) {
278+
/// let offset_of_flag = offset_of!(Self, flag);
279+
/// // The offset of `self.contents` is dynamic because it depends on the alignment of T
280+
/// // which can be dynamic (if `T = dyn SomeTrait`). Therefore, we have to obtain it
281+
/// // dynamically by examining `self`.
282+
/// let offset_of_contents =
283+
/// (&raw const self.contents)
284+
/// .cast::<u8>()
285+
/// .sub_ptr((&raw const *self).cast::<u8>());
286+
///
287+
/// // Since `flag` implements `Copy`, we can just copy it.
288+
/// // We use `pointer::write()` instead of assignment because the destination may be
289+
/// // uninitialized.
290+
/// dst.add(offset_of_flag).cast::<bool>().write(self.flag);
291+
///
292+
/// // Note: if `flag` owned any resources (i.e. had a `Drop` implementation), then we
293+
/// // must prepare to drop it in case `self.contents.clone_to_uninit()` panics.
294+
/// // In this simple case, where we have exactly one field for which `mem::needs_drop()`
295+
/// // might be true (`contents`), we don’t need to care about cleanup or ordering.
296+
/// self.contents.clone_to_uninit(dst.add(offset_of_contents));
297+
///
298+
/// // All fields of the struct have been initialized, therefore the struct is initialized,
299+
/// // and we have satisfied our `unsafe impl CloneToUninit` obligations.
300+
/// }
301+
/// }
302+
///
303+
/// fn main() {
304+
/// // Construct MyDst<[u8; 4]>, then coerce to MyDst<[u8]>.
305+
/// let first: Rc<MyDst<[u8]>> = Rc::new(MyDst {
306+
/// flag: true,
307+
/// contents: [1, 2, 3, 4],
308+
/// });
309+
///
310+
/// let mut second = first.clone();
311+
/// // make_mut() will call clone_to_uninit().
312+
/// for elem in Rc::make_mut(&mut second).contents.iter_mut() {
313+
/// *elem *= 10;
314+
/// }
315+
///
316+
/// assert_eq!(first.contents, [1, 2, 3, 4]);
317+
/// assert_eq!(second.contents, [10, 20, 30, 40]);
318+
/// }
319+
/// ```
320+
///
321+
/// # See Also
322+
///
323+
/// * [`Clone::clone_from`] is a safe function which may be used instead when [`Self: Sized`](Sized)
226324
/// and the destination is already initialized; it may be able to reuse allocations owned by
227-
/// the destination.
325+
/// the destination, whereas `clone_to_uninit` cannot, since its destination is assumed to be
326+
/// uninitialized.
228327
/// * [`ToOwned`], which allocates a new destination container.
229328
///
230329
/// [`ToOwned`]: ../../std/borrow/trait.ToOwned.html
330+
/// [DST]: https://doc.rust-lang.org/reference/dynamically-sized-types.html
331+
/// [trait object]: https://doc.rust-lang.org/reference/types/trait-object.html
231332
#[unstable(feature = "clone_to_uninit", issue = "126799")]
232333
pub unsafe trait CloneToUninit {
233334
/// Performs copy-assignment from `self` to `dst`.
234335
///
235336
/// This is analogous to `std::ptr::write(dst.cast(), self.clone())`,
236-
/// except that `self` may be a dynamically-sized type ([`!Sized`](Sized)).
337+
/// except that `Self` may be a dynamically-sized type ([`!Sized`](Sized)).
237338
///
238339
/// Before this function is called, `dst` may point to uninitialized memory.
239340
/// After this function is called, `dst` will point to initialized memory; it will be

0 commit comments

Comments
 (0)