Code Monkey home page Code Monkey logo

memorypack's People

Contributors

aarnott avatar dependabot[bot] avatar dustedham avatar filzrev avatar github-actions[bot] avatar guitarrapc avatar hadashia avatar hankovich avatar jasonxudeveloper avatar jodydonetti avatar joseftw avatar mihailskuzmins avatar neuecc avatar omurefeguclu avatar pcysl5edgo avatar rameel avatar rauhs avatar seunghulee avatar thorgeirk11 avatar timothymakkison avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

memorypack's Issues

wide Union tag

Currently only support byte.
add ushort,or uint tag support.

Support Order field on Members attributes

Like most serializers, it would be nice to have an attribute field specifying the order of that field instead of relying purely on C# member ordering.

[Member(Order=1)]

A plus would be interop with [DataContract], [DataMember] attributes.

[MemoryPackUnionFormatter] (net7.0) yields compiling error: CS8987 The ‘scoped’ modifier of parameter ‘value’ doesn’t match overridden or implemented member

I have various Types defined in 3 libs, namely Model, Man, Config, and these types are finally used in the lib: Server
i.e. Server depends on Model, Man, Config, otherwise Man and Config depends on Model.
And, All these Types inherits a single interface IMyMemoryPackable defined in Model.

I wrote a MyMemoryPackableFormtter.cs in lib Server like this to register all these types:

[MemoryPackUnionFormatter(typeof(IMyMemoryPackable))]
    [MemoryPackUnion(0, typeof(Type1))]
    [MemoryPackUnion(1, typeof(Type2))]
    [MemoryPackUnion(2, typeof(Type3))]
    public partial class MyMemoryPackableFormatter
    {
    }

but compiler yields:
Server (net7.0) :
compiling error: CS8987 The ‘scoped’ modifier of parameter ‘value’ doesn’t match overridden or implemented member

However,
if i split this MyMemoryPackableFormatter into three separate Formatters(note all these formatters register for the same interface, namely IMyMemoryPackable) into three libs (no matter their names r the same or not), the compiler compiles OK and the program can launch, but the generated code seems only to use one Formatter to do serialize Job (other Types cannot be found ).

the "new" keyword causing member to be initialized twice in generated code.

if u have a member in a MemoryPackable type like this,
public new string Description { get; set; }

u'll get this in generated code:

   [global::MemoryPack.Internal.Preserve]
    public static void Deserialize(ref MemoryPackReader reader, scoped ref PluginInfo? value)
    {

        if (!reader.TryReadObjectHeader(out var count))
        {
            value = default!;
            goto END;
        }


        string __Description;
    ...
        string __Description;
     ...
}

MEMPACK019 when compiling a subclass inherited from Dictionary or ConcurrentDictionary.

MEMPACK019 The MemoryPackable object 'ConfigDictionary' member 'Comparer' type 'global::System.Collections.Generic.IEqualityComparer' is not MemoryPackable. Annotate [MemoryPackable] to 'global::System.Collections.Generic.IEqualityComparer' or if external type that can serialize, annotate [MemoryPackAllowSerialize] to member ....

"Comparer" seems a protected member of Dictionary or ConcurrentDictionary.

[MemoryPackable]
    public partial class ConfigDictionary<T> : Dictionary<string, T>
 {
}

Support for missing / deleted properties

Hi, the Version tolerant section mentions that

MemoryPackable objects, members can be added, but not deleted

I'm trying to use MemoryPack for RPC between two sides that should support different versions.

If I add a property to one side, serialize it, and send it to the other side which doesn't have the added property yet, deserialization crashes in MemoryPackSerializationException.ThrowInvalidPropertyCount.

It's a bit confusing, because technically I added a property, but for the deserializer it's as if I deleted it, which is not supported. Would it be possible to ignore deleted properties?

FluentAPI support?

In the readme you explain that we need to add [MemoryPackable] attribute. I want to avoid this and have clean classes and add such thing via FluentAPI like EF does. Is this already supported or will this be supported?

Unsafe.dll not included in the unitypackage?

The documentation says "The dependency managed DLL System.Runtime.CompilerServices.Unsafe/6.0.0 is included with unitypackage", but v1.4.2 Unsafe.dll was not included with unitypackage.

I attached the import screen of MemoryPack v1.4.2 unitypackage for your reference.

image

Why allocating if value is unmanaged?

Hi, about this code:

public static byte[] Serialize<T>(in T? value, MemoryPackSerializerOptions? options = default)
    {
        if (!RuntimeHelpers.IsReferenceOrContainsReferences<T>())
        {
            var array = AllocateUninitializedArray<byte>(Unsafe.SizeOf<T>());
            Unsafe.WriteUnaligned(ref GetArrayDataReference(array), value);
            return array;
        }

I am not sure why ReusableLinkedArrayBufferWriter is not used for this case too. wouldn't this mean a certain allocation?

Breaking change of binary format, add tuple type

Currently tuple is serialized:

  • If all T is unmanaged, serialize as unamanged struct
  • If T has included reference type, serialize as object format(add object header)

Shouldn't we have a type that is serialized as a continuous value with no object header?

Another possible bug

Thank you for the fast fix on my last issue. But when that was solved is stumbled on another edge case with int. I think the problem occurs when deserializing to a primitive type without generics so my best guess is that it is some sort of boxing issue but I failed to narrow it down further. Fortunately the issue can be recreated with the following code

        var buff = MemoryPackSerializer.Serialize<int>(0);
        var thisWorks = MemoryPackSerializer.Deserialize<int>(buff);
        var thisThrows = MemoryPackSerializer.Deserialize( typeof(int), buff);

If this isn't valid code just close the issue, thanks in advance/ Mattias

netstandard2.1 compiling error: CS8987 The ‘scoped’ modifier of parameter ‘value’ doesn’t match overridden or implemented member

when work with netstandard2.1, the compiler reports on the generated code:
CS8987 The ‘scoped’ modifier of parameter ‘value’ doesn’t match overridden or implemented member.

how to solve this and get MemoryPack work with netstandard2.1?
since i've already dual-targeted both netstandard2.1 and net7.0, and this compiler error prevents my netstandard2.1 library to be compiled.

partial class Stat
{
    [global::MemoryPack.Internal.Preserve]
    sealed class StatFormatter : MemoryPackFormatter<Stat>
    {
        [global::MemoryPack.Internal.Preserve]
        public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer,  ref Stat value)            <-- here
        {
            Stat.Serialize(ref writer, ref value);
        }

        [global::MemoryPack.Internal.Preserve]
        public override void Deserialize(ref MemoryPackReader reader, ref Stat value)           <-- and here
        {
            Stat.Deserialize(ref reader, ref value);
        }
    }
}

Serialization of `List<T>` and `Dictionary<K,V>` fails on Unity + IL2CPP

I executed the following code on an IL2CPP built Android app and got an exception.

I built the app with Unity 2021.3.6f1, and executed it on Pixel 4a(Android) & iPhoneX(iOS).
Managed stripping code level set to minimal.

// List<T> case
var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);

var bin = MemoryPackSerializer.Serialize(list); // Caught an exception here.
var val = MemoryPackSerializer.Deserialize<List<int>>(bin);
Autoconnected Player "Autoconnected Player" ExecutionEngineException: Attempting to call method 'MemoryPack.Formatters.UnmanagedFormatter`1<System.Int32>::Serialize<MemoryPack.Internal.ReusableLinkedArrayBufferWriter>' for which no ahead of time (AOT) code was generated.  Consider increasing the --generic-virtual-method-iterations=1 argument
  at MemoryPack.Formatters.ListFormatter`1[T].Serialize[TBufferWriter] (MemoryPack.MemoryPackWriter`1[TBufferWriter]& writer, System.Collections.Generic.List`1[T]& value) [0x00000] in <00000000000000000000000000000000>:0 
  at MemoryPack.MemoryPackSerializer.Serialize[T,TBufferWriter] (MemoryPack.MemoryPackWriter`1[TBufferWriter]& writer, T& value) [0x00000] in <00000000000000000000000000000000>:0 
  at MemoryPack.MemoryPackSerializer.Serialize[T] (T& value, MemoryPack.MemoryPackSerializeOptions options) [0x00000] in <00000000000000000000000000000000>:0 
  at MemoryPackCheck.Start () [0x00000] in <00000000000000000000000000000000>:0 
MemoryPackCheck:Start()
// Dictionary<K,V> case
var dict = new Dictionary<int, string>();
dict[1] = "one";
dict[2] = "two";
dict[3] = "three";

var bin = MemoryPackSerializer.Serialize(dict);  // Caught an exception here.
var val = MemoryPackSerializer.Deserialize<Dictionary<int, string>>(bin);
Autoconnected Player "Autoconnected Player" ExecutionEngineException: Attempting to call method 'MemoryPack.Formatters.KeyValuePairFormatter`2<System.Int32, System.String>::Serialize<MemoryPack.Internal.ReusableLinkedArrayBufferWriter>' for which no ahead of time (AOT) code was generated.  Consider increasing the --generic-virtual-method-iterations=1 argument
  at MemoryPack.Formatters.DictionaryFormatter`2[TKey,TValue].Serialize[TBufferWriter] (MemoryPack.MemoryPackWriter`1[TBufferWriter]& writer, System.Collections.Generic.Dictionary`2[TKey,TValue]& value) [0x00000] in <00000000000000000000000000000000>:0 
  at MemoryPack.MemoryPackSerializer.Serialize[T,TBufferWriter] (MemoryPack.MemoryPackWriter`1[TBufferWriter]& writer, T& value) [0x00000] in <00000000000000000000000000000000>:0 
  at MemoryPack.MemoryPackSerializer.Serialize[T] (T& value, MemoryPack.MemoryPackSerializeOptions options) [0x00000] in <00000000000000000000000000000000>:0 
  at MemoryPackCheck.Start () [0x00000] in <00000000000000000000000000000000>:0 
MemoryPackCheck:Start()
// List<T> property case
[MemoryPackable]
public partial class MyContainer2
{
    public List<int> List = new List<int>();
}

var container = new MyContainer2();

container.List.Add(1);
container.List.Add(2);
container.List.Add(3);

var bin = MemoryPackSerializer.Serialize(container);  // Caught an exception here.
var val = MemoryPackSerializer.Deserialize<MyContainer2>(bin);
Autoconnected Player "Autoconnected Player" ExecutionEngineException: Attempting to call method 'MemoryPack.Formatters.UnmanagedFormatter`1<System.Int32>::Serialize<MemoryPack.Internal.ReusableLinkedArrayBufferWriter>' for which no ahead of time (AOT) code was generated.  Consider increasing the --generic-virtual-method-iterations=1 argument
  at MemoryPack.Formatters.ListFormatter`1[T].Serialize[TBufferWriter] (MemoryPack.MemoryPackWriter`1[TBufferWriter]& writer, System.Collections.Generic.List`1[T]& value) [0x00000] in <00000000000000000000000000000000>:0 
  at MemoryPack.MemoryPackSerializer.Serialize[T,TBufferWriter] (MemoryPack.MemoryPackWriter`1[TBufferWriter]& writer, T& value) [0x00000] in <00000000000000000000000000000000>:0 
  at MemoryPack.MemoryPackSerializer.Serialize[T] (T& value, MemoryPack.MemoryPackSerializeOptions options) [0x00000] in <00000000000000000000000000000000>:0 
  at MemoryPackCheck.Start () [0x00000] in <00000000000000000000000000000000>:0 
MemoryPackCheck:Start()
// Dictionary<K,V> property case
[MemoryPackable]
public partial class MyContainer
{
    public Dictionary<int, string> Dict = new Dictionary<int, string>();
}

var container = new MyContainer();

container.Dict[1] = "One";
container.Dict[2] = "Two";
container.Dict[3] = "Three";

var bin = MemoryPackSerializer.Serialize(container);  // Caught an exception here.
var val = MemoryPackSerializer.Deserialize<MyContainer>(bin);
Autoconnected Player "Autoconnected Player" ExecutionEngineException: Attempting to call method 'MemoryPack.Formatters.KeyValuePairFormatter`2<System.Int32, System.String>::Serialize<MemoryPack.Internal.ReusableLinkedArrayBufferWriter>' for which no ahead of time (AOT) code was generated.  Consider increasing the --generic-virtual-method-iterations=1 argument
  at MemoryPack.Formatters.DictionaryFormatter`2[TKey,TValue].Serialize[TBufferWriter] (MemoryPack.MemoryPackWriter`1[TBufferWriter]& writer, System.Collections.Generic.Dictionary`2[TKey,TValue]& value) [0x00000] in <00000000000000000000000000000000>:0 
  at MemoryPack.MemoryPackSerializer.Serialize[T,TBufferWriter] (MemoryPack.MemoryPackWriter`1[TBufferWriter]& writer, T& value) [0x00000] in <00000000000000000000000000000000>:0 
  at MemoryPack.MemoryPackSerializer.Serialize[T] (T& value, MemoryPack.MemoryPackSerializeOptions options) [0x00000] in <00000000000000000000000000000000>:0 
  at MemoryPackCheck.Start () [0x00000] in <00000000000000000000000000000000>:0 
MemoryPackCheck:Start()

Add a new constructor for MemoryPackUnionAttribute by using FullName,Assembly info of a type in addition to typeof(Type)

Suggested new constructor: [MemoryPackUnion(0, "MyNamespace.MyType, MyAssemblyName")]

this is useful when the implementing type is not in the same assembly with the Interface, which is usually isolated from its implementation and MemoryPackUnionAttribute may not possibly make a reference to it by typeof() operator.

this is a similar measure in:
[Editor("MyNamespace.ByteArrayEditor, MyAssemblyName", "System.Drawing.Design.UITypeEditor, System.Windows.Forms")]

Bug: failed System.TypeLoadException

The HostOptions.BackgroundServiceExceptionBehavior is configured to StopHost. A BackgroundService has thrown an unhandled exception, and the IHost instance is stopping. To avoid this behavior, configure this to Ignore; however the BackgroundService will not be restarted. System.TypeLoadException: Virtual static method 'Serialize' is not implemented on type 'SystemModule.Packets.ServerPackets.ServerDataMessage' from assembly 'SystemModule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

TODO

Can an extra interface representing the abstract for all MemoryPackable types be added ?

CASE: I need to serialize any MemoryPackable objects using an array or colleciton but seems not possible, cos the most abstract interface IMemoryPackFormatterRegister has a static member, which can not be used as a type parameter.

I think a more abstract interface without static member could solve this problem, couldn't it?

SUGGEST:

namespace MemoryPack
{
    public interface IMemoryPackFormatterRegister: IMemoryPackObject
    {
        static void RegisterFormatter();
    }


    public interface IMemoryPackObject {} 

}



lexically, i prefer the name IMemoryPackable, but it was already used.
A more reasonable hierachy might be IMemoryPackObject: IMemoryPackFormatterRegister : IMemoryPackable

GeneratedRegex or RegexGenerator?

Hi. I just cloned the repo and tried to build with .net 7.0.100-preview.7.22377.5 and got this error:

error CS0246: The type or namespace name 'GeneratedRegexAttribute' could not be found (are you missing a using directive or an assembly reference?)

[GeneratedRegex(@", Version=\d+.\d+.\d+.\d+, Culture=[\w-]+, PublicKeyToken=(?:null|[a-f0-9]{16})")]

But when I replace GeneratedRegex with RegexGenerator It builds successfully.

Integration with MagicOnion

Will there be integration with MagicOnion?
I would like to see an example in ASP Net with zero allocation for objects of a value type, for example structures.

Net 6 Support

Hello, this is a pretty good project for dotneters. However, since Net6 is the newest LTS, is there any possibility of adding support for Net6 with the help of other packages? Thanks.

Endianness

I think we should force little endian

Unity support

I’m curious if supporting a lower version is possible? If we target C# 9/.NET Standard 2.1/Roslyn 3.9.0 we can support Unity. @neuecc I know you already know all of this, I’m just curious what features from C# 11/.NET 7 are required. Thanks.

HttpClient Example for SandboxWebApp

Hello,

I am trying to write a c# console app client for the SandboxWebApp using HttpClient, but so far i have no been sucessful.

How can i use the HttpClient for calling this endpoint?

This is the code for my console app that I am testing:

using MemoryPack;

TestModel value = new() { Id = Guid.NewGuid(), Name = "Test" };


var bin = MemoryPackSerializer.Serialize(value);

HttpClient httpClient = new();

HttpRequestMessage request = new() {
    Content = new ByteArrayContent(bin),
    RequestUri= new Uri("http://localhost:5173"),
    Method= HttpMethod.Post
};

request.Headers.TryAddWithoutValidation("Content-Type", "application/x-memorypack");

var response = await httpClient.SendAsync(request);



[MemoryPackable]
public partial class TestModel
{
    public Guid Id { get; set; }

    public string? Name { get; set; }

}

How to mark up external objects (ie Unity Vector3, etc)

Hi,

This looks great and congrats on the new library. It's clear you've been using this library in Unity projects so I hope there is a simple answer here: If one uses Newtonsoft .NET JSON serializer in a Unity project you typically have to define some custom contracts to properly serialize various Unity structs and classes that are common to add to serialized data. For example an AnimationCurve.
Does MemoryPack have a similar ability to mark up or write contracts for external C# structures that we cannot access?

Typescript casing

I have testet out the library, it's fantastic :)
Is there any way to control the casing of generated typescript models?

TypeScript generator does not generate serializers and enums

I was impressed by how amazing this library is!!
And, even more, after seeing that TypeScript would be supported.

Bug description

I don't know yet if there is a problem with the latest versions, but it looks like the generator is not generating the runtime and dependent files.

image

Expected behavior

  • Runtime should be emitted;
  • Dependent types should also be generated.

Working version

Version 1.8.6 is working as expected.

.NET 7 Native AOT error: Generic virtual method pointer lookup failure

First, thanks for updating MemoryPack to work with .NET 7 and AOT.
Unfortunately my native AOT test program (latest .NET 7) is crashing with the error below:
image

(it works OK in debug and release mode in Visual Studio, but crashes only after publishing and running the AOT executable)

Here is the full test code:

using MemoryPack;

namespace Tests
{
    [MemoryPackable]
    public partial class MemPackObject
    {
        public string TestString { get; set; }
    }

    class MemPackTest
    {
        static void Main(string[] args)
        {
            MemPackObject test_object = new MemPackObject();
            test_object.TestString = "ABC";
            Console.WriteLine("Initial value before serializing: " + test_object.TestString);

            byte[] serialized_object = MemoryPackSerializer.Serialize(test_object);
            MemPackObject? deserialized_object = MemoryPackSerializer.Deserialize<MemPackObject>(serialized_object);

            if (deserialized_object != null)
            {
                Console.WriteLine("Final value after deserializing: " + deserialized_object.TestString);
            }

            Console.WriteLine("Test completed. Press any key to exit");
            Console.ReadKey();
        }

    }
}

MemoryPackable Class cannot be deserialized to MemoryPackable Subclass?

ClassA
{
}

ClassB : ClassA
{
// ClassB may have some extra properties in addtion to ClassA
}


ClassA objectA = new();


ClassB objectB =  MemoryPackSerializer.Deserialize<ClassB>(MemoryPackSerializer.Serialize(objectA));

this throws exception:

MemoryPack.MemoryPackSerializationException:“Length header size is larger than buffer size, length: 2048.

Why?

Support external union metadata

It is impossible to serialize classes that are defined in external libraries, so it would be nice if you could provide the same information as MemoryPackUnion, but via a builder system instead.

From your own example. Instead of doing this:

[MemoryPackable]
[MemoryPackUnion(0, typeof(FooClass))]
[MemoryPackUnion(1, typeof(BarClass))]
public partial interface IUnionSample { }

[MemoryPackable]
public partial class FooClass : IUnionSample { }

[MemoryPackable]
public partial class BarClass : IUnionSample { }

It would be nice to do this:

These 3 classes are provided by an external library that can't take a dependency on MemoryPack. so they look like this (in the library):

public interface IUnionSample { }
public class FooClass : IUnionSample { }
public class BarClass : IUnionSample { }

Since they are not partial, we can't use source generator etc. - instead we create a custom formatter. But in order to support union/polymorphism, we need to provide the inheritance relationships somehow. It could be done like this:

UnionBuilder ub = new UnionBuilder(typeof(IUnionSample));
ub.AddUnion(0, typeof(FooClass));
ub.AddUnion(1, typeof(BarClass));

//Then we provide 'ub' to the serializer in some way.

Note that I just come up with an example on the spot. I have no preference for how the above is achieved.

Possible bug

Hi and thanks for your work to provide super-fast serializers for c#.
When testing a migration from MessagePack to MemoryPack I think I stumbled upon a possible bug when serializing a int into IBufferWriter.

I think the trouble is on row 86 in MemoryPackSerializer.Serialize.cs where Advance(span.Length) is called but the span.Length can be much larger than the serialized data since its legal for IBufferWriter.GetSpan() on row 84 to return a larger span than requested.

Hope I'm describing the issue I am seeing well enough /Mattias

Feature proposal: Formatter Merging, to support assembly dependency architecture and assemblies loaded during runtime(such as plugin)

AssemblyA:

[MemoryPackUnionFormatter(typeof(IPlugin))]
 [MemoryPackUnion(0, typeof(Plugin1))]
 [MemoryPackUnion(1, typeof(Plugin2))]
 public partial class PluginFormatter
 { }

AssemblyB:

[MemoryPackUnionFormatter(typeof(IPlugin))]
[MemoryPackUnion(2, typeof(Plugin3))]
[MemoryPackUnion(3, typeof(Plugin4))]
public partial class PluginFormatter
{ }

Question: Is it possible to merge the MemoryPackUnionFormatters declared in different assemblies (like above) referencing the same interface with/without same class names?
The underlying solution might be allowing formatters for each interface be registered more than once and merge the types into one type dictionary (together with their tags) or be search through a hierachy of dicitonaries.

This solves following issue:

  1. MemoryPackUnionFormatter must be centralized in the final consumer libs, and cannot be distributed in different assemblies, if these libs r used by different programs, each program must write their own formatter (a lot of redundency work), why can not the type registration be done by each assembly on module basis and they merge to one when compiled, while programmers can negotiate tag segments for each assembly to avoid conflicts, like 1-10 for assembly one, 20-30 for another?

  2. Unreferenced types(with known interface) declared in plugin assembly r not applicable for MemoryPack, cos they r not pre-registered in the host program, but what if their types come as compiled with MemoryPack with code already generated?

Unable to compile when [MemoryPackable] class has multiple constructors

I'm testing MemoryPack (latest .NET 7) with a class that has multiple constructors, and I marked one of the constructors as '[MemoryPackConstructor]'.
However, the project doesn't compile and shows an error during compilation:
"Error CS0234 The type or namespace name 'Formatters' does not exist in the namespace 'Tests.MemoryPack' (are you missing an assembly reference?)"

And it points to line 44 in generated code:
image

Here is my full test code:

using MemoryPack;

namespace Tests.MemoryPack
{
    [MemoryPackable]
    public partial class TestObject
    {
        public string testString { get; set; } = "";


        [MemoryPackConstructor]
        public TestObject() { }

        public TestObject(string ignore) { }
    }

    class MemPackTest
    {
        public static void Main()
        {
            TestObject test_object = new();
            test_object.testString = "ABC";
            Console.WriteLine("Initial value before serializing: " + test_object.testString);

            byte[] serialized_object = MemoryPackSerializer.Serialize(test_object);
            TestObject? deserialized_object = MemoryPackSerializer.Deserialize<TestObject>(serialized_object);

            if (deserialized_object != null)
            {
                Console.WriteLine("Final value after deserializing: " + deserialized_object.testString);
            }

            Console.WriteLine("Test completed. Press any key to exit");
            Console.ReadKey();
        }

    }
}

Support for serializing to Spans

I propose new overloads for Serialize and Deserialize which operate on a Span<Byte> and ReadOnlySpan<T>, respectively.

Additionally, a new method would be required which returns the calculated size of the serialized object. Something like GetSerializedByteLength.

Together, it would enable zero-allocation serialization on the stack like this:

const int maxStackAllocSize = 4096;
var length = MemoryPackSerializer.GetSerializedByteLength(v);
Span<byte> buf = length <= maxStackAllocSize ? stackalloc Byte[length] : new Byte[length];
MemoryPackSerializer.Serialize(v, buf);
var val = MemoryPackSerializer.Deserialize<Person>(bin, buf);

__typeToTag.TryGetValue(value.GetType(), out var tag) cannot identify the same Type created in a plugin.

if u have a type used in a plugin (i.e. dynamically loaded assembly) while registered with [MemoryPackUnionFormatter] in the host program, the following line in in the generated code seems unable to get the Type, even The type names are same.

if (__typeToTag.TryGetValue(value.GetType(), out var tag))

this is possibly because the Type registered in __typeToTag is not the same object with value.GetType(), even though their FullNames and GUIDs r the same, for the former was instantiated at host launch, but the latter was instantiated when load the plugin.

is it better to use type GUID as Key?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.