@@ -209,43 +209,150 @@ 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+ /// #![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+ /// }
224281///
225- /// * [`Clone::clone_from`] is a safe function which may be used instead when `Self` is a [`Sized`]
282+ /// unsafe impl<T: ?Sized + CloneToUninit> CloneToUninit for MyDst<T> {
283+ /// unsafe fn clone_to_uninit(&self, dest: *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 must be
295+ /// // assumed to be uninitialized, whereas an assignment assumes it is initialized.
296+ /// dest.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(dest.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
328+ ///
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" ) ]
232339pub unsafe trait CloneToUninit {
233- /// Performs copy-assignment from `self` to `dst `.
340+ /// Performs copy-assignment from `self` to `dest `.
234341 ///
235- /// This is analogous to `std::ptr::write(dst .cast(), self.clone())`,
236- /// except that `self ` may be a dynamically-sized type ([`!Sized`](Sized)).
342+ /// This is analogous to `std::ptr::write(dest .cast(), self.clone())`,
343+ /// except that `Self ` may be a dynamically-sized type ([`!Sized`](Sized)).
237344 ///
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
345+ /// Before this function is called, `dest ` may point to uninitialized memory.
346+ /// After this function is called, `dest ` will point to initialized memory; it will be
240347 /// sound to create a `&Self` reference from the pointer with the [pointer metadata]
241348 /// from `self`.
242349 ///
243350 /// # Safety
244351 ///
245352 /// Behavior is undefined if any of the following conditions are violated:
246353 ///
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)`.
354+ /// * `dest ` must be [valid] for writes for `std::mem::size_of_val(self)` bytes.
355+ /// * `dest ` must be properly aligned to `std::mem::align_of_val(self)`.
249356 ///
250357 /// [valid]: crate::ptr#safety
251358 /// [pointer metadata]: crate::ptr::metadata()
@@ -254,60 +361,60 @@ pub unsafe trait CloneToUninit {
254361 ///
255362 /// This function may panic. (For example, it might panic if memory allocation for a clone
256363 /// of a value owned by `self` fails.)
257- /// If the call panics, then `*dst ` should be treated as uninitialized memory; it must not be
364+ /// If the call panics, then `*dest ` should be treated as uninitialized memory; it must not be
258365 /// read or dropped, because even if it was previously valid, it may have been partially
259366 /// overwritten.
260367 ///
261- /// The caller may also need to take care to deallocate the allocation pointed to by `dst `,
368+ /// The caller may also need to take care to deallocate the allocation pointed to by `dest `,
262369 /// if applicable, to avoid a memory leak, and may need to take other precautions to ensure
263370 /// soundness in the presence of unwinding.
264371 ///
265372 /// Implementors should avoid leaking values by, upon unwinding, dropping all component values
266373 /// that might have already been created. (For example, if a `[Foo]` of length 3 is being
267374 /// cloned, and the second of the three calls to `Foo::clone()` unwinds, then the first `Foo`
268375 /// cloned should be dropped.)
269- unsafe fn clone_to_uninit ( & self , dst : * mut u8 ) ;
376+ unsafe fn clone_to_uninit ( & self , dest : * mut u8 ) ;
270377}
271378
272379#[ unstable( feature = "clone_to_uninit" , issue = "126799" ) ]
273380unsafe impl < T : Clone > CloneToUninit for T {
274381 #[ inline]
275- unsafe fn clone_to_uninit ( & self , dst : * mut u8 ) {
382+ unsafe fn clone_to_uninit ( & self , dest : * mut u8 ) {
276383 // SAFETY: we're calling a specialization with the same contract
277- unsafe { <T as self :: uninit:: CopySpec >:: clone_one ( self , dst . cast :: < T > ( ) ) }
384+ unsafe { <T as self :: uninit:: CopySpec >:: clone_one ( self , dest . cast :: < T > ( ) ) }
278385 }
279386}
280387
281388#[ unstable( feature = "clone_to_uninit" , issue = "126799" ) ]
282389unsafe impl < T : Clone > CloneToUninit for [ T ] {
283390 #[ inline]
284391 #[ 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 ) ;
392+ unsafe fn clone_to_uninit ( & self , dest : * mut u8 ) {
393+ let dest : * mut [ T ] = dest . with_metadata_of ( self ) ;
287394 // SAFETY: we're calling a specialization with the same contract
288- unsafe { <T as self :: uninit:: CopySpec >:: clone_slice ( self , dst ) }
395+ unsafe { <T as self :: uninit:: CopySpec >:: clone_slice ( self , dest ) }
289396 }
290397}
291398
292399#[ unstable( feature = "clone_to_uninit" , issue = "126799" ) ]
293400unsafe impl CloneToUninit for str {
294401 #[ inline]
295402 #[ cfg_attr( debug_assertions, track_caller) ]
296- unsafe fn clone_to_uninit ( & self , dst : * mut u8 ) {
403+ unsafe fn clone_to_uninit ( & self , dest : * mut u8 ) {
297404 // SAFETY: str is just a [u8] with UTF-8 invariant
298- unsafe { self . as_bytes ( ) . clone_to_uninit ( dst ) }
405+ unsafe { self . as_bytes ( ) . clone_to_uninit ( dest ) }
299406 }
300407}
301408
302409#[ unstable( feature = "clone_to_uninit" , issue = "126799" ) ]
303410unsafe impl CloneToUninit for crate :: ffi:: CStr {
304411 #[ cfg_attr( debug_assertions, track_caller) ]
305- unsafe fn clone_to_uninit ( & self , dst : * mut u8 ) {
412+ unsafe fn clone_to_uninit ( & self , dest : * mut u8 ) {
306413 // SAFETY: For now, CStr is just a #[repr(trasnsparent)] [c_char] with some invariants.
307414 // And we can cast [c_char] to [u8] on all supported platforms (see: to_bytes_with_nul).
308415 // The pointer metadata properly preserves the length (so NUL is also copied).
309416 // See: `cstr_metadata_is_length_with_nul` in tests.
310- unsafe { self . to_bytes_with_nul ( ) . clone_to_uninit ( dst ) }
417+ unsafe { self . to_bytes_with_nul ( ) . clone_to_uninit ( dest ) }
311418 }
312419}
313420
0 commit comments