Skip to content

Improve codegen of String::retain method #96605

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

Merged
merged 1 commit into from
May 21, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 17 additions & 8 deletions library/alloc/src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1466,19 +1466,28 @@ impl String {
let mut guard = SetLenOnDrop { s: self, idx: 0, del_bytes: 0 };

while guard.idx < len {
let ch = unsafe { guard.s.get_unchecked(guard.idx..len).chars().next().unwrap() };
let ch =
// SAFETY: `guard.idx` is positive-or-zero and less that len so the `get_unchecked`
// is in bound. `self` is valid UTF-8 like string and the returned slice starts at
// a unicode code point so the `Chars` always return one character.
unsafe { guard.s.get_unchecked(guard.idx..len).chars().next().unwrap_unchecked() };
let ch_len = ch.len_utf8();

if !f(ch) {
guard.del_bytes += ch_len;
} else if guard.del_bytes > 0 {
unsafe {
ptr::copy(
guard.s.vec.as_ptr().add(guard.idx),
guard.s.vec.as_mut_ptr().add(guard.idx - guard.del_bytes),
ch_len,
);
}
// SAFETY: `guard.idx` is in bound and `guard.del_bytes` represent the number of
// bytes that are erased from the string so the resulting `guard.idx -
// guard.del_bytes` always represent a valid unicode code point.
//
// `guard.del_bytes` >= `ch.len_utf8()`, so taking a slice with `ch.len_utf8()` len
// is safe.
ch.encode_utf8(unsafe {
crate::slice::from_raw_parts_mut(
guard.s.as_mut_ptr().add(guard.idx - guard.del_bytes),
ch.len_utf8(),
)
});
}

// Point idx to the next char
Expand Down