diff --git a/net/FlatBuffers/FlatBufferBuilder.cs b/net/FlatBuffers/FlatBufferBuilder.cs index 93f72be34..908352d4d 100644 --- a/net/FlatBuffers/FlatBufferBuilder.cs +++ b/net/FlatBuffers/FlatBufferBuilder.cs @@ -16,6 +16,7 @@ using System; +using System.Collections.Generic; using System.Text; /// @file @@ -47,6 +48,9 @@ namespace FlatBuffers // For the current vector being built. private int _vectorNumElems = 0; + // For CreateSharedString + private Dictionary _sharedStringMap = null; + /// /// Create a FlatBufferBuilder with a given initial size. /// @@ -579,6 +583,32 @@ namespace FlatBuffers } #endif + /// + /// Store a string in the buffer, which can contain any binary data. + /// If a string with this exact contents has already been serialized before, + /// instead simply returns the offset of the existing string. + /// + /// The string to encode. + /// + /// The offset in the buffer where the encoded string starts. + /// + public StringOffset CreateSharedString(string s) + { + if (_sharedStringMap == null) + { + _sharedStringMap = new Dictionary(); + } + + if (_sharedStringMap.ContainsKey(s)) + { + return _sharedStringMap[s]; + } + + var stringOffset = CreateString(s); + _sharedStringMap.Add(s, stringOffset); + return stringOffset; + } + /// @cond FLATBUFFERS_INTERNAL // Structs are stored inline, so nothing additional is being added. // `d` is always 0. diff --git a/tests/FlatBuffers.Test/FlatBuffersFuzzTests.cs b/tests/FlatBuffers.Test/FlatBuffersFuzzTests.cs index 2d411a2b2..1bb391423 100644 --- a/tests/FlatBuffers.Test/FlatBuffersFuzzTests.cs +++ b/tests/FlatBuffers.Test/FlatBuffersFuzzTests.cs @@ -135,6 +135,17 @@ namespace FlatBuffers.Test }, builder.DataBuffer.ToFullArray()); } + [FlatBuffersTestMethod] + public void TestCreateSharedAsciiString() + { + var builder = new FlatBufferBuilder(1); + builder.CreateSharedString("foo"); + Assert.ArrayEqual(new byte[] { 3, 0, 0, 0, (byte)'f', (byte)'o', (byte)'o', 0 }, builder.DataBuffer.ToFullArray()); + + builder.CreateSharedString("foo"); + Assert.ArrayEqual(new byte[] { 3, 0, 0, 0, (byte)'f', (byte)'o', (byte)'o', 0 }, builder.DataBuffer.ToFullArray()); + } + [FlatBuffersTestMethod] public void TestCreateArbitarytring() {