Skip to content

Commit

Permalink
Merge branch 'main' into fix-union-value
Browse files Browse the repository at this point in the history
  • Loading branch information
sssooonnnggg authored Oct 29, 2024
2 parents f0f6361 + a86c8ae commit 0a49018
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/FlatSharp.Compiler/SchemaModel/IFlatSharpAttributes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
* limitations under the License.
*/

using System.Text.RegularExpressions;
using FlatSharp.Attributes;
namespace FlatSharp.Compiler.SchemaModel;

Expand Down Expand Up @@ -63,6 +64,14 @@ public static void EmitAsMetadata(this IFlatSharpAttributes attributes, CodeWrit
string key = pair.Key;
string? value = pair.Value.Value;

// Prepend backslash to escape backslashes and quotes:
// \ => \\
// " => \"
if (value is not null)
{
value = Regex.Replace(value!, "([\\\\\"])", "\\${1}");
}

writer.AppendLine($"[FlatBufferMetadataAttribute(FlatBufferMetadataKind.FbsAttribute, \"{key}\", \"{value}\")]");
}
}
Expand Down
44 changes: 44 additions & 0 deletions src/Tests/FlatSharpCompilerTests/EscapedCharInAttributeTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
namespace FlatSharpTests
{
public class EscapedCharInAttributeTests
{
[Fact]
public void EscapedCharInAttribute_DoubleQuote()
{
string schema = "namespace ns;attribute custom;table Foo { Bar : int (custom: \"hello,\\\"world\\\"\"); }";

var assembly = FlatSharpCompiler.CompileAndLoadAssembly(schema, new());
var foo = assembly.GetType("ns.Foo");
var bar = foo.GetProperty("Bar");
var metaAttr = bar.GetCustomAttribute<FlatBufferMetadataAttribute>();
Assert.NotNull(metaAttr.Value);
Assert.Equal("hello,\"world\"", metaAttr.Value.ToString());
}

[Fact]
public void EscapedCharInAttribute_SingleQuote()
{
string schema = "namespace ns;attribute custom;table Foo { Bar : int (custom: \"hello,'world'\"); }";

var assembly = FlatSharpCompiler.CompileAndLoadAssembly(schema, new());
var foo = assembly.GetType("ns.Foo");
var bar = foo.GetProperty("Bar");
var metaAttr = bar.GetCustomAttribute<FlatBufferMetadataAttribute>();
Assert.NotNull(metaAttr.Value);
Assert.Equal("hello,'world'", metaAttr.Value.ToString());
}

[Fact]
public void EscapedCharInAttribute_BackSlash()
{
string schema = "namespace ns;attribute custom;table Foo { Bar : int (custom: \"hello,\\\\world\"); }";

var assembly = FlatSharpCompiler.CompileAndLoadAssembly(schema, new());
var foo = assembly.GetType("ns.Foo");
var bar = foo.GetProperty("Bar");
var metaAttr = bar.GetCustomAttribute<FlatBufferMetadataAttribute>();
Assert.NotNull(metaAttr.Value);
Assert.Equal("hello,\\world", metaAttr.Value.ToString());
}
}
}

0 comments on commit 0a49018

Please sign in to comment.