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

optimized textwidth(::Char) for ASCII #55398

Merged
merged 9 commits into from
Aug 7, 2024
Merged
Show file tree
Hide file tree
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
9 changes: 9 additions & 0 deletions base/strings/unicode.jl
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,15 @@ julia> textwidth('⛵')
```
"""
function textwidth(c::AbstractChar)
ismalformed(c) && return 1
i = codepoint(c)
i < 0x7f && return Int(i >= 0x20) # ASCII fast path
Int(ccall(:utf8proc_charwidth, Cint, (UInt32,), i))
end

function textwidth(c::Char)
b = bswap(reinterpret(UInt32, c)) # from isascii(c)
b < 0x7f && return Int(b >= 0x20) # ASCII fast path
ismalformed(c) && return 1
Int(ccall(:utf8proc_charwidth, Cint, (UInt32,), c))
end
Expand Down
14 changes: 14 additions & 0 deletions test/strings/util.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,20 @@

SubStr(s) = SubString("abc$(s)de", firstindex(s) + 3, lastindex(s) + 3)

@testset "textwidth" begin
for (c, w) in [('x', 1), ('α', 1), ('🍕', 2), ('\0', 0), ('\u0302', 0), ('\xc0', 1)]
@test textwidth(c) == w
@test textwidth(c^3) == w*3
@test w == @invoke textwidth(c::AbstractChar)
end
for i in 0x00:0x7f # test all ASCII chars (which have fast path)
w = Int(ccall(:utf8proc_charwidth, Cint, (UInt32,), i))
c = Char(i)
@test textwidth(c) == w
@test w == @invoke textwidth(c::AbstractChar)
end
end

@testset "padding (lpad and rpad)" begin
@test lpad("foo", 2) == "foo"
@test rpad("foo", 2) == "foo"
Expand Down