JuliaData / FlatBuffers.jl

A pure Julia implementation of google flatbuffers
https://juliadata.github.io/FlatBuffers.jl/stable
Other
43 stars 14 forks source link

How to retrieve value from Union #64

Open sptrakesh opened 1 year ago

sptrakesh commented 1 year ago

Hello,

Pardon my ignorance, trying Julia for the first time. I am trying to write a client for a TCP service I have in C++. I am trying to figure out how to extract the appropriate value from a union type in the response.

The IDL for the response can be viewed here

The Julia generated structures for the responses look like the following:

FlatBuffers.@with_kw mutable struct Response{A}
    value_type::UInt8 = 0
    value::A = nothing
end

struct ResultVariantKeyValueResults end
ResultVariantKeyValueResults(args...; kwargs...) = KeyValueResults(args...; kwargs...)

struct ResultVariantSuccess end
ResultVariantSuccess(args...; kwargs...) = Success(args...; kwargs...)

FlatBuffers.@UNION(ResultVariant, (
    Nothing,
    ResultVariantKeyValueResults,
    ResultVariantSuccess,
))

FlatBuffers.@with_kw mutable struct KeyValueResults{A}
    value::Vector{A} = []
end

FlatBuffers.@with_kw mutable struct KeyValueResult{A}
    key::String = ""
    value_type::UInt8 = 0
    value::A = nothing
end

FlatBuffers.@with_kw mutable struct Success
    value::Bool = false
end

I can connect to the TCP server, and submit a FB request. I get the FB response back, which is as defined in the IDL linked above. The response from the server once deserialised prints out the following expected structure:

┌ Info: Response{Union{Nothing, ResultVariantKeyValueResults, ResultVariantSuccess}}
│   value_type: UInt8 0x02
└   value: ResultVariantSuccess ResultVariantSuccess()

I am trying to figure out how I can convert the ResultVariantSuccess into the Success structure (or for the case of ResultVariantKeyValueResults into KeyValueResults). In the C++ code, there are value_as methods, which allow me to extract the proper data structures from the unions. I do not see anything similar in the FlatBuffers.jl file (at least did not see anything that looked similar).

Thanks in advance for any help in resolving the issue. Rakesh