On Tue, Nov 19, 2024 at 1:06 PM Abdiel Janulgue <abdiel.janulgue@xxxxxxxxx> wrote: > > > On 19/11/2024 13:45, Alice Ryhl wrote: > >> + pub fn alloc_page(flags: Flags) -> Result<ARef<Self>, AllocError> { > >> // SAFETY: Depending on the value of `gfp_flags`, this call may sleep. Other than that, it > >> // is always safe to call this method. > >> let page = unsafe { bindings::alloc_pages(flags.as_raw(), 0) }; > >> - let page = NonNull::new(page).ok_or(AllocError)?; > >> - // INVARIANT: We just successfully allocated a page, so we now have ownership of the newly > >> - // allocated page. We transfer that ownership to the new `Page` object. > >> - Ok(Self { page }) > >> + if page.is_null() { > >> + return Err(AllocError); > >> + } > >> + // CAST: Self` is a `repr(transparent)` wrapper around `bindings::page`. > >> + let ptr = page.cast::<Self>(); > >> + // INVARIANT: We just successfully allocated a page, ptr points to the new `Page` object. > >> + // SAFETY: According to invariant above ptr is valid. > >> + Ok(unsafe { ARef::from_raw(NonNull::new_unchecked(ptr)) }) > > > > Why did you change the null check? You should be able to avoid > > changing anything but the last line. > > Changing only the line, it complains: > > 86 | Ok(unsafe { ARef::from_raw(page) }) > | -------------- ^^^^ expected `NonNull<Page>`, > found `NonNull<page>` > > Unless this is what you mean? > > let page = unsafe { bindings::alloc_pages(flags.as_raw(), 0) }; > let page = page.cast::<Self>(); > let page = NonNull::new(page).ok_or(AllocError)?; > Ok(unsafe { ARef::from_raw(page) }) You can put the cast here: let page = unsafe { bindings::alloc_pages(flags.as_raw(), 0) }; let page = NonNull::new(page).ok_or(AllocError)?; Ok(unsafe { ARef::from_raw(page.cast()) }) > But what if alloc_pages returns null in the place? Would that be a valid > cast still? The cast is correct both before and after the null check. The above code returns Err(AllocError) when the pointer is null. Alice