@@ -262,43 +262,146 @@ pub struct AssertParamIsCopy<T: Copy + ?Sized> {
262
262
_field : crate :: marker:: PhantomData < T > ,
263
263
}
264
264
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.
266
266
///
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.
270
277
///
271
278
/// # Safety
272
279
///
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.)
275
321
///
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
+ /// }
277
333
///
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)
279
379
/// 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.
281
382
/// * [`ToOwned`], which allocates a new destination container.
282
383
///
283
384
/// [`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
284
387
#[ unstable( feature = "clone_to_uninit" , issue = "126799" ) ]
285
388
pub unsafe trait CloneToUninit {
286
- /// Performs copy-assignment from `self` to `dst `.
389
+ /// Performs copy-assignment from `self` to `dest `.
287
390
///
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)).
290
393
///
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
293
396
/// sound to create a `&Self` reference from the pointer with the [pointer metadata]
294
397
/// from `self`.
295
398
///
296
399
/// # Safety
297
400
///
298
401
/// Behavior is undefined if any of the following conditions are violated:
299
402
///
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)`.
302
405
///
303
406
/// [valid]: crate::ptr#safety
304
407
/// [pointer metadata]: crate::ptr::metadata()
@@ -307,60 +410,60 @@ pub unsafe trait CloneToUninit {
307
410
///
308
411
/// This function may panic. (For example, it might panic if memory allocation for a clone
309
412
/// 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
311
414
/// read or dropped, because even if it was previously valid, it may have been partially
312
415
/// overwritten.
313
416
///
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 `,
315
418
/// if applicable, to avoid a memory leak, and may need to take other precautions to ensure
316
419
/// soundness in the presence of unwinding.
317
420
///
318
421
/// Implementors should avoid leaking values by, upon unwinding, dropping all component values
319
422
/// that might have already been created. (For example, if a `[Foo]` of length 3 is being
320
423
/// cloned, and the second of the three calls to `Foo::clone()` unwinds, then the first `Foo`
321
424
/// cloned should be dropped.)
322
- unsafe fn clone_to_uninit ( & self , dst : * mut u8 ) ;
425
+ unsafe fn clone_to_uninit ( & self , dest : * mut u8 ) ;
323
426
}
324
427
325
428
#[ unstable( feature = "clone_to_uninit" , issue = "126799" ) ]
326
429
unsafe impl < T : Clone > CloneToUninit for T {
327
430
#[ inline]
328
- unsafe fn clone_to_uninit ( & self , dst : * mut u8 ) {
431
+ unsafe fn clone_to_uninit ( & self , dest : * mut u8 ) {
329
432
// 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 > ( ) ) }
331
434
}
332
435
}
333
436
334
437
#[ unstable( feature = "clone_to_uninit" , issue = "126799" ) ]
335
438
unsafe impl < T : Clone > CloneToUninit for [ T ] {
336
439
#[ inline]
337
440
#[ 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 ) ;
340
443
// 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 ) }
342
445
}
343
446
}
344
447
345
448
#[ unstable( feature = "clone_to_uninit" , issue = "126799" ) ]
346
449
unsafe impl CloneToUninit for str {
347
450
#[ inline]
348
451
#[ 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 ) {
350
453
// 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 ) }
352
455
}
353
456
}
354
457
355
458
#[ unstable( feature = "clone_to_uninit" , issue = "126799" ) ]
356
459
unsafe impl CloneToUninit for crate :: ffi:: CStr {
357
460
#[ 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 ) {
359
462
// SAFETY: For now, CStr is just a #[repr(trasnsparent)] [c_char] with some invariants.
360
463
// And we can cast [c_char] to [u8] on all supported platforms (see: to_bytes_with_nul).
361
464
// The pointer metadata properly preserves the length (so NUL is also copied).
362
465
// 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 ) }
364
467
}
365
468
}
366
469
0 commit comments