Re: [PATCH 07/10] rust: alloc: update `VecExt` to take allocation flags

From: Boqun Feng
Date: Mon Mar 25 2024 - 16:46:27 EST


On Mon, Mar 25, 2024 at 04:54:15PM -0300, Wedson Almeida Filho wrote:
[...]
> + fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> {
> + <Self as VecExt<_>>::reserve(self, 1, flags)?;
> + let (ptr, len, cap) = destructure(self);
> + // SAFETY: ptr is valid for `cap` elements. And `cap` is greater (by at least 1) than
> + // `len` because of the call to `reserve` above. So the pointer after offsetting by `len`
> + // elements is valid for write.
> + unsafe { ptr.wrapping_add(len).write(v) };
> +
> + // SAFETY: The only difference from the values returned by `destructure` is that `length`
> + // is incremented by 1, which is fine because we have just initialised the element at
> + // offset `length`.
> + unsafe { rebuild(self, ptr, len + 1, cap) };

probably use spare_capacity_mut() here to avoid `destructure` and
`rebuild`?

https://doc.rust-lang.org/std/vec/struct.Vec.html#method.spare_capacity_mut

// .. after reserve succeed.
// there must be room for adding one more.
self.spare_capacity_mut()[0].write(v);
// or unsafe { self.spare_capacity_mut().as_mut_ptr().cast().write(v); }

unsafe {
self.set_len(self.len() + 1);
}

Thoughts?

Regards,
Boqun

> Ok(())
> }
>
[...]