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

Improve performance of ncodeunits(::Char) #54001

Merged
merged 3 commits into from
Apr 9, 2024
Merged
Changes from 1 commit
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
15 changes: 14 additions & 1 deletion base/char.jl
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,20 @@ to an output stream, or `ncodeunits(string(c))` but computed efficiently.
This method requires at least Julia 1.1. In Julia 1.0 consider
using `ncodeunits(string(c))`.
"""
ncodeunits(c::Char) = write(devnull, c) # this is surprisingly efficient
function ncodeunits(c::Char)
# All Char are 4 byte wide, and since unicode encoding
# doesn't have null bytes (except for \0), we can just
# count non-zero bytes
char_data = reinterpret(UInt32, c)
mask = 0xff % UInt32
nbytes = !iszero(char_data & mask)
Base.Cartesian.@nexprs 3 i -> begin
m <<= 0x8
Seelengrab marked this conversation as resolved.
Show resolved Hide resolved
nbytes += !iszero(char_data & mask)
end
# We have to account for `\0`, which is encoded as all zeros
nbytes + iszero(uc)
Seelengrab marked this conversation as resolved.
Show resolved Hide resolved
end

"""
codepoint(c::AbstractChar) -> Integer
Expand Down