Skip to content

Commit e818105

Browse files
stevengjfingolfinViralBShah
authored
document that unsafe_string accepts Cstring (#56907)
Document that `unsafe_string` allows its argument to be a `Cstring`. There is also another method that accepts `Cwstring`, which transcodes from a NUL-terminated `wchar_t` array (assumed to be either UTF-32 or UTF-16 depending on the width of `wchar_t`). Should that be documented in the same docstring or in a different docstring? --------- Co-authored-by: Max Horn <[email protected]> Co-authored-by: Viral B. Shah <[email protected]>
1 parent 2e26583 commit e818105

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

base/strings/cstring.jl

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -301,14 +301,27 @@ function transcode(::Type{UInt8}, src::AbstractVector{UInt16})
301301
return dst
302302
end
303303

304+
"""
305+
unsafe_string(p::Ptr{T}, [length::Integer]) where {T<:Union{UInt16,UInt32,Cwchar_t}}
306+
unsafe_string(p::Cwstring)
307+
308+
Transcode a string from the address of a C-style (NUL-terminated) string encoded as UTF-16
309+
(`T=UInt16`), UTF-32 (`T=UInt32`), or the system-dependent `wchar_t` (`T=Cwchar_t` or `Cwstring`),
310+
returning a `String` (UTF-8 encoding), similar to [`transcode`](@ref) but reading directly
311+
from a pointer. (The pointer can be safely freed afterwards.) If `length` is specified
312+
(the length of the data in encoding units), the string does not have to be NUL-terminated.
313+
314+
This function is labeled "unsafe" because it will crash if `p` is not
315+
a valid memory address to data of the requested length (or NUL-terminated data).
316+
"""
304317
function unsafe_string(p::Ptr{T}, length::Integer) where {T<:Union{UInt16,UInt32,Cwchar_t}}
305318
transcode(String, unsafe_wrap(Array, p, length; own=false))
306319
end
307-
function unsafe_string(cw::Cwstring)
308-
p = convert(Ptr{Cwchar_t}, cw)
320+
function unsafe_string(p::Ptr{T}) where {T<:Union{UInt16,UInt32,Cwchar_t}}
309321
n = 1
310322
while unsafe_load(p, n) != 0
311323
n += 1
312324
end
313325
return unsafe_string(p, n - 1)
314326
end
327+
unsafe_string(cw::Cwstring) = unsafe_string(convert(Ptr{Cwchar_t}, cw))

base/strings/string.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ takestring!(v::Vector{UInt8}) = String(v)
109109

110110
"""
111111
unsafe_string(p::Ptr{UInt8}, [length::Integer])
112+
unsafe_string(p::Cstring)
112113
113114
Copy a string from the address of a C-style (NUL-terminated) string encoded as UTF-8.
114115
(The pointer can be safely freed afterwards.) If `length` is specified

0 commit comments

Comments
 (0)