From 96d438df47d29cf16ddbeca67b2ddd12b2b7bf2b Mon Sep 17 00:00:00 2001 From: Michael Le Date: Thu, 22 Dec 2022 15:28:00 -0500 Subject: [PATCH] Perform nil check on string fields when packing (#7719) Co-authored-by: Derek Bailey --- src/idl_gen_go.cpp | 7 +++++-- tests/MyGame/Example/Monster.go | 5 ++++- tests/MyGame/Example/Stat.go | 5 ++++- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/idl_gen_go.cpp b/src/idl_gen_go.cpp index 0a04f19c4..15d0a1c94 100644 --- a/src/idl_gen_go.cpp +++ b/src/idl_gen_go.cpp @@ -1054,8 +1054,11 @@ class GoGenerator : public BaseGenerator { const std::string offset = field_var + "Offset"; if (IsString(field.value.type)) { - code += - "\t" + offset + " := builder.CreateString(t." + field_field + ")\n"; + code += "\t" + offset + " := flatbuffers.UOffsetT(0)\n"; + code += "\tif t." + field_field + " != \"\" {\n"; + code += "\t\t" + offset + " = builder.CreateString(t." + field_field + + ")\n"; + code += "\t}\n"; } else if (IsVector(field.value.type) && field.value.type.element == BASE_TYPE_UCHAR && field.value.type.enum_def == nullptr) { diff --git a/tests/MyGame/Example/Monster.go b/tests/MyGame/Example/Monster.go index 0717aa676..5380e1350 100644 --- a/tests/MyGame/Example/Monster.go +++ b/tests/MyGame/Example/Monster.go @@ -74,7 +74,10 @@ type MonsterT struct { func (t *MonsterT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { if t == nil { return 0 } - nameOffset := builder.CreateString(t.Name) + nameOffset := flatbuffers.UOffsetT(0) + if t.Name != "" { + nameOffset = builder.CreateString(t.Name) + } inventoryOffset := flatbuffers.UOffsetT(0) if t.Inventory != nil { inventoryOffset = builder.CreateByteString(t.Inventory) diff --git a/tests/MyGame/Example/Stat.go b/tests/MyGame/Example/Stat.go index d7976cd7b..9c0821419 100644 --- a/tests/MyGame/Example/Stat.go +++ b/tests/MyGame/Example/Stat.go @@ -14,7 +14,10 @@ type StatT struct { func (t *StatT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { if t == nil { return 0 } - idOffset := builder.CreateString(t.Id) + idOffset := flatbuffers.UOffsetT(0) + if t.Id != "" { + idOffset = builder.CreateString(t.Id) + } StatStart(builder) StatAddId(builder, idOffset) StatAddVal(builder, t.Val)