From bed19a5340c12fda7e03d0abe0f34304a3e27590 Mon Sep 17 00:00:00 2001 From: husobee Date: Mon, 30 Apr 2018 17:37:24 -0400 Subject: [PATCH] Addition of Go FinishWithFileIdentifier (#4720) * 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 | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/go/builder.go b/go/builder.go index a7bf4a1d9..e47f420c2 100644 --- a/go/builder.go +++ b/go/builder.go @@ -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()