← Back to Pull requests

Use `char::encode_utf8_raw_unchecked` over `ptr::copy` in `String::retain` #165992

Open
asder8215 opened this pull request with 86 lines diff across 1 files
View on GitHub
asder8215 asder8215 commented on Nov 15, 2026 10:45 UTC
Author

Related to https://github.com/rust-lang/rust/issues/165988

This PR re-introduces the re-implementation of String::retain made in https://github.com/rust-lang/rust/pull/150067 and the safety hygiene changes made in https://github.com/rust-lang/rust/pull/163624.

The re-implementation of String::retain was initially reverted due to a performance regression found from the ptr::copy(...) code in rust-lang/rust#150067. The previous (or current at this time of writing/editing this description) implementation utilized char::encode_utf8 to copy over retained bytes into holes/deleted bytes area, which I would assume it's faster than doing a ptr::copy(...) as it just copies over the retained character into the destination one by one (we don't have to worry about overlap safety unlike what ptr::copy_nonoverlapping requires since we utilize a copy of char):

https://github.com/rust-lang/rust/blob/5f4effd579500175af844241eb179e756190f1e7/library/core/src/char/methods.rs#L2615-L2648

Furthermore, since we don't need the returned mutable string slice from char::encode_utf8 , I use char::encode_utf8_raw_unchecked directly instead.

cc @fereidani @Talha-Dmr

<!-- homu-ignore:start -->
<!--
Please read our [LLM policy] before opening a PR,
If you used an LLM to generate any part of this PR, including the PR description, please disclose that according to our [guidelines][disclosure guidelines].
LLM contributions are not banned, but are held to a higher standard of review and correctness.

[LLM policy]: https://forge.rust-lang.org/policies/llm-usage.html
[disclosure guidelines]: https://rustc-dev-guide.rust-lang.org/llm-guidance/writing.html#disclosure-guidelines

If this PR is related to an unstable feature or an otherwise tracked effort,
please link to the relevant tracking issue here. If you don't know of a related
tracking issue or there are none, feel free to ignore this.

This PR will get automatically assigned to a reviewer. In case you would like
a specific user to review your work, you can assign it to them by using

r? <reviewer name>

When merged, your PR's description becomes part of the commit message of a merge commit.
If you do not want certain parts of it (such as your LLM disclosure) to show up in the permanent git history,
surround them with a pair of HTML comments containing homu-ignore:start and homu-ignore:end.
-->
<!-- homu-ignore:end -->

Diff: 86 lines (+49 / -37) across 1 files Reviewer: JohnTitor Review duration: 27322m
All Vouch review confidence checks passed
Residual risk 0.09 = Change Risk (0.30) × (1 − Review Confidence (0.68)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.30 · 86 lines diff across 1 files
0.30
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.56 · 5 substantive comment(s)
0.56
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
68%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.267
Real PR Conversation Timeline
8 items
asder8215 asder8215 commented on code on Nov 15, 2026 11:04 UTC
Code Review
library/alloc/src/string.rs:1
@@ -1744,12 +1745,14 @@ 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`.
+                // SAFETY: `g.write` is always behind `g.read` by at least the current `ch_len`

I have to update this safety comment, to say it's behind the read in character ch by at least ch_len (g.read is updated at the end of the loop).

Will do this later in the morning.

View changes since the review

asder8215 asder8215 commented on code on Nov 16, 2026 00:34 UTC
Code Review
library/alloc/src/string.rs:1
@@ -1709,6 +1709,7 @@ impl String {
         }
 
         impl Drop for PanicGuard<'_> {
+            #[cold]

Also, noting for myself this should be removed when I rebase after revert gets merged in. Earlier, I thought we're not entering this case often if it's similar to Vec::retain where we set the length of the vec and mem::forget the guard, but we call drop(g) at the end.

View changes since the review*

asder8215 asder8215 commented on code on Nov 16, 2026 00:35 UTC
Code Review
library/alloc/src/string.rs:1
@@ -2107,7 +2110,7 @@ impl String {
     /// [`char`]: prim@char
     #[inline]
     #[must_use = "`self` will be dropped if the result is not used"]
-    #[stable(feature = "string_into_chars", since = "1.101.0")]
+    #[stable(feature = "string_into_chars", since = "CURRENT_RUSTC_VERSION")]

I also have no idea why these changes were made. I don't recall making these myself.

View changes since the review

workingjubilee workingjubilee commented on code on Nov 16, 2026 06:17 UTC
Code Review
library/alloc/src/string.rs:1
@@ -2107,7 +2110,7 @@ impl String {
     /// [`char`]: prim@char
     #[inline]
     #[must_use = "`self` will be dropped if the result is not used"]
-    #[stable(feature = "string_into_chars", since = "1.101.0")]
+    #[stable(feature = "string_into_chars", since = "CURRENT_RUSTC_VERSION")]

git works in mysterious ways :sparkles:

workingjubilee workingjubilee commented on code on Nov 16, 2026 21:34 UTC
Code Review
library/alloc/src/string.rs:1
@@ -1744,12 +1745,14 @@ 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`.
+                // SAFETY: `g.write` is always behind `g.read` by at least the current `ch_len`
+                // bytes, so copying `ch` from write..read should be safe. Moreover, we do not
+                // have to worry about overlap safety with `char::encode_utf8` (unlike
+                // ptr::copy_nonoverlapping`) because we have a copy of the char that
+                // we populate within write..write + ch_len one byte at a time.
                 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));

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

fereidani fereidani commented on code on Nov 16, 2026 22:38 UTC
Code Review
library/alloc/src/string.rs:1
@@ -1744,12 +1745,14 @@ 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`.
+                // SAFETY: `g.write` is always behind `g.read` by at least the current `ch_len`
+                // bytes, so copying `ch` from write..read should be safe. Moreover, we do not
+                // have to worry about overlap safety with `char::encode_utf8` (unlike
+                // ptr::copy_nonoverlapping`) because we have a copy of the char that
+                // we populate within write..write + ch_len one byte at a time.
                 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));

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 commented on code on Nov 17, 2026 01:32 UTC
Code Review
library/alloc/src/string.rs:1
@@ -1744,12 +1745,14 @@ 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`.
+                // SAFETY: `g.write` is always behind `g.read` by at least the current `ch_len`
+                // bytes, so copying `ch` from write..read should be safe. Moreover, we do not
+                // have to worry about overlap safety with `char::encode_utf8` (unlike
+                // ptr::copy_nonoverlapping`) because we have a copy of the char that
+                // we populate within write..write + ch_len one byte at a time.
                 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));

@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.

Reviewers
Assignees
asder8215 asder8215
Labels
risk: low confidence: 68.3% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 29.7% (LOW) · Higher = larger blast radius
29.7%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 68.3% · Lower = rushed or shallow review
68.3%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 9.4% · Safe to merge
9.4%
Repository