Note that if you want a fixed number of bytes, then you can use a StringView of an SVector:
julia> using StringViews, StaticArrays
julia> s = StringView(SVector{4,UInt8}(b"abcd"))
"abcd"
It is probably more useful to have a fixed upper bound on the number of bytes, in which case you can use a StringView
of a SubArray
of an SVector
.
julia> s = StringView(@view SVector{8,UInt8}(b"abcd ")[1:4])
"abcd"
For example, given an array a
of strings, you can convert it to an array of strings with fixed-length inline (isbits
) storage via:
julia> function tofixedstr(s::String, nbytes)
n = ncodeunits(s)
StringView(@view SVector{nbytes}(codeunits(s * ' '^(nbytes-n)))[Base.OneTo(n)])
end
tofixedstr (generic function with 3 methods)
julia> function tofixedstr(a::AbstractVector{String})
npad = maximum(ncodeunits, a)
tofixedstr.(a, npad)
end
tofixedstr (generic function with 3 methods)
julia> a = ["foo", "blärg", "l♡ve"]
3-element Array{String,1}:
"foo"
"blärg"
"l♡ve"
julia> b = tofixedstr(a)
3-element Array{StringView{SubArray{UInt8,1,SArray{Tuple{6},UInt8,1,6},Tuple{Base.OneTo{Int64}},true}},1}:
"foo"
"blärg"
"l♡ve"
Note that this is a bits type, so all of the data is stored inline, as needed for SharedArray
:
julia> isbits(b[1])
true
julia> println(reinterpret(UInt8, b))
UInt8[0x66, 0x6f, 0x6f, 0x20, 0x20, 0x20, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x6c, 0xc3, 0xa4, 0x72, 0x67, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6c, 0xe2, 0x99, 0xa1, 0x76, 0x65, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
(Note that 0x20
is the ' '
padding byte in each underlying SVector
.)
All the usual string operations should work, e.g.
julia> sort(b)
3-element Array{StringView{SubArray{UInt8,1,SArray{Tuple{6},UInt8,1,6},Tuple{Base.OneTo{Int64}},true}},1}:
"blärg"
"foo"
"l♡ve"