stable-vec icon indicating copy to clipboard operation
stable-vec copied to clipboard

Rewrite `OptionCore` to avoid relying on unclear guarantees by `Vec`

Open LukasKalbertodt opened this issue 3 months ago • 0 comments

OptionCore uses a Vec<Option<T>>. It maintains that all elements between len and cap are initialized to None. Some methods rely on this. Unfortunately, I don't think there are super clear promises given by the docs of Vec. There is this part:

Vec will not specifically overwrite any data that is removed from it, but also won’t specifically preserve it. Its uninitialized memory is scratch space that it may use however it wants. It will generally just do whatever is most efficient or otherwise easy to implement. Do not rely on removed data to be erased for security purposes. Even if you drop a Vec, its buffer may simply be reused by another allocation. Even if you zero a Vec’s memory first, that might not actually happen because the optimizer does not consider this a side-effect that must be preserved. There is one case which we will not break, however: using unsafe code to write to the excess capacity, and then increasing the length to match, is always valid.

Plus the documentation of set_len with the example. But this just suggests that writing to uninitialized memory and then immediately calling set_len is fine. No promises that any other method calls would preserve the memory after len.

So I think I would probably feel more comfortable just not using Vec but writing custom allocation and all of that.

LukasKalbertodt avatar Mar 17 '24 13:03 LukasKalbertodt