From 105de5e7e9df5e56edbfb0c3eedd8cc4b0294f96 Mon Sep 17 00:00:00 2001 From: Mahdi Ali-Raihan Date: Sun, 15 Nov 2026 15:21:31 -0500 Subject: [PATCH 1/2] Revert #150067 due to perf regression Revert due to performance regression in String::retain - The changes introduced by #150067 can be re-landed when we remove the memmove instruction (ptr::copy) it adds in String::retain. This reverts the implementation of String::retain from commit 6a24a6e47cbac27e0f98c17e98597cff19b9f536 to how it was previously implemented as in 8aef23ab9b9db11fef7791cd52492741ddc73b50 --- library/alloc/src/string.rs | 86 ++++++++++++++++--------------------- 1 file changed, 37 insertions(+), 49 deletions(-) diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index c8336c4f43823..4f59e88657b3f 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, hint, ptr, slice}; +use core::{fmt, hash, ptr, slice}; #[cfg(not(no_global_oom_handling))] use crate::alloc::Allocator; @@ -1697,66 +1697,54 @@ impl String { where F: FnMut(char) -> bool, { - let len = self.len(); - if len == 0 { - // Explicit check results in better optimization - return; - } - - struct PanicGuard<'a> { + struct SetLenOnDrop<'a> { s: &'a mut String, - write: usize, + idx: usize, + del_bytes: usize, } - impl Drop for PanicGuard<'_> { + impl<'a> Drop for SetLenOnDrop<'a> { fn drop(&mut self) { - debug_assert!(self.write <= self.s.len()); - debug_assert!(str::from_utf8(&self.s.vec[..self.write]).is_ok()); + let new_len = self.idx - self.del_bytes; + debug_assert!(new_len <= self.s.len()); // SAFETY: Restore the string length to the number of bytes written so far. - unsafe { self.s.vec.set_len(self.write) } + unsafe { self.s.vec.set_len(new_len) }; } } - // 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: 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 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() }; 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`. - unsafe { - let ptr = g.s.vec.as_mut_ptr(); - ptr::copy(ptr.add(read), ptr.add(g.write), ch_len); - } - g.write += ch_len; + + 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(), + ) + }); } - read += ch_len; + + // Point idx to the next char + guard.idx += ch_len; } - // All bytes processed; commit the final length by dropping the guard. - drop(g); + drop(guard); } /// Inserts a character into this `String` at byte position `idx`. From e2c014f4842c6887d457680b35dcca25ea18cea4 Mon Sep 17 00:00:00 2001 From: Talha Demir Date: Sun, 15 Nov 2026 15:32:27 -0500 Subject: [PATCH 2/2] Re-introduce safety hygiene changes made in String::retain by #163624 This re-introduces the change made by #163624 where we slice the byte vector before converting to str, avoiding whole-buffer conversion when compaction may leave invalid UTF-8. --- library/alloc/src/string.rs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index 4f59e88657b3f..71f8fe8309b34 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -1716,11 +1716,18 @@ impl String { 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() }; + // 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(guard.s.vec.get_unchecked(guard.idx..len)); + tail.chars().next().unwrap_unchecked() + }; let ch_len = ch.len_utf8(); if !f(ch) {