Reputation: 284
I am looking to serialize a [][]byte
message with FlatBuffers. Given than FBS Vectors cannot be nested it seems that this is the way to go:
namespace msgfbs;
table SubmitMessage {
nonces:[Nonce];
}
table Nonce {
bytes:[ubyte];
}
Now to write this structure I ended up writing this function:
func NewSubmitMessage(builder *fbs.Builder, nonces [][]byte) []byte {
builder.Reset()
nonceCount := len(nonces)
// Convert nonces to byte vectors
byteVectors := make([]fbs.UOffsetT, nonceCount)
for i, nonce := range nonces {
byteVectors[i] = builder.CreateByteVector(nonce)
}
// Create FBS Nonces
noncesFbs := make([]fbs.UOffsetT, nonceCount)
for i := range nonces {
msgfbs.NonceStart(builder)
msgfbs.NonceAddBytes(builder, byteVectors[i])
noncesFbs[i] = msgfbs.NonceEnd(builder)
}
// Create vector of FBS Nonces
msgfbs.SubmitMessageStartNoncesVector(builder, nonceCount)
for i := nonceCount - 1; i >= 0; i-- {
builder.PrependUOffsetT(noncesFbs[i])
}
noncesVector := builder.EndVector(nonceCount)
// Create message
msgfbs.SubmitMessageStart(builder)
msgfbs.SubmitMessageAddNonces(builder, noncesVector)
builder.Finish(msgfbs.SubmitMessageEnd(builder))
builder.PrependByte(Submit)
return builder.FinishedBytes()
}
I need 3 consecutive for-loop before finally wrapping up my message. Is this the simplest way to serialize a [][]byte
? Is there a more efficient way to achieve the same?
Upvotes: 0
Views: 369
Reputation: 6074
The first 2 for loops can be merged: you can create the byte vector, followed by the table holding it. You just can't nest the byte vector between Start/End.
For the last for loop there really should be a helper function doing this for you (they exist for other languages). If there's none in Go, create an issue (or better yet, a PR) on the FlatBuffers repo.
Upvotes: 1