Re: [RFC PATCH] rust: alloc: pass `old_layout` to `Allocator`

From: Gary Guo
Date: Mon Sep 23 2024 - 12:13:42 EST


On Mon, 23 Sep 2024 15:56:28 +0200
Alice Ryhl <aliceryhl@xxxxxxxxxx> wrote:

> On Sat, Sep 21, 2024 at 5:33 PM Danilo Krummrich <dakr@xxxxxxxxxx> wrote:
> > @@ -84,11 +92,18 @@ unsafe fn call(
> > &self,
> > ptr: Option<NonNull<u8>>,
> > layout: Layout,
> > + old_layout: Layout,
> > flags: Flags,
> > ) -> Result<NonNull<[u8]>, AllocError> {
> > let size = aligned_size(layout);
> > let ptr = match ptr {
> > - Some(ptr) => ptr.as_ptr(),
> > + Some(ptr) => {
> > + if old_layout.size() == 0 {
> > + ptr::null()
> > + } else {
> > + ptr.as_ptr()
> > + }
> > + }
>
> This is making Allocator work with zero-sized types, which deviates
> from std. We should not do that without a reason. What is the reason?
>
> Alice

As Benno said, this makes the API closer to Rust `allocator_api`
Allocator trait as opposed to deviation.

There's one benefit of doing this (discussed with Danilo off-list),
which is it removes ZST special casing from caller. This RFC patch
simplifies `Box` handling, and if we add this line to the safety doc

`ptr` does not need to be a pointer returned by this
allocator if the layout is zero-sized.

then the `Vec` can also be simplified, removing all logics handling ZST
specially, except for `Vec::new()` which it forges a well-aligned
dangling pointer from nowhere.

Best,
Gary