From a593a11e593b55f64b4094e28efb1cb85cae125b Mon Sep 17 00:00:00 2001 From: mustiikhalil Date: Fri, 24 Jan 2020 20:57:34 +0300 Subject: [PATCH] [Go] Implements a SharedStrings function (#5733) * Adds the sharedstring implementation for go * Reimplemented testcase according to request --- go/builder.go | 17 ++++++++++++++++- tests/go_test.go | 27 ++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/go/builder.go b/go/builder.go index 8d75700ce..0e763d7ac 100644 --- a/go/builder.go +++ b/go/builder.go @@ -17,6 +17,8 @@ type Builder struct { head UOffsetT nested bool finished bool + + sharedStrings map[string]UOffsetT } const fileIdentifierLength = 4 @@ -33,7 +35,6 @@ func NewBuilder(initialSize int) *Builder { b.head = UOffsetT(initialSize) b.minalign = 1 b.vtables = make([]UOffsetT, 0, 16) // sensible default capacity - return b } @@ -307,6 +308,20 @@ func (b *Builder) EndVector(vectorNumElems int) UOffsetT { return b.Offset() } +// CreateSharedString Checks if the string is already written +// to the buffer before calling CreateString +func (b *Builder) CreateSharedString(s string) UOffsetT { + if b.sharedStrings == nil { + b.sharedStrings = make(map[string]UOffsetT) + } + if v, ok := b.sharedStrings[s]; ok { + return v + } + off := b.CreateString(s) + b.sharedStrings[s] = off + return off +} + // CreateString writes a null-terminated string as a vector. func (b *Builder) CreateString(s string) UOffsetT { b.assertNotNested() diff --git a/tests/go_test.go b/tests/go_test.go index 29a2e0e43..9b2ec964a 100644 --- a/tests/go_test.go +++ b/tests/go_test.go @@ -28,6 +28,7 @@ import ( "reflect" "sort" "testing" + "testing/quick" flatbuffers "github.com/google/flatbuffers/go" ) @@ -77,7 +78,8 @@ func TestAll(t *testing.T) { CheckByteStringIsNestedError(t.Fatalf) CheckStructIsNotInlineError(t.Fatalf) CheckFinishedBytesError(t.Fatalf) - + CheckSharedStrings(t.Fatalf) + // Verify that GetRootAs works for non-root tables CheckGetRootAsForNonRootTable(t.Fatalf) CheckTableAccessors(t.Fatalf) @@ -1375,6 +1377,29 @@ func CheckStringIsNestedError(fail func(string, ...interface{})) { b.CreateString("foo") } +func CheckSharedStrings(fail func(string, ...interface{})) { + f := func(strings []string) bool { + b := flatbuffers.NewBuilder(0) + for _, s1 := range strings { + for _, s2 := range strings { + off1 := b.CreateSharedString(s1) + off2 := b.CreateSharedString(s2) + + if (s1 == s2) && (off1 != off2) { + return false + } + if (s1 != s2) && (off1 == off2) { + return false + } + } + } + return true + } + if err := quick.Check(f, nil); err != nil { + fail("expected same offset") + } +} + // CheckByteStringIsNestedError verifies that a bytestring can not be created // inside another object. func CheckByteStringIsNestedError(fail func(string, ...interface{})) {