Commit 51dd733b authored by mugisoba's avatar mugisoba Committed by Wouter van Oortmerssen

[C#] add FlatBuffersBuilder.CreateSharedString (#5372)

parent 79f0df3d
......@@ -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<string, StringOffset> _sharedStringMap = null;
/// <summary>
/// Create a FlatBufferBuilder with a given initial size.
/// </summary>
......@@ -579,6 +583,32 @@ namespace FlatBuffers
}
#endif
/// <summary>
/// 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.
/// </summary>
/// <param name="s">The string to encode.</param>
/// <returns>
/// The offset in the buffer where the encoded string starts.
/// </returns>
public StringOffset CreateSharedString(string s)
{
if (_sharedStringMap == null)
{
_sharedStringMap = new Dictionary<string, StringOffset>();
}
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.
......
......@@ -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()
{
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment