Re: [PATCH v3 1/2] rust: kernel: add `drop_contents` to `BoxExt`

Boqun Feng
2024-08-03T15:41:00Z

On Sat, Aug 03, 2024 at 03:32:06PM +0000, Benno Lossin wrote:
> On 03.08.24 17:11, Boqun Feng wrote:
> > On Sat, Aug 03, 2024 at 02:23:42PM +0000, Benno Lossin wrote:
> >> On 03.08.24 16:16, Benno Lossin wrote:
> >>> @@ -53,4 +69,12 @@ fn new_uninit(flags: Flags) -> Result<Box<MaybeUninit<T>>, AllocError> {
> >>> // zero-sized types, we use `NonNull::dangling`.
> >>> Ok(unsafe { Box::from_raw(ptr) })
> >>> }
> >>> +
> >>> + fn drop_contents(this: Self) -> Box<MaybeUninit<T>> {
> >>> + let ptr = Box::into_raw(this);
> >>> + // SAFETY: `ptr` is valid, because it came from `Box::into_raw`.
> >>> + unsafe { ptr::drop_in_place(ptr) };
> >>> + // SAFETY: `ptr` is valid, because it came from `Box::into_raw`.
> >>
> >> I just noticed that I missed another comment from Boqun here. Got
> >> confused with the two mails. I would replace the comment above with
> >>
> >> // CAST: `T` and `MaybeUninit<T>` have the same layout.
> >> let ptr = ptr.cast::<MaybeUninit<T>>();
> >> // SAFETY: `ptr` is valid for writes, because it came from `Box::into_raw` and it is valid for
> >> // reads, since the pointer came from `Box::into_raw` and the type is `MaybeUninit<T>`.
> >>
> >> Let me know if you want another version.
> >
> > Looks good to me, please do send an updated version.
> >
> > Although, I would expect the "CAST" comment already explains that if
> > `ptr` is a valid, then the casting result is also valid, i.e. we put
> > "CAST" comments on the casting that matters to safety. But that seems
> > not matching what you use CAST for?
>
> Well the pointer is no longer valid for reads, since the value has been
> dropped. Only through the cast, it becomes again read-valid.
>

Fair enough, the past Boqun who made that suggestion might also realise
this and that's why he brought this up ;-)

> CAST comments must justify why the layouts are the same. On that note,
> this comment might be better:
>
> // CAST: `MaybeUninit<T>` is a transparent wrapper of `T`.
>

Looks good to me.

Regards,
Boqun

> ---
> Cheers,
> Benno
>