Addition of Go FinishWithFileIdentifier (#4720)
authorhusobee <husobee@e-ie.io>
Mon, 30 Apr 2018 21:37:24 +0000 (17:37 -0400)
committerWouter van Oortmerssen <aardappel@gmail.com>
Mon, 30 Apr 2018 21:37:24 +0000 (14:37 -0700)
* Addition of Go FinishWithFileIdentifier, allows for Go flatbuffer data to contain a file identifier

* adding panic as per review if fileIdentifier does not match length, letting prep pad the file identifier

* updated error message to not use fmt.Sprintf

* using minalign for alignment for file identifier

go/builder.go

index a7bf4a1..e47f420 100644 (file)
@@ -19,6 +19,8 @@ type Builder struct {
        finished  bool
 }
 
+const fileIdentifierLength = 4
+
 // NewBuilder initializes a Builder of size `initial_size`.
 // The internal buffer is grown as needed.
 func NewBuilder(initialSize int) *Builder {
@@ -111,9 +113,10 @@ func (b *Builder) WriteVtable() (n UOffsetT) {
        existingVtable := UOffsetT(0)
 
        // Trim vtable of trailing zeroes.
-       i := len(b.vtable) - 1;
-       for ; i >= 0 && b.vtable[i] == 0; i-- {}
-       b.vtable = b.vtable[:i + 1];
+       i := len(b.vtable) - 1
+       for ; i >= 0 && b.vtable[i] == 0; i-- {
+       }
+       b.vtable = b.vtable[:i+1]
 
        // Search backwards through existing vtables, because similar vtables
        // are likely to have been recently appended. See
@@ -540,6 +543,23 @@ func (b *Builder) Slot(slotnum int) {
        b.vtable[slotnum] = UOffsetT(b.Offset())
 }
 
+// FinishWithFileIdentifier finalizes a buffer, pointing to the given `rootTable`.
+// as well as applys a file identifier
+func (b *Builder) FinishWithFileIdentifier(rootTable UOffsetT, fid []byte) {
+       if fid == nil || len(fid) != fileIdentifierLength {
+               panic("incorrect file identifier length")
+       }
+       // In order to add a file identifier to the flatbuffer message, we need
+       // to prepare an alignment and file identifier length
+       b.Prep(b.minalign, SizeInt32+fileIdentifierLength)
+       for i := fileIdentifierLength - 1; i >= 0; i-- {
+               // place the file identifier
+               b.PlaceByte(fid[i])
+       }
+       // finish
+       b.Finish(rootTable)
+}
+
 // Finish finalizes a buffer, pointing to the given `rootTable`.
 func (b *Builder) Finish(rootTable UOffsetT) {
        b.assertNotNested()