this post was submitted on 10 Aug 2023
1 points (100.0% liked)

The Rust Programming Language

1 readers
0 users here now

A place for all things related to the Rust programming language—an open-source systems language that emphasizes performance, reliability, and...

founded 1 year ago
MODERATORS
 
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.

no comments (yet)
sorted by: hot top controversial new old
there doesn't seem to be anything here