Make Vec::set_len enforce the len <= cap invariant

That's no different from ptr::read or <[T]>::get_unchecked. This kind of thing is exactly what unsafe is there for. Even v.set_len(v.capacity()) will trivially leak information.

Why do you think they'd be more successful at avoiding unsound code when they have to write all of it, rather than just call set_len correctly?

Just because you run panic-abort, that doesn't mean libraries should be written in ways that don't work with panic-unwind. I consider libraries that aren't panic-safe a much bigger problem than an an unsafe method.

3 Likes

I sat down with someone familiar with this sort of problem in C++ (though not a Rust person) and after staring at a couple of examples we’ve concluded we’ve been thinking about this the wrong way this whole time. It sounds like this isn’t a solution for the problem I set out to solve, specifically because of your points about ptr::read. I’m not sure that I buy the optimization worry in the examples I’m thinking of, so I wonder if this is still a useful change… I expect I need to look at compiler output to make a more educated guess.

All that said, the documentation should be a bit more clear as to how dangerous this method is, and maybe get rid of some of the sillier examples.

I doubt there is a good solution to the problem I want to solve, unfortunately.

I'm absolutely in favour of some more-realistic examples here. Maybe one that passes the buffer over FFI and then set_lens to number of items that external code claims to have written?

1 Like

++ to that. Perhaps also a # Safety section, which is oddly missing from the documentation? I think something to make it clear that improper use can lead to reading uninit or to leaked resources (due to failed RAII) is a good idea.

Honestly, I’m curious how much the unsafe wg cares about trying to run around and add better warnings to unsafe functions in std.

2 Likes

Docs updated, including a safety section:

And I’m trying to add a debug_assert!:

14 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.