upvote
I agree that this is the better design. Rust calls these Vec::reserve and Vec::reserve_exact

Zig calls the analagous methods ensureTotalCapacity and ensureTotalCapacityPrecise

It's worth mentioning that talk of "exact" and "precise" may be misleading because it probably makes sense to (and despite that word exact Vec does explicitly say it might) discern that the actual allocation was big enough for slightly more items and increase the capacity accordingly.

Right now, many (most?) allocators if asked for enough room to store 7 Doodads, each 7 bytes in length with one byte alignment (thus total 49 bytes), may give you 64 bytes because it was easier, but can't or won't tell you about that. Rust's GlobalAlloc can't do better, nor can C's malloc family. But Rust's (unstable) Allocator trait and many modern malloc-descendents can tell you hey, here are 64 bytes instead. With that fixed your growable array type should consider this, after all instead of 7 Doodads, 64 bytes is enough for 9 Doodads, so it's free capacity.

reply
Note that glibc does provide a malloc_usable_size to query the size of a malloc'd block; not standard though of course.

A problem with just directly exposing such is it makes precise sanitizing impossible, as you'd have to tolerate some out-of-intended-bounds reads/writes. (and making the sanitizer always give exact-size allocations would also be bad as that'd end up not testing code paths that may break when they're not)

reply