Re: [PATCH v2 2/3] rust: alloc: add Vec::resize method

From: Tamir Duberstein
Date: Wed Mar 19 2025 - 11:59:53 EST


On Wed, Mar 19, 2025 at 10:34 AM Benno Lossin <benno.lossin@xxxxxxxxx> wrote:
>
> On Wed Mar 19, 2025 at 2:42 PM CET, Tamir Duberstein wrote:
> > On Tue, Mar 18, 2025 at 8:50 PM Benno Lossin <benno.lossin@xxxxxxxxx> wrote:
> >>
> >> On Tue Mar 18, 2025 at 9:12 PM CET, Tamir Duberstein wrote:
> >> > On Sun, Mar 16, 2025 at 7:17 AM Andrew Ballance
> >> > <andrewjballance@xxxxxxxxx> wrote:
> >> >> + pub fn resize(&mut self, new_len: usize, value: T, flags: Flags) -> Result<(), AllocError> {
> >> >> + if new_len > self.len() {
> >> >> + self.extend_with(new_len - self.len(), value, flags)
> >> >> + } else {
> >> >> + self.truncate(new_len);
> >> >> + Ok(())
> >> >> + }
> >> >> + }
> >> >
> >> > You can avoid underflow checking in debug builds by using `checked_sub`:
> >>
> >> `checked_sub` doesn't only avoid underflow in debug builds, but rather
> >> in all builds. But the code below is a good suggestion.
> >
> > Yes, I know :)
> >
> > I included that language because the underflow check is likely
> > optimized away in release builds.
>
> If the function is inlined and the compiler can argue that `new_len >
> self.len()`, then yes, but otherwise I'm pretty sure it won't be
> optimized away.
>
> Also if it is optimized away, then the check was still "executed", so I
> find it a bit misleading to say "in debug builds" (making it sound like
> it wouldn't do it in non-debug builds).

If we're talking about the same thing then I think we're both wrong
and the correct phrasing would have been: "you can avoid underflow
checking when CONFIG_RUST_OVERFLOW_CHECKS=y by using `checked_sub`". I
was referring to the underflow check implicit in `new_len -
self.len()`.