Skip to content

Commit a76df84

Browse files
committed
Add a more efficient implementation for String(::ReinterpretArray)
1 parent eebda6c commit a76df84

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

base/strings/string.jl

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,20 @@ function String(v::Vector{UInt8})
7777
setfield!(v, :ref, memoryref(Memory{UInt8}()))
7878
return str
7979
end
80+
function String(v::ReinterpretArray{UInt8, 1, S, Vector{S}, IsReshaped}) where {S, IsReshaped}
81+
len = length(v)
82+
len == 0 && return ""
83+
ref = v.parent.ref
84+
if ref.ptr_or_offset == ref.mem.ptr
85+
str = ccall(:jl_genericmemory_to_string, Ref{String}, (Any, Int), ref.mem, len)
86+
else
87+
str = ccall(:jl_pchar_to_string, Ref{String}, (Ptr{S}, Int), ref, len)
88+
end
89+
# optimized empty!(v.parent); sizehint!(v.parent, 0) calls
90+
setfield!(v.parent, :size, (0,))
91+
setfield!(v.parent, :ref, memoryref(Memory{S}()))
92+
return str
93+
end
8094

8195
"Create a string re-using the memory, if possible.
8296
Mutating or reading the memory after calling this function is undefined behaviour."

0 commit comments

Comments
 (0)