Re: [PATCH] rust: alloc: use `spare_capacity_mut` to reduce unsafe
From: Danilo Krummrich
Date: Tue Mar 18 2025 - 07:54:44 EST
On Tue, Mar 18, 2025 at 09:22:59AM +0000, Alice Ryhl wrote:
> 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.
I think it should be fine. dec_len(), by returning this slice, indicates to the
caller what's left behind in case no action is taken.
Subsequent operations are unsafe anyways and can easily justify their validity
by saying that they only take over, what otherwise would have been left behind.
Do I miss anything?