Skip to content

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

Open
asder8215 wants to merge 3 commits into
rust-lang:mainfrom
asder8215:string_retain_regression_fix
Open

asder8215 wants to merge 3 commits into
rust-lang:mainfrom
asder8215:string_retain_regression_fix

Conversation

@asder8215

@asder8215 asder8215 commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Related to #165988

This PR re-introduces the re-implementation of String::retain made in #150067 and the safety hygiene changes made in #163624.

The re-implementation of String::retain was initially reverted due to a performance regression found from the ptr::copy(...) code in #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):

pub const unsafe fn encode_utf8_raw_unchecked(code: u32, dst: *mut u8) {
let len = len_utf8(code);
// SAFETY: The caller must guarantee that the buffer pointed to by `dst`
// is at least `len` bytes long.
unsafe {
if len == 1 {
*dst = code as u8;
return;
}
let last1 = (code >> 0 & 0x3F) as u8 | TAG_CONT;
let last2 = (code >> 6 & 0x3F) as u8 | TAG_CONT;
let last3 = (code >> 12 & 0x3F) as u8 | TAG_CONT;
let last4 = (code >> 18 & 0x3F) as u8 | TAG_FOUR_B;
if len == 2 {
*dst = last2 | TAG_TWO_B;
*dst.add(1) = last1;
return;
}
if len == 3 {
*dst = last3 | TAG_THREE_B;
*dst.add(1) = last2;
*dst.add(2) = last1;
return;
}
*dst = last4;
*dst.add(1) = last3;
*dst.add(2) = last2;
*dst.add(3) = last1;
}
}

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

@rustbot rustbot added the A-str Area: `str` and `String` label Nov 15, 2026
@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-libs Relevant to the library team, which will review and decide on the PR/issue. labels Nov 15, 2026
@rustbot

rustbot commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator

r? @maxdexh

rustbot has assigned @maxdexh.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

Why was this reviewer chosen?

The reviewer was selected based on:

  • Owners of files modified in this PR: libs
  • libs expanded to 38 candidates
  • Random selection from JohnTitor, Mark-Simulacrum, clarfonthey, maxdexh

@asder8215 asder8215 changed the title Revert String::retain implementation to use char::encode_utf8_raw_unchecked over ptr::copy Revert String::retain implementation to use char::encode_utf8_raw_unchecked over ptr::copy Nov 15, 2026
@maxdexh

maxdexh commented Nov 15, 2026

Copy link
Copy Markdown
Member

cc @joboet (reviewer of the reverted PR)
(feel free to take this one if you want; otherwise i'll read through this stuff when i get the time)

Comment thread library/alloc/src/string.rs Resolved
@theemathas theemathas added the beta-nominated Nominated for backporting to the compiler in the beta channel. label Nov 15, 2026
@hanna-kruppe

hanna-kruppe commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Thank you for preparing this. It looks like this PR:

  1. Reverts only a relevant subset of Alloc String::retain optimization #150067 rather than completely reverting the merge commit 35df304 (it doesn't revert without conflicts, so I can't easily check, but at least the change to PanicGuard wasn't reverted)
  2. adds some additional changes on top, beyond what's necessary to fix conflicts with other changes on main (e.g., the switch from char::encode_utf8 to encode_utf8_raw_unchecked, changes to safety comments)

In general a "straight revert" is preferable in these situations, especially for reverts we might want to backport, as that's usually less risky and quicker to review. See also the section on reverts in the forge (technically compiler team policy, but a lot of it is good advice more generally).

So I'd propose that you (or someone else, if you'd prefer) first create a straight revert (with only minimal changes to fix conflicts), we backport that, and any other changes (including e.g. encode_utf8_raw_unchecked and trying to re-land a fixed version of the original PR) go into separate follow-up PRs.

@asder8215

Copy link
Copy Markdown
Contributor Author

I would be open to reverting the implementation of String::retain to how it was before #150067 (in a separate PR) and have this PR open to re-introduce the change #150067 brought later. However, one thing to note is that aside from #150067, a later change that was made to String::retain was in #163624, which changes this:

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() };

(same piece of code seen in #150067 just with let ch = unsafe { g.s.get_unchecked(read..len).chars().next().unwrap_unchecked() };)

to this:

// 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()
};

I believe the reason why this change was made was because it's possible for our string to contain invalid utf 8 bytes at one point in replacing 'deleted' bytes/'holes' (e.g. the example provided in #163624, shows that when we remove 'é', which takes up 2 bytes, in "éab" and then retain "a" we go from C3 A9 61 62 to 61 A9 61 62 as the "a" covers 1 of the 2 byte gap left by 'é'). However, I don't understand the safety reasoning they mention in #163624, as we're indexing the region after the hole/unread bytes, which shouldn't violate str::get_unchecked?

Regardless, I wanted to check in on if I should integrate the change made in #163624 to the String::retain reversion (implementation before #150067) since we'd be regressing the change it makes there?

@asder8215 asder8215 changed the title Revert String::retain implementation to use char::encode_utf8_raw_unchecked over ptr::copy Use char::encode_utf8_raw_unchecked over ptr::copy in String::retain Nov 15, 2026
@workingjubilee

Copy link
Copy Markdown
Member

@asder8215 If reverting that other PR immediately gets us to a fully clean revert: Yes, both. It will collapse any waffling on our side into a "yes". Please try and inform.

If that lands and gets backported, then we want to immediately reland a variant of #163624 so that the safety hygiene changes are addressed. They don't necessarily affect the "amount of actual UB" in the code, as I understand it, but they do affect how brittle it is to further changes in our codebase so they remain desirable.

@hanna-kruppe

Copy link
Copy Markdown
Contributor

To answer this question (and expand on what Jubilee said w.r.t. safety hygiene):

However, I don't understand the safety reasoning they mention in #163624, as we're indexing the region after the hole/unread bytes, which shouldn't violate str::get_unchecked?

Unless explicitly stated otherwise, functions that take &str inputs can expect the &str value to be "safe" (i.e., "satify the type's safety invariant") and may have UB otherwise. Of course str::get_unchecked doesn't actually do much that could cause UB, but we don't guarantee that in its documentation (e.g., we might want to add more UB checks to it in the future).

Code inside the standard library can rely on more details than we publicly guarantee, but this sets a bad example and is harder to maintain (e.g., when making changes to one function you usually don't audit all callers to see what implementation details they rely on). So it's better to not call get_unchecked on invalid UTF-8 strings.

@asder8215

asder8215 commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Just noting it in here: I was benchmarking the char::encode_utf8_raw_unchecked change in this repo I made (copied the relevant parts from stdlib I needed to maintain fereidani's code while just swapping ptr::copy for char::encode_utf8_raw_unchecked); the benchmark test utilizes the same case that Julio, the original issue owner in #165988, was benchmarking on (except I took out the for _ in 100000 and just run the for _ in 0..15, otherwise it would've taken ~9-10 minutes to run). Here's the results I got:

Current String Retain Benchmarks
                        time:   [50.872 µs 51.192 µs 51.560 µs]
                        change: [−8.3504% −7.4582% −6.5739%] (p = 0.00 < 0.05)
                        Performance has improved.
Found 13 outliers among 100 measurements (13.00%)
  10 (10.00%) high mild
  3 (3.00%) high severe

     Running benches/optimized_string_retain_bench.rs (target/release/build/string_retain_bench/c2239f57c8c677a2/out/optimized_string_retain_bench-c2239f57c8c677a2)
Gnuplot not found, using plotters backend
Optimized String Retain Benchmarks
                        time:   [24.069 µs 24.146 µs 24.236 µs]
                        change: [−1.6890% −0.6281% +0.1240%] (p = 0.20 > 0.05)
                        No change in performance detected.
Found 9 outliers among 100 measurements (9.00%)
  3 (3.00%) high mild
  6 (6.00%) high severe

     Running benches/prev_string_retain_bench.rs (target/release/build/string_retain_bench/82614048d323b7fe/out/prev_string_retain_bench-82614048d323b7fe)
Gnuplot not found, using plotters backend
Previous String Retain Benchmarks
                        time:   [33.673 µs 33.779 µs 33.906 µs]
                        change: [−1.5816% −0.9992% −0.4596%] (p = 0.00 < 0.05)
                        Change within noise threshold.
Found 12 outliers among 100 measurements (12.00%)
  5 (5.00%) high mild
  7 (7.00%) high severe

The current string retain refers to the fereidani's String::retain implementation right now (since the revert isn't merged in yet).
The previous string retain benchmark refers to the one previous to fereidani's implementation.
And the optimized one refers to feiradani's implementation with a small change in swapping ptr::copy with char::encoded_utf8_raw_unchecked

It really seems like swapping out the ptr::copy for char::encode_utf8_raw_unchecked fixes the perf regression and actually optimizes it over the previous implementation of String::retain.

Comment thread library/alloc/src/string.rs Outdated
}

impl Drop for PanicGuard<'_> {
#[cold]

@asder8215 asder8215 Nov 16, 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.

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

Comment thread library/alloc/src/string.rs Outdated
#[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")]

@asder8215 asder8215 Nov 16, 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.

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

View changes since the review

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.

git works in mysterious ways ✨

@rust-bors

This comment has been minimized.

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));

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

fereidani and others added 3 commits November 16, 2026 21:07
Slice the byte vector before converting to str, avoiding a whole-buffer conversion while compaction may leave invalid UTF-8.
…g::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)`
@asder8215
asder8215 force-pushed the string_retain_regression_fix branch from 546d7ab to ef992ba Compare November 17, 2026 02:35
@asder8215

asder8215 commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Currently, I have Feiradani's and Talha's changes in separate commits. If it's preferred to squash the commits and point to Fereidani's and Talha's PR in the commit message directly, lmk and I could do that.

@workingjubilee

Copy link
Copy Markdown
Member

Separate commits is fine.

@nia-e nia-e removed the beta-nominated Nominated for backporting to the compiler in the beta channel. label Nov 17, 2026
@maxdexh

maxdexh commented Nov 19, 2026

Copy link
Copy Markdown
Member

I didn't follow the discussion here at all, and the wall of PR links (that isn't even complete) kinda confuses me. @workingjubilee do you want to take this? You seem to know more about this method

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-str Area: `str` and `String` S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-libs Relevant to the library team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants