google / flatbuffers

FlatBuffers: Memory Efficient Serialization Library

Home Page:https://flatbuffers.dev/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support file_identifier in Go

jdemeyer opened this issue · comments

it seems that Go supports an explicit file identifier using Builder.FinishWithFileIdentifier. But the docs at https://flatbuffers.dev/flatbuffers_guide_writing_schema.html state that the file identifier should be added automatically by a FinishMonsterBuffer call but this is not implemented for Go. Also, there doesn't seem to be a way in Go to check an identifier (there is no MonsterBufferHasIdentifier)

Am I reading the docs correctly? Is this something to be fixed?

Yeah doesn't seem to be implemented yet in Go (or Python either)

You are correct that the Go implementation of FlatBuffers does not currently provide a way to automatically add a file identifier to a FlatBuffer. As a result, you need to use Builder.FinishWithFileIdentifier() to manually add a file identifier to a FlatBuffer.

Regarding checking a file identifier in a FlatBuffer, the Go implementation does not provide a specific function for this, but you can check the identifier manually using the bytes.Equal() function to compare the identifier bytes in the FlatBuffer against the expected identifier bytes.

Here's an example of how you could add a file identifier to a FlatBuffer in Go:

go
Copy code
import (
"github.com/google/flatbuffers/go"
)

func createMonster(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
// ... build your FlatBuffer as normal ...
// Use FinishWithFileIdentifier to add a file identifier
return builder.FinishWithFileIdentifier("MONS")
}
And here's an example of how you could check the file identifier in a FlatBuffer in Go:

go
Copy code
import (
"bytes"
"github.com/google/flatbuffers/go"
)

func readMonster(buf []byte) {
// Read the FlatBuffer as normal
monster := GetRootAsMonster(buf, 0)

// Check the file identifier
expectedIdentifier := []byte("MONS")
identifier := monster.FileIdentifier()

if !bytes.Equal(identifier[:], expectedIdentifier) {
    // Handle error
}

}
I hope this helps! While it would be nice if the Go implementation provided a more convenient way to add and check file identifiers, using FinishWithFileIdentifier() and bytes.Equal() should still allow you to add and check file identifiers in your FlatBuffers.

@saurabhmj11 Do you know if there are plans to support file_identifier in --jsonschema as well? Currently looks like the file_identifier metadata is lost when converting fbs to json format with flatc --jsonschema.