-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Convert into a struct or named tuple #7
Comments
The key to the transformations you're looking for is the unexported julia> using BitFlags
julia> @bitflag BitFlagName::UInt32 begin
flag_x
flag_y
flag_z
end
julia> function Base.convert(::Type{NamedTuple}, flag::BitFlagName)
T = BitFlags.basetype(BitFlagName)
return NamedTuple(sym => T(flag) & v != zero(T) for (v, sym) in BitFlags.namemap(BitFlagName))
end
julia> convert(NamedTuple, flag_x | flag_y)
(flag_x = true, flag_y = true, flag_z = false) The conversion to your julia> struct Foo
flag_x::Bool
flag_y::Bool
flag_z::Bool
end
julia> function Base.convert(::Type{Foo}, flag::BitFlagName)
nt = convert(NamedTuple, flag)
foo_args = (getfield(nt, k) for k in fieldnames(Foo))
return Foo(foo_args...)
end
julia> convert(Foo, flag_x | flag_y)
Foo(true, true, false) I don't know much julia> using StructArrays
julia> svec2 = StructVector(convert.(Foo, [flag_x, flag_y, flag_x | flag_y]))
3-element StructArray(::Vector{Bool}, ::Vector{Bool}, ::Vector{Bool}) with eltype Foo:
Foo(true, false, false)
Foo(false, true, false)
Foo(true, true, false)
julia> svec2[1]
Foo(true, false, false)
julia> BitVector(svec2.flag_x)
3-element BitVector:
1
0
1 |
Thanks! Also, for performance reasons Also it can be generated from unrolled loop, like here: https://gist.github.com/sairus7/c370c8972d9466b2c621affbeb98a9c7 |
I want to use this as a packed representation for a structure (or a named tuple) with bool fields.
Can I transform this into such a structure?
And then I need to wrap an array of bitflags into a StructArray with fields stored as BitVectors:
The text was updated successfully, but these errors were encountered: