猿问

Flatbuffer mutate 不会改变字节

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


这是我的平面缓冲区表定义:


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 的调用似乎成功以来它们没有改变?


墨色风雨
浏览 140回答 2
2回答

繁星coding

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

四季花海

这个问题至少有两种解决方案。对于我来说,第二种解决方案更好,因为它会减少字节的复制。通过创建一个中间字符串(因此,创建字节的副本)。一般来说,对于平面缓冲区,您希望避免复制,但对于我的用例,我对此表示同意。像这样包装表定义:    table LotsOfData {        notMutated:[ubyte];    }    table TestMutate {        notMutated:LotsOfData;        serverId:int32;    }
随时随地看视频慕课网APP

相关分类

Go
我要回答