perf: remove loop from str::floor_char_boundary
#149466
Open
+34
−10
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
#144472 made
str::floor_char_boundarya const function, but in doing so introduced a loop. This is unnecessary because the next UTF-8 character boundary can only be within a 4-byte range.This produces excessive code for e.g.
str.floor_char_boundary(20), because the loop is unrolled.https://godbolt.org/z/5f3YsM6oK
This PR replaces the loop with 3 checks in series.
In addition to reducing code size in some cases, it also removes bounds checks from calling code when following
floor_char_boundarywith a call toString::truncate(which I assume might be a common pattern).Notes
I tried using
index.unchecked_sub(1), but found it doesn't remove bounds checks, whereasindex.checked_sub(1).unwrap_unchecked()does. Surprising!The
assert_uncheckeds are required to elide checks from code following thefloor_char_boundarycall e.g.:If this PR is accepted, I'll follow up with a similar PR for
ceil_char_boundary.Very happy to receive feedback and amend.