diff --git a/README.md b/README.md index 80bafae1..9e4ba50e 100644 --- a/README.md +++ b/README.md @@ -335,6 +335,20 @@ public partial class MyStringDictionary : Dictionary } ``` +Static constructor +--- +MemoryPackable class can not define static constructor because generated partial class uses it. Instead, you can define a `static partial void StaticConstructor()` to do the same thing. + +```csharp +[MemoryPackable] +public partial class CctorSample +{ + static partial void StaticConstructor() + { + } +} +``` + Polymorphism (Union) --- MemoryPack supports serializing interface and abstract class objects for polymorphism serialization. In MemoryPack this feature is called Union. Only interfaces and abstracts classes are allowed to be annotated with `[MemoryPackUnion]` attributes. Unique union tags are required. diff --git a/sandbox/SandboxConsoleApp/Program.cs b/sandbox/SandboxConsoleApp/Program.cs index 71652df8..e6aab77e 100644 --- a/sandbox/SandboxConsoleApp/Program.cs +++ b/sandbox/SandboxConsoleApp/Program.cs @@ -47,11 +47,26 @@ var span = CollectionsMarshal.AsSpan(value.Payload); + +[MemoryPackable] +public partial class CctorSample +{ + static partial void StaticConstructor() + { + } +} + [MemoryPackable] public partial class ListBytesSample { public int Id { get; set; } public List Payload { get; set; } + + static partial void StaticConstructor() + { + Console.WriteLine("foo"); + // throw new NotImplementedException(); + } } [MemoryPackable] diff --git a/src/MemoryPack.Generator/MemoryPackGenerator.Emitter.cs b/src/MemoryPack.Generator/MemoryPackGenerator.Emitter.cs index c0d3ccac..c4283cc7 100644 --- a/src/MemoryPack.Generator/MemoryPackGenerator.Emitter.cs +++ b/src/MemoryPack.Generator/MemoryPackGenerator.Emitter.cs @@ -350,10 +350,12 @@ public void Emit(StringBuilder writer, IGeneratorContext context) partial {{classOrStructOrRecord}} {{TypeName}} : IMemoryPackable<{{TypeName}}>{{fixedSizeInterface}} { {{EmitCustomFormatters()}} + static partial void StaticConstructor(); static {{Symbol.Name}}() { {{registerT}} + StaticConstructor(); } {{fixedSizeMethod}} [global::MemoryPack.Internal.Preserve] @@ -1194,9 +1196,12 @@ string EmitGenericCollectionTemplate(IGeneratorContext context) var code = $$""" partial class {{TypeName}} : IMemoryPackFormatterRegister { + static partial void StaticConstructor(); + static {{Symbol.Name}}() { {{register}} + StaticConstructor(); } {{staticRegisterFormatterMethod}}RegisterFormatter() diff --git a/src/MemoryPack.Generator/TypeScriptRuntime.cs b/src/MemoryPack.Generator/TypeScriptRuntime.cs index b7f303a7..f24bc3dc 100644 --- a/src/MemoryPack.Generator/TypeScriptRuntime.cs +++ b/src/MemoryPack.Generator/TypeScriptRuntime.cs @@ -283,6 +283,11 @@ public writeString(value: string | null): void { return; } + if (value.length == 0) { + this.writeCollectionHeader(0); + return; + } + // (int ~utf8-byte-count, int utf16-length, utf8-bytes) this.ensureCapacity(8 + ((value.length + 1) * 3));