dongyixiu3110 2019-09-21 18:04
浏览 93
已采纳

有没有更简单的方法可以使用FlatBuffers序列化[] [] byte?

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?

  • 写回答

1条回答 默认 最新

  • dsf55s1233 2019-09-21 19:06
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?