Skip to content
Open
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
86 changes: 49 additions & 37 deletions library/alloc/src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -1697,54 +1697,66 @@ 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: 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) {
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
// is always behind `read`, so we should always have space to encode this
// character from g.write..g.write + ch_len.
unsafe {
core::char::encode_utf8_raw_unchecked(ch as u32, g.s.as_mut_ptr().add(g.write));

@workingjubilee workingjubilee Nov 16, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now that I look at things properly since the revert is landed and we have more room to think about this, I believe the code that you suggested is very similar to the contents of encode_utf8_raw_unchecked, @fereidani.

View changes since the review

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I remember that I had benchmark this in the original PR and as it is recalculating the utf8 length once more it was slower,
Following is the strongest solution that I've found then:

                unsafe {
                    let src = ptr.add(read);
                    let dst = ptr.add(g.write);
                    match ch_len {
                        1 => ptr::copy(src, dst, 1),
                        2 => ptr::copy(src, dst, 2),
                        3 => ptr::copy(src, dst, 3),
                        _ => ptr::copy(src, dst, 4),
                    }
                }

We already have the ch_len available, there is no good reason to recalculate it.
I also remember that instruction count was smaller for the code above. But I'll suggest contributor to do their own benchmarks and instruction count comparisons with the current version of rust compiler.

@asder8215 asder8215 Nov 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@fereidani I tried out your suggestion in a separate benchmark file here on the same benchmark case. Running cargo bench --no-run and perf stat <benchmark executable> --bench gives me the following results (also can be found in this folder, where version 1 refers to char::encode_utf8_raw_unchecked change and version 2 refers to your change):

This is the char::encode_utf8_raw_unchecked results:

Optimized String Retain Benchmarks
                        time:   [24.037 µs 24.050 µs 24.064 µs]
                        change: [−0.1407% +0.2229% +0.4890%] (p = 0.18 > 0.05)
                        No change in performance detected.
Found 12 outliers among 100 measurements (12.00%)
  9 (9.00%) low mild
  2 (2.00%) high mild
  1 (1.00%) high severe


 Performance counter stats for './target/release/build/string_retain_bench/c2239f57c8c677a2/out/optimized_string_retain_bench-c2239f57c8c677a2 --bench':

                 0      context-switches:u               #      0.0 cs/sec  cs_per_second     
                 0      cpu-migrations:u                 #      0.0 migrations/sec  migrations_per_second
             6,221      page-faults:u                    #    404.3 faults/sec  page_faults_per_second
         15,386.38 msec task-clock:u                     #      nan CPUs  CPUs_utilized       
       190,798,614      branch-misses:u                  #      0.4 %  branch_miss_rate         (49.98%)
    53,941,263,358      branches:u                       #   3505.8 M/sec  branch_frequency     (50.07%)
    70,711,942,238      cpu-cycles:u                     #      4.6 GHz  cycles_frequency       (66.76%)
   222,588,101,890      instructions:u                   #      3.1 instructions  insn_per_cycle  (50.07%)
     1,572,526,614      stalled-cycles-frontend:u        #     0.02 frontend_cycles_idle        (49.97%)

       8.640385245 seconds time elapsed

      15.110534000 seconds user
       0.075471000 seconds sys

This is the ptr::copy(...) suggestion results:

Optimized String Retain Version Two Benchmarks
                        time:   [27.290 µs 27.355 µs 27.438 µs]
                        change: [+1.0174% +1.1835% +1.3712%] (p = 0.00 < 0.05)
                        Performance has regressed.
Found 8 outliers among 100 measurements (8.00%)
  6 (6.00%) high mild
  2 (2.00%) high severe


 Performance counter stats for './target/release/build/string_retain_bench/fe2b0b9936d108b4/out/optimized_string_retain_two_bench-fe2b0b9936d108b4 --bench':

                 0      context-switches:u               #      0.0 cs/sec  cs_per_second     
                 0      cpu-migrations:u                 #      0.0 migrations/sec  migrations_per_second
             6,462      page-faults:u                    #    408.9 faults/sec  page_faults_per_second
         15,803.18 msec task-clock:u                     #      nan CPUs  CPUs_utilized       
       193,426,678      branch-misses:u                  #      0.4 %  branch_miss_rate         (50.04%)
    50,460,848,700      branches:u                       #   3193.1 M/sec  branch_frequency     (50.00%)
    72,576,877,287      cpu-cycles:u                     #      4.6 GHz  cycles_frequency       (66.68%)
   218,952,799,755      instructions:u                   #      3.0 instructions  insn_per_cycle  (49.97%)
     1,558,472,472      stalled-cycles-frontend:u        #     0.02 frontend_cycles_idle        (50.02%)

       9.074109030 seconds time elapsed

      15.438428000 seconds user
       0.106568000 seconds sys

It's true that your suggestion improves over the previous String::retain implementation (previous to the re-implementation you made I mean). However, it does seem like using char::encode_utf8_raw_unchecked directly is slightly faster than having this match expression on the length of the character according to cargo bench and what perf results are telling me. Instruction counts are higher with char::encode_utf8_raw_unchecked, but it seems like it has less branch-misses, page faults, total cpu-cycles is lower.

}
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`.
Expand Down
Loading