Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize String#index(Char) and #rindex(Char) for invalid UTF-8 #14461

Merged
Merged
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
12 changes: 10 additions & 2 deletions src/string.cr
Original file line number Diff line number Diff line change
Expand Up @@ -3334,7 +3334,11 @@ class String
# ```
def index(search : Char, offset = 0) : Int32?
# If it's ASCII we can delegate to slice
if search.ascii? && single_byte_optimizable?
if single_byte_optimizable?
# With `single_byte_optimizable?` there are only ASCII characters and invalid UTF-8 byte
# sequences and we can immediately reject any non-ASCII codepoint.
return unless search.ascii?

return to_slice.fast_index(search.ord.to_u8, offset)
end

Expand Down Expand Up @@ -3445,7 +3449,11 @@ class String
# ```
def rindex(search : Char, offset = size - 1)
# If it's ASCII we can delegate to slice
if search.ascii? && single_byte_optimizable?
if single_byte_optimizable?
# With `single_byte_optimizable?` there are only ASCII characters and invalid UTF-8 byte
# sequences and we can immediately reject any non-ASCII codepoint.
return unless search.ascii?

return to_slice.rindex(search.ord.to_u8, offset)
end

Expand Down
Loading