What is the best practice for go back and forth between a NTuple{N,UInt8} where N and a String?
x = "Dfsddfs"
a = ntuple(i -> i <= ncodeunits(x) ? codeunit(x,i) : 0x0, 10 + 1)
function _ntuple_to_string(x)
r = Ref(x)
GC.@preserve r unsafe_string(Ptr{Cchar}(pointer_from_objref(r)))
end
julia> _ntuple_to_string(a)
"Dfsddfs"
Using unsafe_string like this seems pretty unsafe. (For one thing, you are assuming that the tuple-data is NUL-terminated because you didn’t pass a length. I’m surprised it doesn’t crash. Oh, I see, you explicitly NUL-terminated your tuple.)
I would do something like:
function ntuple_to_string(t::NTuple{N,UInt8}) where N
b = Base.StringVector(N) # or N-1 if your tuples are NUL-terminated
return String(b .= t) # or t[1:N-1]
end
But you could alternatively use an ordinary Vector, at the price of making an extra copy of the data. Or use an ordinary Vector with StringViews.jl to avoid the copy.