@@ -209,43 +209,150 @@ pub struct AssertParamIsCopy<T: Copy + ?Sized> {
209
209
_field : crate :: marker:: PhantomData < T > ,
210
210
}
211
211
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.
213
213
///
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.
217
224
///
218
225
/// # Safety
219
226
///
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.)
222
268
///
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
+ /// }
224
281
///
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)
226
330
/// 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.
228
333
/// * [`ToOwned`], which allocates a new destination container.
229
334
///
230
335
/// [`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
231
338
#[ unstable( feature = "clone_to_uninit" , issue = "126799" ) ]
232
339
pub unsafe trait CloneToUninit {
233
- /// Performs copy-assignment from `self` to `dst `.
340
+ /// Performs copy-assignment from `self` to `dest `.
234
341
///
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)).
237
344
///
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
240
347
/// sound to create a `&Self` reference from the pointer with the [pointer metadata]
241
348
/// from `self`.
242
349
///
243
350
/// # Safety
244
351
///
245
352
/// Behavior is undefined if any of the following conditions are violated:
246
353
///
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)`.
249
356
///
250
357
/// [valid]: crate::ptr#safety
251
358
/// [pointer metadata]: crate::ptr::metadata()
@@ -254,60 +361,60 @@ pub unsafe trait CloneToUninit {
254
361
///
255
362
/// This function may panic. (For example, it might panic if memory allocation for a clone
256
363
/// 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
258
365
/// read or dropped, because even if it was previously valid, it may have been partially
259
366
/// overwritten.
260
367
///
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 `,
262
369
/// if applicable, to avoid a memory leak, and may need to take other precautions to ensure
263
370
/// soundness in the presence of unwinding.
264
371
///
265
372
/// Implementors should avoid leaking values by, upon unwinding, dropping all component values
266
373
/// that might have already been created. (For example, if a `[Foo]` of length 3 is being
267
374
/// cloned, and the second of the three calls to `Foo::clone()` unwinds, then the first `Foo`
268
375
/// cloned should be dropped.)
269
- unsafe fn clone_to_uninit ( & self , dst : * mut u8 ) ;
376
+ unsafe fn clone_to_uninit ( & self , dest : * mut u8 ) ;
270
377
}
271
378
272
379
#[ unstable( feature = "clone_to_uninit" , issue = "126799" ) ]
273
380
unsafe impl < T : Clone > CloneToUninit for T {
274
381
#[ inline]
275
- unsafe fn clone_to_uninit ( & self , dst : * mut u8 ) {
382
+ unsafe fn clone_to_uninit ( & self , dest : * mut u8 ) {
276
383
// 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 > ( ) ) }
278
385
}
279
386
}
280
387
281
388
#[ unstable( feature = "clone_to_uninit" , issue = "126799" ) ]
282
389
unsafe impl < T : Clone > CloneToUninit for [ T ] {
283
390
#[ inline]
284
391
#[ 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 ) ;
287
394
// 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 ) }
289
396
}
290
397
}
291
398
292
399
#[ unstable( feature = "clone_to_uninit" , issue = "126799" ) ]
293
400
unsafe impl CloneToUninit for str {
294
401
#[ inline]
295
402
#[ 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 ) {
297
404
// 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 ) }
299
406
}
300
407
}
301
408
302
409
#[ unstable( feature = "clone_to_uninit" , issue = "126799" ) ]
303
410
unsafe impl CloneToUninit for crate :: ffi:: CStr {
304
411
#[ 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 ) {
306
413
// SAFETY: For now, CStr is just a #[repr(trasnsparent)] [c_char] with some invariants.
307
414
// And we can cast [c_char] to [u8] on all supported platforms (see: to_bytes_with_nul).
308
415
// The pointer metadata properly preserves the length (so NUL is also copied).
309
416
// 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 ) }
311
418
}
312
419
}
313
420
0 commit comments