Skip to content

Add a more efficient implementation for String(::ReinterpretArray) #58438

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

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
10 changes: 10 additions & 0 deletions base/strings/string.jl
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,16 @@ function String(v::Vector{UInt8})
setfield!(v, :ref, memoryref(Memory{UInt8}()))
return str
end
function String(v::ReinterpretArray{UInt8, 1, S, Vector{S}, IsReshaped}) where {S, IsReshaped}
len = length(v)
len == 0 && return ""
return ccall(:jl_pchar_to_string, Ref{String}, (Ptr{S}, Int), v.parent.ref, len)
end
function String(v::ReinterpretArray{UInt8, 1, S, Memory{S}, IsReshaped}) where {S, IsReshaped}
len = length(v)
len == 0 && return ""
return ccall(:jl_pchar_to_string, Ref{String}, (Ptr{S}, Int), v.parent.ptr, len)
end

"Create a string re-using the memory, if possible.
Mutating or reading the memory after calling this function is undefined behaviour."
Expand Down
8 changes: 8 additions & 0 deletions test/strings/basic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ using Random
@test String("abc!") == "abc!"
@test String(0x61:0x63) == "abc"

v = [0x61,0x62,0x63,0x21]
v32 = copy(reinterpret(UInt32, v))
@test String(reinterpret(UInt8, v32)) == "abc!" && !isempty(v32)
@test 1 == @allocations String(reinterpret(UInt8, v32))
m32 = v32.ref.mem
@test String(reinterpret(UInt8, m32)) == "abc!" && !isempty(m32)
@test 1 == @allocations String(reinterpret(UInt8, m32))

# Check that resizing empty source vector does not corrupt string
b = IOBuffer()
@inferred write(b, "ab")
Expand Down