Re: [PATCH] rust: alloc: use `spare_capacity_mut` to reduce unsafe

Alice Ryhl
2025-03-18T09:23:03Z

On Mon, Mar 17, 2025 at 01:55:18PM -0400, Tamir Duberstein wrote:
> > >
> > > fn dec_len(&mut self, count: usize) -> &mut [T] {
> > > self.len = self.len.saturating_sub(count);
> > >
> > > // Potentially broken, since maybe `count > self.len`, hence need an
> > > // additional check.
> > > unsafe { slice::from_raw_parts_mut(self.as_mut_ptr().add(self.len), count) }
> > > }
> >
> > Ah sorry, in my mental model the function returned `()`. Do we need the
> > return value?
>
> The return value is the whole genesis of `dec_len`, we want to return
> something to let the caller know they need to drop or copy the memory.

Hold on .. it returns &mut [T]. You're usually not allowed to take
ownership of or drop values behind a mutable reference.

Alice