Flatbuffer mutate 不会改变字节

Flatbuffer mutate doesn't change bytes

我 运行 遇到了从字节突变平面缓冲区的问题。根据 flatbuffer 文档 (https://github.com/google/flatbuffers/blob/master/docs/source/Tutorial.md),您可以 改变固定大小的字段,例如 int32。正如您在下面看到的,生成的 golang TestMutate 有一个 MutateServerId() 函数。我的问题是,在我改变它之后,字节似乎没有改变。

这是我的 flatbuffer table 定义:

namespace foo;

table TestMutate {
    serverId:int32;
}

这是我写的单元测试:

func TestMutateFlatbuffer2(test *testing.T) {
    builder := flatbuffers.NewBuilder(1024)
    packageWalletStorageServicesRPC.TestMutateStart(builder)
    packageWalletStorageServicesRPC.TestMutateAddServerId(builder, 1)
    endMessage := packageWalletStorageServicesRPC.TestMutateEnd(builder)
    builder.Finish(endMessage)

    bytes := builder.FinishedBytes()
    testMutate := packageWalletStorageServicesRPC.GetRootAsTestMutate(bytes, 0)
    success := testMutate.MutateServerId(2)
    if !success {
        panic("Server id not mutated.")
    } else {
        logger.Logf(logger.INFO, "serverId mutated to:%d", testMutate.ServerId())
    }

    mutatedBytes := testMutate.Table().Bytes
    if string(mutatedBytes) == string(bytes) {
        panic("Bytes were not mutated.")
    }
}

这是测试的输出。

=== RUN   TestMutateFlatbuffer2
2019/08/01 19:33:56.801926 foo_test.go:389   : [ I ]: serverId mutated to:2
--- FAIL: TestMutateFlatbuffer2 (0.00s)
panic: Bytes were not mutated. [recovered]
    panic: Bytes were not mutated.

请注意,我似乎已经改变了底层结构,但是当我获得平面缓冲区的字节时, 他们没有改变。问题 1:我获取字节的方式是否正确?问题 2:如果我以正确的方式获取它们,为什么 自从调用 mutate 似乎成功后,它们没有改变吗?

您的测试 string(mutatedBytes) == string(bytes) 失败,因为...您正在将变异缓冲区与自身进行比较。 bytes 指的是一个缓冲区,在你的突变之前包含一个 1,在它之后包含一个 2。mutatedBytes 指向同一个缓冲区,因此也包含一个 2。事实是 testMutate.ServerId() returns 2 应该告诉您缓冲区已成功变异,因为没有其他方法 return 2 :) 您必须制作 [=11= 的(深)副本] 如果您希望此比较显示缓冲区不同,则在突变之前。

这个问题至少有两种解决方案。第二种解决方案对我来说更好,因为它减少了字节复制。

  1. 通过创建中间字符串(因此,字节的副本)。通常对于平面缓冲区,您希望避免复制,但对于我的用例,我可以接受。

  2. 像这样包装 table 定义:


    table LotsOfData {
        notMutated:[ubyte];
    }

    table TestMutate {
        notMutated:LotsOfData;
        serverId:int32;
    }