Skip to content

Added range for vec.drain call #489

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from

Conversation

silyevsk
Copy link

Without a range, the length of vec after using the drainer is zero anyways, even without forgetting the drainer.

@ehuss
Copy link
Contributor

ehuss commented Apr 29, 2025

Sorry, I don't quite understand. My understanding is that this is illustrating what would happen if you had a naive implementation where you implemented the fixup in the Drain drop method. If that is the case, then the length of the Vec will be unchanged and indeed accessing vec[0] will be unsound.

The standard library's drain doesn't suffer from this because it does not take that naive approach, but instead prepares the Vec to be safe even if Drain is leaked.

I believe that is what this is trying to get across.

@silyevsk
Copy link
Author

silyevsk commented May 6, 2025

You are right. What I think ..3 can improve is that it will show the additional leaking that mem::forget(drainer) creates (in the actual implementation, not in the naive approach): if we comment out the mem::forget line, all works fine (there's 1 element left in the vec and it can be accessed), but with the mem::forget executed, the vec's length is zero, so the program will panic when trying to access vec[0] which shows that the last element (which was not related to the drainer) is leaked.

@traviscross
Copy link
Contributor

Thanks for the suggestion here. For the reasons that @ehuss described, we're going to close this out. The purpose of the example here is to motivate why the standard library's implementation of Vec::drain is both necessary and correct, so the code is meant to be read in the context of drain as implemented in the naive way described in the paragraphs leading up to the example, and the example is already OK in that context.

@traviscross traviscross closed this May 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants