JuliaStrings / InlineStrings.jl

Fixed-width string types for Julia
Other
45 stars 13 forks source link

Support constructing from bytes buffer alone #43

Closed nickrobinson251 closed 2 years ago

nickrobinson251 commented 2 years ago

Was there a reason not to support this and instead require a user to give pos and len arguments explicitly?

I don't particularly have a use-case beyond having expected this to work having it tried it when developing locally...

Since someone can write

julia> String([0x61, 0x62, 0x63])
"abc"

I thought it might make sense to be able to write

julia> String3([0x61, 0x62, 0x63])
"abc"

I think length(buf) is probably the correct default, e.g. to get

julia> String3([0x61, 0x62, 0x63, 0x64])
ERROR: ArgumentError: string too large (4) to convert to String3
Stacktrace:
 [1] stringtoolong(T::Type, n::Int64)
   @ InlineStrings ~/repos/InlineStrings.jl/src/InlineStrings.jl:264
 [2] String3(buf::Vector{UInt8}, pos::Int64, len::Int64)
   @ InlineStrings ~/repos/InlineStrings.jl/src/InlineStrings.jl:201
 [3] String3(buf::Vector{UInt8})
   @ InlineStrings ~/repos/InlineStrings.jl/src/InlineStrings.jl:199
 [4] top-level scope
   @ REPL[39]:1

(rather than e.g. just consuming as much of the buffer as would fit in the requested type)

mkitti commented 2 years ago

This is part of my motivation for StaticStrings.jl:

julia> using StaticStrings

julia> StaticString((0x61, 0x62, 0x63))
"abc"

julia> StaticString((0x61, 0x62, 0x63, 0x64))
"abcd"

julia> StaticString(Tuple((0x61, 0x62, 0x63)))
"abc"

julia> StaticString(Tuple((0x61, 0x62, 0x63, 0x64)))
"abcd"