This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/xSUNiMODx on 2023-08-10 18:04:40.


Could someone clarify to me how the implementation of Vec::retain_mut works? Source code is here.

From what I understand we are doing two passes over the vector, but only the second pass actually does the moving around.

It looks like the first process_loop call only gets rid of 1 element and makes a “hole” there. We then move on to the second process_loop call and that uses the hole we made to copy whatever the next non-removable element is into the first available hole.

One point of confusion is why the comment here makes sense: // SAFETY: deleted_cnt > 0, so the hole slot must not overlap with current element. Why are we guaranteed that deleted_cnt > 0?

After all the moving around we call drop on the guard. The comment says that the whole ptr::copy gets optimized away by LLVM, which I don’t understand, since deleted_cnt is likely to be greater than 0. I do understand the copying of the unchecked elements into the holes we just made though.

A final question is why we need two calls to process_loop over a const bool generic, since they seem pretty different.