From fbcebef5d98823dbc4db675a1e2860a3df81e96a Mon Sep 17 00:00:00 2001 From: Khashayar Fereidani Date: Mon, 16 Nov 2026 21:07:40 -0500 Subject: [PATCH 1/3] Improve and optimize `String::retain` implementation --- library/alloc/src/string.rs | 77 +++++++++++++++++++------------------ 1 file changed, 40 insertions(+), 37 deletions(-) diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index 1e3861b3cb933..a89b6930b42e7 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -58,7 +58,7 @@ use core::ops::Add; use core::ops::AddAssign; use core::ops::{self, Range, RangeBounds}; use core::str::pattern::{Pattern, Utf8Pattern}; -use core::{fmt, hash, ptr, slice}; +use core::{fmt, hash, hint, ptr, slice}; #[cfg(not(no_global_oom_handling))] use crate::alloc::Allocator; @@ -1697,54 +1697,57 @@ impl String { where F: FnMut(char) -> bool, { - struct SetLenOnDrop<'a> { + let len = self.len(); + if len == 0 { + // Explicit check results in better optimization + return; + } + + struct PanicGuard<'a> { s: &'a mut String, - idx: usize, - del_bytes: usize, + write: usize, } - impl<'a> Drop for SetLenOnDrop<'a> { + impl Drop for PanicGuard<'_> { fn drop(&mut self) { - let new_len = self.idx - self.del_bytes; - debug_assert!(new_len <= self.s.len()); + debug_assert!(self.write <= self.s.len()); + debug_assert!(str::from_utf8(&self.s.vec[..self.write]).is_ok()); // SAFETY: Restore the string length to the number of bytes written so far. - unsafe { self.s.vec.set_len(new_len) }; + unsafe { self.s.vec.set_len(self.write) } } } - let len = self.len(); - let mut guard = SetLenOnDrop { s: self, idx: 0, del_bytes: 0 }; - - while guard.idx < len { - 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() }; + // Fast path: find the first character that should be removed or return early. + let mut chars = self.char_indices(); + let (mut read, write) = loop { + let Some((idx, ch)) = chars.next() else { return }; + if hint::unlikely(!f(ch)) { + break (idx + ch.len_utf8(), idx); + } + }; + drop(chars); + + // Slow path: at least one character is going to be removed. + let mut g = PanicGuard { s: self, write }; + while read < len { + // SAFETY: `read` is within bound because `read` < `len`, so taking + // a slice with `len` is safe. + let ch = unsafe { g.s.get_unchecked(read..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 { - // 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(), - ) - }); + if f(ch) { + // SAFETY: `read` is on a char boundary, as guaranteed above; `g.write` is + // within bounds because it is always behind `read`. + unsafe { + let ptr = g.s.vec.as_mut_ptr(); + ptr::copy(ptr.add(read), ptr.add(g.write), ch_len); + } + g.write += ch_len; } - - // Point idx to the next char - guard.idx += ch_len; + read += ch_len; } - drop(guard); + // All bytes processed; commit the final length by dropping the guard. + drop(g); } /// Inserts a character into this `String` at byte position `idx`. From 20c87946f97138d5354338f49eefdb59f24c337e Mon Sep 17 00:00:00 2001 From: Talha-Dmr Date: Mon, 16 Nov 2026 21:18:25 -0500 Subject: [PATCH 2/3] String::retain: convert only the untouched UTF-8 tail Slice the byte vector before converting to str, avoiding a whole-buffer conversion while compaction may leave invalid UTF-8. --- library/alloc/src/string.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index a89b6930b42e7..4e6255e996c5e 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -1730,9 +1730,18 @@ impl String { // Slow path: at least one character is going to be removed. let mut g = PanicGuard { s: self, write }; while read < len { - // SAFETY: `read` is within bound because `read` < `len`, so taking - // a slice with `len` is safe. - let ch = unsafe { g.s.get_unchecked(read..len).chars().next().unwrap_unchecked() }; + // SAFETY: Use `vec`: `String`'s deref includes `write..read`, + // which may be invalid UTF-8. The vector's length is still `len`; + // `read < len`, so `read..len` is in bounds and non-empty. + // At least one character was removed, so `write < read`. + // Copies end before the next `read`, preserving unread bytes. + // `read` starts after a `char_indices` character and advances by whole + // characters, so it stays on a char boundary. The original string was valid UTF-8, + // so the unchanged, non-empty tail is valid UTF-8 and `chars().next()` returns `Some`. + let ch = unsafe { + let tail = str::from_utf8_unchecked(g.s.vec.get_unchecked(read..len)); + tail.chars().next().unwrap_unchecked() + }; let ch_len = ch.len_utf8(); if f(ch) { // SAFETY: `read` is on a char boundary, as guaranteed above; `g.write` is From ef992ba451e322a634e8b7a9b06b51350079109b Mon Sep 17 00:00:00 2001 From: Mahdi Ali-Raihan Date: Mon, 16 Nov 2026 21:33:22 -0500 Subject: [PATCH 3/3] Use `char::encode_utf8_raw_unchecked` over `ptr::copy(...)` in `String::retain` Using `char::encode_utf8_raw_unchecked` significantly improves the performance (and fixes regression) of `String::retain` over using `ptr::copy(src, dst, ch_len)` --- library/alloc/src/string.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index 4e6255e996c5e..0fe418aaffde1 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -1745,10 +1745,10 @@ impl String { let ch_len = ch.len_utf8(); if f(ch) { // SAFETY: `read` is on a char boundary, as guaranteed above; `g.write` is - // within bounds because it is always behind `read`. + // is always behind `read`, so we should always have space to encode this + // character from g.write..g.write + ch_len. unsafe { - let ptr = g.s.vec.as_mut_ptr(); - ptr::copy(ptr.add(read), ptr.add(g.write), ch_len); + core::char::encode_utf8_raw_unchecked(ch as u32, g.s.as_mut_ptr().add(g.write)); } g.write += ch_len; }