Re: [PATCH v5 04/26] rust: alloc: implement `Allocator` for `Kmalloc`

Danilo Krummrich
2024-08-14T16:59:21Z

On Wed, Aug 14, 2024 at 04:21:38PM +0000, Benno Lossin wrote:
> On 12.08.24 20:22, Danilo Krummrich wrote:
> > + /// # Safety
> > + ///
> > + /// This method has the same safety requirements as `Allocator::realloc`.
>
> Please make this a link.

Sure.

>
> > + unsafe fn call(
> > + &self,
> > + ptr: Option<NonNull<u8>>,
> > + layout: Layout,
> > + flags: Flags,
> > + ) -> Result<NonNull<[u8]>, AllocError> {
> > + let size = aligned_size(layout);
> > + let ptr = match ptr {
> > + Some(ptr) => ptr.as_ptr(),
> > + None => ptr::null(),
> > + };
> > +
> > + // SAFETY: `ptr` is either NULL or valid by the safety requirements of this function.
> > + let raw_ptr = unsafe {
> > + // If `size == 0` and `ptr != NULL` the memory behind the pointer is freed.
> > + self.0(ptr.cast(), size, flags.0).cast()
> > + };
> > +
> > + let ptr = if size == 0 {
>
> Why do you do this check *after* calling `self.0`?

Because I need `raw_ptr` in the else case below.

>
> ---
> Cheers,
> Benno
>
> > + NonNull::dangling()
> > + } else {
> > + NonNull::new(raw_ptr).ok_or(AllocError)?
> > + };
> > +
> > + Ok(NonNull::slice_from_raw_parts(ptr, size))
> > + }
> > +}
>