Re: [PATCH v2 2/3] rust: alloc: add Vec::resize method
From: Benno Lossin
Date: Wed Mar 19 2025 - 10:58:43 EST
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).
---
Cheers,
Benno