diff --git a/Nino.unitypackage b/Nino.unitypackage new file mode 100644 index 0000000..9875b7f Binary files /dev/null and b/Nino.unitypackage differ diff --git a/Nino_Unity/Assets/Nino/Editor/SerializationHelper.cs b/Nino_Unity/Assets/Nino/Editor/SerializationHelper.cs deleted file mode 100644 index 84d97e5..0000000 --- a/Nino_Unity/Assets/Nino/Editor/SerializationHelper.cs +++ /dev/null @@ -1,43 +0,0 @@ -#if UNITY_2017_1_OR_NEWER -using System.IO; -using System.Linq; -using UnityEditor; -using System.Reflection; -using Nino.Serialization; - -namespace Nino.Editor -{ - public static class SerializationHelper - { - /// - /// External DLL, such as ILRuntime/huatuo hot update dll - /// 外部dll,例如ILRuntime和huatuo的热更dll - /// - private static readonly string[] ExternalDLLPath = new string[] - { -#if ILRuntime - "Assets/Nino/Test/Editor/Serialization/Test11.bytes" -#endif - }; - - /// - /// Export path, you can change this to export it anywhere under Assets directory - /// If you want to export outside of Assets, you can use ../ - /// 导出目录,你可以修改这个路径,代码会生成到Assets目录下你指定的这个路径内 - /// 如果需要导出到Assets外部,可以在路径内写入../ - /// - private const string ExportPath = "Nino/Generated"; - - [MenuItem("Nino/Generator/Serialization Code")] - public static void GenerateSerializationCode() - { - var assemblies = System.AppDomain.CurrentDomain.GetAssemblies().ToList(); - assemblies.AddRange(ExternalDLLPath.Select(s => Assembly.Load(File.ReadAllBytes(s)))); - // ReSharper disable RedundantArgumentDefaultValue - CodeGenerator.GenerateSerializationCodeForAllTypePossible(ExportPath, assemblies.ToArray()); - AssetDatabase.Refresh(); - // ReSharper restore RedundantArgumentDefaultValue - } - } -} -#endif \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Generated/Nino_Test_BuildTestDataCodeGen_Serialize.cs b/Nino_Unity/Assets/Nino/Generated/Nino_Test_BuildTestDataCodeGen_Serialize.cs deleted file mode 100644 index e7acec1..0000000 --- a/Nino_Unity/Assets/Nino/Generated/Nino_Test_BuildTestDataCodeGen_Serialize.cs +++ /dev/null @@ -1,94 +0,0 @@ -/* this is generated by nino */ -using System.Runtime.CompilerServices; - -namespace Nino.Test -{ - public partial class BuildTestDataCodeGen - { - public static BuildTestDataCodeGen.SerializationHelper NinoSerializationHelper = new BuildTestDataCodeGen.SerializationHelper(); - public unsafe class SerializationHelper: Nino.Serialization.NinoWrapperBase - { - #region NINO_CODEGEN - public SerializationHelper() - { - - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override void Serialize(BuildTestDataCodeGen value, ref Nino.Serialization.Writer writer) - { - if(value == null) - { - writer.Write(false); - return; - } - writer.Write(true); - writer.Write(ref value.a, sizeof(System.Byte),ref value.b, sizeof(System.SByte),ref value.c, sizeof(System.Int16),ref value.d, sizeof(System.UInt16),ref value.e, sizeof(System.Int32),ref value.f, sizeof(System.UInt32),ref value.g, sizeof(System.Int64),ref value.h, sizeof(System.UInt64)); - writer.Write(ref value.i, sizeof(System.Single),ref value.j, sizeof(System.Double),ref value.k, sizeof(System.Decimal),ref value.l, sizeof(System.Boolean),ref value.m, sizeof(System.Char)); - writer.Write(value.n); - writer.Write(value.o); - writer.Write(value.p); - writer.Write(value.q); - writer.Write(value.r); - writer.Write(value.s); - writer.Write(value.t); - writer.Write(value.u); - writer.Write(value.v); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override BuildTestDataCodeGen Deserialize(Nino.Serialization.Reader reader) - { - if(!reader.ReadBool()) - return null; - BuildTestDataCodeGen value = new BuildTestDataCodeGen(); - reader.Read(ref value.a, sizeof(System.Byte),ref value.b, sizeof(System.SByte),ref value.c, sizeof(System.Int16),ref value.d, sizeof(System.UInt16),ref value.e, sizeof(System.Int32),ref value.f, sizeof(System.UInt32),ref value.g, sizeof(System.Int64),ref value.h, sizeof(System.UInt64)); - reader.Read(ref value.i, sizeof(System.Single),ref value.j, sizeof(System.Double),ref value.k, sizeof(System.Decimal),ref value.l, sizeof(System.Boolean),ref value.m, sizeof(System.Char)); - value.n = reader.ReadString(); - value.o = reader.ReadList(); - value.p = reader.ReadList(); - value.q = reader.ReadArray(); - value.r = reader.ReadArray(); - value.s = reader.ReadDictionary(); - value.t = reader.ReadDictionary(); - value.u = reader.ReadDictionary(); - value.v = reader.ReadDictionary(); - return value; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override int GetSize(BuildTestDataCodeGen value) - { - if(value == null) - { - return 1; - } - int ret = 1; - ret += Nino.Serialization.Serializer.GetSize(value.a); - ret += Nino.Serialization.Serializer.GetSize(value.b); - ret += Nino.Serialization.Serializer.GetSize(value.c); - ret += Nino.Serialization.Serializer.GetSize(value.d); - ret += Nino.Serialization.Serializer.GetSize(value.e); - ret += Nino.Serialization.Serializer.GetSize(value.f); - ret += Nino.Serialization.Serializer.GetSize(value.g); - ret += Nino.Serialization.Serializer.GetSize(value.h); - ret += Nino.Serialization.Serializer.GetSize(value.i); - ret += Nino.Serialization.Serializer.GetSize(value.j); - ret += Nino.Serialization.Serializer.GetSize(value.k); - ret += Nino.Serialization.Serializer.GetSize(value.l); - ret += Nino.Serialization.Serializer.GetSize(value.m); - ret += Nino.Serialization.Serializer.GetSize(value.n); - ret += Nino.Serialization.Serializer.GetSize(value.o); - ret += Nino.Serialization.Serializer.GetSize(value.p); - ret += Nino.Serialization.Serializer.GetSize(value.q); - ret += Nino.Serialization.Serializer.GetSize(value.r); - ret += Nino.Serialization.Serializer.GetSize(value.s); - ret += Nino.Serialization.Serializer.GetSize(value.t); - ret += Nino.Serialization.Serializer.GetSize(value.u); - ret += Nino.Serialization.Serializer.GetSize(value.v); - return ret; - } - #endregion - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Generated/Nino_Test_CollectionTest_Serialize.cs b/Nino_Unity/Assets/Nino/Generated/Nino_Test_CollectionTest_Serialize.cs deleted file mode 100644 index 960f649..0000000 --- a/Nino_Unity/Assets/Nino/Generated/Nino_Test_CollectionTest_Serialize.cs +++ /dev/null @@ -1,65 +0,0 @@ -/* this is generated by nino */ -using System.Runtime.CompilerServices; - -namespace Nino.Test -{ - public partial class CollectionTest - { - public static CollectionTest.SerializationHelper NinoSerializationHelper = new CollectionTest.SerializationHelper(); - public unsafe class SerializationHelper: Nino.Serialization.NinoWrapperBase - { - #region NINO_CODEGEN - public SerializationHelper() - { - - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override void Serialize(CollectionTest value, ref Nino.Serialization.Writer writer) - { - if(value == null) - { - writer.Write(false); - return; - } - writer.Write(true); - writer.Write(value.a); - writer.Write(value.b); - writer.Write(value.c); - writer.Write(value.d); - writer.Write(value.e); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override CollectionTest Deserialize(Nino.Serialization.Reader reader) - { - if(!reader.ReadBool()) - return null; - CollectionTest value = new CollectionTest(); - value.a = reader.ReadList(); - value.b = reader.ReadList(); - value.c = reader.ReadDictionary(); - value.d = reader.ReadDictionary(); - value.e = reader.ReadDictionary(); - return value; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override int GetSize(CollectionTest value) - { - if(value == null) - { - return 1; - } - int ret = 1; - ret += Nino.Serialization.Serializer.GetSize(value.a); - ret += Nino.Serialization.Serializer.GetSize(value.b); - ret += Nino.Serialization.Serializer.GetSize(value.c); - ret += Nino.Serialization.Serializer.GetSize(value.d); - ret += Nino.Serialization.Serializer.GetSize(value.e); - return ret; - } - #endregion - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Generated/Nino_Test_ComplexData_Serialize.cs b/Nino_Unity/Assets/Nino/Generated/Nino_Test_ComplexData_Serialize.cs deleted file mode 100644 index 83ed16f..0000000 --- a/Nino_Unity/Assets/Nino/Generated/Nino_Test_ComplexData_Serialize.cs +++ /dev/null @@ -1,80 +0,0 @@ -/* this is generated by nino */ -using System.Runtime.CompilerServices; - -namespace Nino.Test -{ - public partial class ComplexData - { - public static ComplexData.SerializationHelper NinoSerializationHelper = new ComplexData.SerializationHelper(); - public unsafe class SerializationHelper: Nino.Serialization.NinoWrapperBase - { - #region NINO_CODEGEN - public SerializationHelper() - { - - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override void Serialize(ComplexData value, ref Nino.Serialization.Writer writer) - { - if(value == null) - { - writer.Write(false); - return; - } - writer.Write(true); - writer.Write(value.a); - writer.Write(value.b); - writer.Write(value.c); - writer.Write(value.d); - writer.Write(value.e); - writer.Write(value.f); - writer.Write(value.g); - writer.Write(value.h); - writer.Write(value.i); - writer.Write(value.j); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override ComplexData Deserialize(Nino.Serialization.Reader reader) - { - if(!reader.ReadBool()) - return null; - ComplexData value = new ComplexData(); - value.a = reader.ReadArray(); - value.b = reader.ReadList(); - value.c = reader.ReadArray>(); - value.d = reader.ReadDictionary>(); - value.e = reader.ReadArray>>(); - value.f = reader.ReadArray(); - value.g = reader.ReadList(); - value.h = reader.ReadArray(); - value.i = reader.ReadArray>(); - value.j = reader.ReadArray>(); - return value; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override int GetSize(ComplexData value) - { - if(value == null) - { - return 1; - } - int ret = 1; - ret += Nino.Serialization.Serializer.GetSize(value.a); - ret += Nino.Serialization.Serializer.GetSize(value.b); - ret += Nino.Serialization.Serializer.GetSize(value.c); - ret += Nino.Serialization.Serializer.GetSize(value.d); - ret += Nino.Serialization.Serializer.GetSize(value.e); - ret += Nino.Serialization.Serializer.GetSize(value.f); - ret += Nino.Serialization.Serializer.GetSize(value.g); - ret += Nino.Serialization.Serializer.GetSize(value.h); - ret += Nino.Serialization.Serializer.GetSize(value.i); - ret += Nino.Serialization.Serializer.GetSize(value.j); - return ret; - } - #endregion - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Generated/Nino_Test_CustomTypeTest_Serialize.cs b/Nino_Unity/Assets/Nino/Generated/Nino_Test_CustomTypeTest_Serialize.cs deleted file mode 100644 index 861a096..0000000 --- a/Nino_Unity/Assets/Nino/Generated/Nino_Test_CustomTypeTest_Serialize.cs +++ /dev/null @@ -1,69 +0,0 @@ -/* this is generated by nino */ -using System.Runtime.CompilerServices; - -namespace Nino.Test -{ - public partial class CustomTypeTest - { - public static CustomTypeTest.SerializationHelper NinoSerializationHelper = new CustomTypeTest.SerializationHelper(); - public unsafe class SerializationHelper: Nino.Serialization.NinoWrapperBase - { - #region NINO_CODEGEN - public SerializationHelper() - { - - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override void Serialize(CustomTypeTest value, ref Nino.Serialization.Writer writer) - { - if(value == null) - { - writer.Write(false); - return; - } - writer.Write(true); - writer.Write(ref value.v3, sizeof(UnityEngine.Vector3),ref value.dt, sizeof(System.DateTime)); - writer.Write(value.ni); - writer.Write(value.qs); - writer.Write(ref value.m, sizeof(UnityEngine.Matrix4x4)); - writer.Write(value.dict); - writer.Write(value.dict2); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override CustomTypeTest Deserialize(Nino.Serialization.Reader reader) - { - if(!reader.ReadBool()) - return null; - CustomTypeTest value = new CustomTypeTest(); - reader.Read(ref value.v3, sizeof(UnityEngine.Vector3),ref value.dt, sizeof(System.DateTime)); - value.ni = reader.ReadNullable(); - value.qs = reader.ReadList(); - reader.Read(ref value.m, sizeof(UnityEngine.Matrix4x4)); - value.dict = reader.ReadDictionary(); - value.dict2 = reader.ReadDictionary(); - return value; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override int GetSize(CustomTypeTest value) - { - if(value == null) - { - return 1; - } - int ret = 1; - ret += Nino.Serialization.Serializer.GetSize(value.v3); - ret += Nino.Serialization.Serializer.GetSize(value.dt); - ret += Nino.Serialization.Serializer.GetSize(value.ni); - ret += Nino.Serialization.Serializer.GetSize(value.qs); - ret += Nino.Serialization.Serializer.GetSize(value.m); - ret += Nino.Serialization.Serializer.GetSize(value.dict); - ret += Nino.Serialization.Serializer.GetSize(value.dict2); - return ret; - } - #endregion - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Generated/Nino_Test_Data_Serialize.cs b/Nino_Unity/Assets/Nino/Generated/Nino_Test_Data_Serialize.cs deleted file mode 100644 index 082a81a..0000000 --- a/Nino_Unity/Assets/Nino/Generated/Nino_Test_Data_Serialize.cs +++ /dev/null @@ -1,53 +0,0 @@ -/* this is generated by nino */ -using System.Runtime.CompilerServices; - -namespace Nino.Test -{ - public partial struct Data - { - public static Data.SerializationHelper NinoSerializationHelper = new Data.SerializationHelper(); - public unsafe class SerializationHelper: Nino.Serialization.NinoWrapperBase - { - #region NINO_CODEGEN - public SerializationHelper() - { - int ret = 1; - ret += sizeof(System.Int32); - ret += sizeof(System.Int16); - ret += sizeof(System.Int64); - ret += sizeof(System.Single); - ret += sizeof(System.Decimal); - ret += sizeof(System.Double); - ret += sizeof(System.Boolean); - ret += sizeof(Nino.Test.TestEnum); - Nino.Serialization.Serializer.SetFixedSize(ret); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override void Serialize(Data value, ref Nino.Serialization.Writer writer) - { - - writer.Write(true); - writer.Write(ref value.x, sizeof(System.Int32),ref value.y, sizeof(System.Int16),ref value.z, sizeof(System.Int64),ref value.f, sizeof(System.Single),ref value.d, sizeof(System.Decimal),ref value.db, sizeof(System.Double),ref value.bo, sizeof(System.Boolean),ref value.en, sizeof(Nino.Test.TestEnum)); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override Data Deserialize(Nino.Serialization.Reader reader) - { - if(!reader.ReadBool()) - return default; - Data value = new Data(); - reader.Read(ref value.x, sizeof(System.Int32),ref value.y, sizeof(System.Int16),ref value.z, sizeof(System.Int64),ref value.f, sizeof(System.Single),ref value.d, sizeof(System.Decimal),ref value.db, sizeof(System.Double),ref value.bo, sizeof(System.Boolean),ref value.en, sizeof(Nino.Test.TestEnum)); - return value; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override int GetSize(Data value) - { - - return Nino.Serialization.Serializer.GetFixedSize(); - } - #endregion - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Generated/Nino_Test_IncludeAllClassCodeGen_Serialize.cs b/Nino_Unity/Assets/Nino/Generated/Nino_Test_IncludeAllClassCodeGen_Serialize.cs deleted file mode 100644 index a35fa86..0000000 --- a/Nino_Unity/Assets/Nino/Generated/Nino_Test_IncludeAllClassCodeGen_Serialize.cs +++ /dev/null @@ -1,56 +0,0 @@ -/* this is generated by nino */ -using System.Runtime.CompilerServices; - -namespace Nino.Test -{ - public partial class IncludeAllClassCodeGen - { - public static IncludeAllClassCodeGen.SerializationHelper NinoSerializationHelper = new IncludeAllClassCodeGen.SerializationHelper(); - public unsafe class SerializationHelper: Nino.Serialization.NinoWrapperBase - { - #region NINO_CODEGEN - public SerializationHelper() - { - int ret = 1; - ret += sizeof(System.Int32); - ret += sizeof(System.Int64); - ret += sizeof(System.Single); - ret += sizeof(System.Double); - Nino.Serialization.Serializer.SetFixedSize(ret); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override void Serialize(IncludeAllClassCodeGen value, ref Nino.Serialization.Writer writer) - { - if(value == null) - { - writer.Write(false); - return; - } - writer.Write(true); - writer.Write(ref value.a, sizeof(System.Int32),ref value.b, sizeof(System.Int64),ref value.c, sizeof(System.Single),ref value.d, sizeof(System.Double)); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override IncludeAllClassCodeGen Deserialize(Nino.Serialization.Reader reader) - { - if(!reader.ReadBool()) - return null; - IncludeAllClassCodeGen value = new IncludeAllClassCodeGen(); - reader.Read(ref value.a, sizeof(System.Int32),ref value.b, sizeof(System.Int64),ref value.c, sizeof(System.Single),ref value.d, sizeof(System.Double)); - return value; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override int GetSize(IncludeAllClassCodeGen value) - { - if(value == null) - { - return 1; - } - return Nino.Serialization.Serializer.GetFixedSize(); - } - #endregion - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Generated/Nino_Test_NestedData2_Serialize.cs b/Nino_Unity/Assets/Nino/Generated/Nino_Test_NestedData2_Serialize.cs deleted file mode 100644 index 1f48182..0000000 --- a/Nino_Unity/Assets/Nino/Generated/Nino_Test_NestedData2_Serialize.cs +++ /dev/null @@ -1,59 +0,0 @@ -/* this is generated by nino */ -using System.Runtime.CompilerServices; - -namespace Nino.Test -{ - public partial class NestedData2 - { - public static NestedData2.SerializationHelper NinoSerializationHelper = new NestedData2.SerializationHelper(); - public unsafe class SerializationHelper: Nino.Serialization.NinoWrapperBase - { - #region NINO_CODEGEN - public SerializationHelper() - { - - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override void Serialize(NestedData2 value, ref Nino.Serialization.Writer writer) - { - if(value == null) - { - writer.Write(false); - return; - } - writer.Write(true); - writer.Write(value.name); - writer.Write(value.ps); - writer.Write(value.vs); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override NestedData2 Deserialize(Nino.Serialization.Reader reader) - { - if(!reader.ReadBool()) - return null; - NestedData2 value = new NestedData2(); - value.name = reader.ReadString(); - value.ps = reader.ReadArray(); - value.vs = reader.ReadList(); - return value; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override int GetSize(NestedData2 value) - { - if(value == null) - { - return 1; - } - int ret = 1; - ret += Nino.Serialization.Serializer.GetSize(value.name); - ret += Nino.Serialization.Serializer.GetSize(value.ps); - ret += Nino.Serialization.Serializer.GetSize(value.vs); - return ret; - } - #endregion - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Generated/Nino_Test_NestedData_Serialize.cs b/Nino_Unity/Assets/Nino/Generated/Nino_Test_NestedData_Serialize.cs deleted file mode 100644 index e6688da..0000000 --- a/Nino_Unity/Assets/Nino/Generated/Nino_Test_NestedData_Serialize.cs +++ /dev/null @@ -1,56 +0,0 @@ -/* this is generated by nino */ -using System.Runtime.CompilerServices; - -namespace Nino.Test -{ - public partial class NestedData - { - public static NestedData.SerializationHelper NinoSerializationHelper = new NestedData.SerializationHelper(); - public unsafe class SerializationHelper: Nino.Serialization.NinoWrapperBase - { - #region NINO_CODEGEN - public SerializationHelper() - { - - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override void Serialize(NestedData value, ref Nino.Serialization.Writer writer) - { - if(value == null) - { - writer.Write(false); - return; - } - writer.Write(true); - writer.Write(value.name); - writer.Write(value.ps); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override NestedData Deserialize(Nino.Serialization.Reader reader) - { - if(!reader.ReadBool()) - return null; - NestedData value = new NestedData(); - value.name = reader.ReadString(); - value.ps = reader.ReadArray(); - return value; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override int GetSize(NestedData value) - { - if(value == null) - { - return 1; - } - int ret = 1; - ret += Nino.Serialization.Serializer.GetSize(value.name); - ret += Nino.Serialization.Serializer.GetSize(value.ps); - return ret; - } - #endregion - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Generated/Nino_Test_NotIncludeAllClass_Serialize.cs b/Nino_Unity/Assets/Nino/Generated/Nino_Test_NotIncludeAllClass_Serialize.cs deleted file mode 100644 index 94dff11..0000000 --- a/Nino_Unity/Assets/Nino/Generated/Nino_Test_NotIncludeAllClass_Serialize.cs +++ /dev/null @@ -1,56 +0,0 @@ -/* this is generated by nino */ -using System.Runtime.CompilerServices; - -namespace Nino.Test -{ - public partial class NotIncludeAllClass - { - public static NotIncludeAllClass.SerializationHelper NinoSerializationHelper = new NotIncludeAllClass.SerializationHelper(); - public unsafe class SerializationHelper: Nino.Serialization.NinoWrapperBase - { - #region NINO_CODEGEN - public SerializationHelper() - { - int ret = 1; - ret += sizeof(System.Int32); - ret += sizeof(System.Int64); - ret += sizeof(System.Single); - ret += sizeof(System.Double); - Nino.Serialization.Serializer.SetFixedSize(ret); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override void Serialize(NotIncludeAllClass value, ref Nino.Serialization.Writer writer) - { - if(value == null) - { - writer.Write(false); - return; - } - writer.Write(true); - writer.Write(ref value.a, sizeof(System.Int32),ref value.b, sizeof(System.Int64),ref value.c, sizeof(System.Single),ref value.d, sizeof(System.Double)); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override NotIncludeAllClass Deserialize(Nino.Serialization.Reader reader) - { - if(!reader.ReadBool()) - return null; - NotIncludeAllClass value = new NotIncludeAllClass(); - reader.Read(ref value.a, sizeof(System.Int32),ref value.b, sizeof(System.Int64),ref value.c, sizeof(System.Single),ref value.d, sizeof(System.Double)); - return value; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override int GetSize(NotIncludeAllClass value) - { - if(value == null) - { - return 1; - } - return Nino.Serialization.Serializer.GetFixedSize(); - } - #endregion - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/Attributes/CodeGenIgnoreAttribute.cs b/Nino_Unity/Assets/Nino/Serialization/Attributes/CodeGenIgnoreAttribute.cs deleted file mode 100644 index ce79d46..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/Attributes/CodeGenIgnoreAttribute.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; - -namespace Nino.Serialization -{ - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)] - public class CodeGenIgnoreAttribute : Attribute - { - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/Attributes/NinoIgnoreAttribute.cs b/Nino_Unity/Assets/Nino/Serialization/Attributes/NinoIgnoreAttribute.cs deleted file mode 100644 index e59454b..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/Attributes/NinoIgnoreAttribute.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; - -namespace Nino.Serialization -{ - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)] - public class NinoIgnoreAttribute : Attribute - { - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/Attributes/NinoMemberAttribute.cs b/Nino_Unity/Assets/Nino/Serialization/Attributes/NinoMemberAttribute.cs deleted file mode 100644 index c756f58..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/Attributes/NinoMemberAttribute.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; - -namespace Nino.Serialization -{ - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)] - public class NinoMemberAttribute : Attribute - { - public readonly ushort Index; - - /// - /// Indicate a member that can be serialized and deserialized - /// 标明该成员可以被序列化或反序列化 - /// - /// index while serializing or deserializing | 序列化或反序列化时的顺序 - public NinoMemberAttribute(ushort index) - { - this.Index = index; - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/Attributes/NinoSerializeAttribute.cs b/Nino_Unity/Assets/Nino/Serialization/Attributes/NinoSerializeAttribute.cs deleted file mode 100644 index 609cd02..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/Attributes/NinoSerializeAttribute.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; - -namespace Nino.Serialization -{ - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)] - public class NinoSerializeAttribute : Attribute - { - public readonly bool IncludeAll; - - /// - /// A struct or class to be serialized and deserialized - /// 一个结构体或一个类型的会被序列化以及反序列化 - /// include all fields and properties - /// - public NinoSerializeAttribute(bool includeAll = true) - { - IncludeAll = includeAll; - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/CodeGenerator.cs b/Nino_Unity/Assets/Nino/Serialization/CodeGenerator.cs deleted file mode 100644 index 0e1102f..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/CodeGenerator.cs +++ /dev/null @@ -1,696 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using Nino.Shared.Mgr; -using Nino.Shared.Util; -using System.Reflection; - -namespace Nino.Serialization -{ - /// - /// Nino code generator - /// TODO support nullable, hashset, queue, stack - /// - public static class CodeGenerator - { - /// - /// Generate serialization code file at Assets/ouputPath - /// editor only method - /// - /// - /// - public static void GenerateSerializationCodeForAllTypePossible(string outputPath = "Nino/Generated", - Assembly[] assemblies = null) - { - //find all types - var types = (assemblies ?? AppDomain.CurrentDomain.GetAssemblies()).SelectMany(a => a.GetTypes()).ToList() - .FindAll(t => - { - //find NinoSerializeAttribute - NinoSerializeAttribute[] ns = - (NinoSerializeAttribute[])t.GetCustomAttributes(typeof(NinoSerializeAttribute), true); - if (ns.Length == 0) return false; - return true; - }).ToList(); - //iterate - foreach (var type in types) - { - //gen - GenerateSerializationCode(type, outputPath); - } - } - - /// - /// Get a valid nino serialize class - /// - /// - /// - /// - private static bool GetValidNinoClass(Type type, bool log = true) - { - //nested - if (type.IsNested) - { - if (log) - Logger.E("Code Gen", $"Can not generate code for type: {type} due to it is a nested class"); - return false; - } - - //generic - if (type.IsGenericType) - { - if (log) - Logger.E("Code Gen", $"Can not generate code for type: {type} due to it is a generic class"); - return false; - } - - //find NinoSerializeAttribute - NinoSerializeAttribute[] ns = - (NinoSerializeAttribute[])type.GetCustomAttributes(typeof(NinoSerializeAttribute), true); - if (ns.Length == 0) return false; - - CodeGenIgnoreAttribute[] ci = - (CodeGenIgnoreAttribute[])type.GetCustomAttributes(typeof(CodeGenIgnoreAttribute), true); - if (ci.Length != 0) return false; - return true; - } - - /// - /// Generate serialization code file at Assets/ouputPath - /// editor only method - /// - /// - /// - // ReSharper disable CognitiveComplexity - public static void GenerateSerializationCode(Type type, string outputPath = "Nino/Generated") - // ReSharper restore CognitiveComplexity - { - //nino class only - if (!GetValidNinoClass(type)) return; - - //code template - string template = - @"/* this is generated by nino */ -using System.Runtime.CompilerServices; - -{namespace} -{start} - public partial struct {type} - { - public static {type}.SerializationHelper NinoSerializationHelper = new {type}.SerializationHelper(); - public unsafe class SerializationHelper: Nino.Serialization.NinoWrapperBase<{type}> - { - #region NINO_CODEGEN - public SerializationHelper() - { -{ctor} - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override void Serialize({type} value, ref Nino.Serialization.Writer writer) - { - {nullCheck} - writer.Write(true); -{members} - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override {type} Deserialize(Nino.Serialization.Reader reader) - { - if(!reader.ReadBool()) - {returnNull} - {createObj} -{fields} - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override int GetSize({type} value) - { - {sizeNull} -{size} - } - #endregion - } - } -{end}"; - if (type.IsClass) - { - template = template.Replace("struct", "class"); - template = template.Replace("{nullCheck}", @"if(value == null) - { - writer.Write(false); - return; - }"); - template = template.Replace("{returnNull}", "return null;"); - template = template.Replace("{sizeNull}", @"if(value == null) - { - return 1; - }"); - -#if UNITY_2017_1_OR_NEWER - //see if type inherits MonoBehaviour - if (type.IsSubclassOf(typeof(UnityEngine.MonoBehaviour))) - { - template = template.Replace("{createObj}", "{type} value = new UnityEngine.GameObject(\"{type}\").AddComponent<{type}>();"); - } - else -#endif - { - template = template.Replace("{createObj}", "{type} value = new {type}();"); - } - } - else - { - template = template.Replace("{nullCheck}", @""); - template = template.Replace("{returnNull}", "return default;"); - template = template.Replace("{sizeNull}", @""); - } - - //replace namespace - if (!string.IsNullOrEmpty(type.Namespace)) - { - template = template.Replace("{namespace}", $"namespace {type.Namespace}"); - template = template.Replace("{start}", "{"); - template = template.Replace("{end}", "}"); - } - else - { - template = template.Replace("{namespace}", string.Empty); - template = template.Replace("{start}", string.Empty); - template = template.Replace("{end}", string.Empty); - } - - //class full name - var classFullName = - $"{type.GetFriendlyName()}"; - //replace full name - template = template.Replace("{type}", classFullName); - - //find members - TypeModel.TryGetModel(type, out var model); - //invalid model - if (model != null) - { - if (!model.Valid) - { - throw new InvalidOperationException("invalid model"); - } - } - - //generate model - if (model == null) - { - model = TypeModel.CreateModel(type); - } - - var members = model.Members; - - #region serialize - - //build params - StringBuilder sb = new StringBuilder(); - List unmanagedMembers = new List(); - for (int i = 0; i < members.Count; i++) - { - var info = members[i]; - var member = info.Member; - var mt = info.Type; - - //try optimize - if (TypeModel.IsUnmanaged(mt) && member is FieldInfo) - { - unmanagedMembers.Clear(); - unmanagedMembers.Add(info); - for (int j = i + 1; j < members.Count; j++) - { - var info2 = members[j]; - var member2 = info2.Member; - var mt2 = info2.Type; - if (TypeModel.IsUnmanaged(mt2) && member2 is FieldInfo) - { - unmanagedMembers.Add(info2); - } - else - { - break; - } - } - - i += unmanagedMembers.Count - 1; - //batch write with batch size 8 - while (unmanagedMembers.Count > 0) - { - if (unmanagedMembers.Count <= 8) - { - sb.Append( - $" writer.Write({string.Join(",", unmanagedMembers.Select(x => $"ref value.{x.Member.Name}, sizeof({BeautifulLongTypeName(x.Type)})"))});\n"); - unmanagedMembers.Clear(); - } - else - { - sb.Append( - $" writer.Write({string.Join(",", unmanagedMembers.Take(8).Select(x => $"ref value.{x.Member.Name}, sizeof({BeautifulLongTypeName(x.Type)})"))});\n"); - unmanagedMembers.RemoveRange(0, 8); - } - } - - continue; - } - - //enum - if (mt.IsEnum) - { - sb.Append( - $" writer.WriteEnum<{BeautifulLongTypeName(mt)}>(value.{member.Name});\n"); - } - //array/list - else if (mt.IsArray || (mt.IsGenericType && mt.GetGenericTypeDefinition() == ConstMgr.ListDefType)) - { - sb.Append($" writer.Write(value.{member.Name});\n"); - } - //dict - else if (mt.IsGenericType && mt.GetGenericTypeDefinition() == ConstMgr.DictDefType) - { - sb.Append($" writer.Write(value.{member.Name});\n"); - } - //nullable - else if (mt.IsGenericType && mt.GetGenericTypeDefinition() == ConstMgr.NullableDefType) - { - sb.Append($" writer.Write(value.{member.Name});\n"); - } - //basic type - else - { - sb.Append( - $" {GetSerializeBasicTypeStatement(mt, $"value.{member.Name}", member is PropertyInfo)};\n"); - } - } - - if (members.Count > 0) - { - //remove \n at the end - sb.Remove(sb.Length - 1, 1); - } - - //replace template members - template = template.Replace("{members}", sb.ToString()); - - #endregion - - #region deserialize - - sb.Clear(); - for (int i = 0; i < members.Count; i++) - { - var info = members[i]; - var member = info.Member; - var mt = info.Type; - - //try optimize - if (TypeModel.IsUnmanaged(mt) && member is FieldInfo) - { - unmanagedMembers.Clear(); - unmanagedMembers.Add(info); - for (int j = i + 1; j < members.Count; j++) - { - var info2 = members[j]; - var member2 = info2.Member; - var mt2 = info2.Type; - if (TypeModel.IsUnmanaged(mt2) && member2 is FieldInfo) - { - unmanagedMembers.Add(info2); - } - else - { - break; - } - } - - i += unmanagedMembers.Count - 1; - //batch write with batch size 8 - while (unmanagedMembers.Count > 0) - { - if (unmanagedMembers.Count <= 8) - { - sb.Append( - $" reader.Read({string.Join(",", unmanagedMembers.Select(x => $"ref value.{x.Member.Name}, sizeof({BeautifulLongTypeName(x.Type)})"))});\n"); - unmanagedMembers.Clear(); - } - else - { - sb.Append( - $" reader.Read({string.Join(",", unmanagedMembers.Take(8).Select(x => $"ref value.{x.Member.Name}, sizeof({BeautifulLongTypeName(x.Type)})"))});\n"); - unmanagedMembers.RemoveRange(0, 8); - } - } - - continue; - } - - //enum - if (mt.IsEnum) - { - if (member is PropertyInfo) - { - sb.Append( - $" value.{member.Name} = reader.ReadEnum<{BeautifulLongTypeName(mt)}>();\n"); - } - else - { - sb.Append( - $" reader.ReadEnum<{BeautifulLongTypeName(mt)}>(ref value.{member.Name});\n"); - } - } - //array/list - else if (mt.IsArray || (mt.IsGenericType && mt.GetGenericTypeDefinition() == ConstMgr.ListDefType)) - { - Type elemType = mt.IsGenericType ? mt.GenericTypeArguments[0] : mt.GetElementType(); - - //create field - if (mt.IsArray) - { - //multidimensional array - if (mt.GetArrayRank() > 1) - { - throw new NotSupportedException( - "can not serialize multidimensional array, use jagged array instead"); - } - - sb.Append( - $" value.{member.Name} = reader.ReadArray<{BeautifulLongTypeName(elemType)}>();\n"); - } - else - { - sb.Append( - $" value.{member.Name} = reader.ReadList<{BeautifulLongTypeName(elemType)}>();\n"); - } - } - //dict - else if (mt.IsGenericType && mt.GetGenericTypeDefinition() == ConstMgr.DictDefType) - { - var args = mt.GetGenericArguments(); - Type keyType = args[0]; - Type valueType = args[1]; - - sb.Append( - $" value.{member.Name} = reader.ReadDictionary<{BeautifulLongTypeName(keyType)},{BeautifulLongTypeName(valueType)}>();\n"); - } - //nullable - else if (mt.IsGenericType && mt.GetGenericTypeDefinition() == ConstMgr.NullableDefType) - { - var args = mt.GetGenericArguments(); - Type keyType = args[0]; - - sb.Append( - $" value.{member.Name} = reader.ReadNullable<{BeautifulLongTypeName(keyType)}>();\n"); - } - //not enum -> basic type - else - { - string val = GetDeserializeBasicTypeStatement(mt, member is PropertyInfo, - $"value.{member.Name}"); - sb.Append($" {val}\n"); - } - } - - sb.Append(" return value;\n"); - //remove comma at the end - sb.Remove(sb.Length - 1, 1); - - //replace template fields - template = template.Replace("{fields}", sb.ToString()); - - #endregion - - #region getsize - - sb.Clear(); - if (TypeModel.IsFixedSizeType(type)) - { - sb.Append( - $" return Nino.Serialization.Serializer.GetFixedSize<{BeautifulLongTypeName(type)}>();"); - } - else - { - sb.Append(" int ret = 1;\n"); - foreach (var info in members) - { - var member = info.Member; - var size = Serializer.GetFixedSize(info.Type); - sb.Append( - size != -1 - ? $" ret += {size}; // size for {member.Name}\n" - : $" ret += Nino.Serialization.Serializer.GetSize(value.{member.Name});\n"); - } - - sb.Append(" return ret;"); - } - - //replace template fields - template = template.Replace("{size}", sb.ToString()); - - #endregion - - #region ctor - - sb.Clear(); - if (TypeModel.IsFixedSizeType(type)) - { - sb.Append(" int ret = 1;\n"); - foreach (var info in members) - { - var mt = info.Type; - sb.Append( - $" ret += sizeof({BeautifulLongTypeName(mt)});\n"); - } - - sb.Append( - $" Nino.Serialization.Serializer.SetFixedSize<{BeautifulLongTypeName(type)}>(ret);"); - } - - //replace template fields - template = template.Replace("{ctor}", sb.ToString()); - - #endregion - - //save path - var output = Path.Combine(ConstMgr.AssetPath, outputPath); - if (!Directory.Exists(output)) - { - Directory.CreateDirectory(output); - } - - //save file path - output = Path.Combine(output, - $"{type.Namespace}{(!string.IsNullOrEmpty(type.Namespace) ? "." : "")}{type.GetFriendlyName()}" - .Replace(".", "_").Replace(",", "_") - .Replace("<", "_").Replace(">", "_") + - "_Serialize.cs"); - if (File.Exists(output)) - { - File.Delete(output); - } - - //save - File.WriteAllText(output, template); - -#if UNITY_2017_1_OR_NEWER - Logger.D("Code Gen", $"saved {output}"); -#else - Logger.D("Code Gen", $"saved {output}, please move this file to your project"); -#endif - } - - // ReSharper disable CognitiveComplexity - private static string GetDeserializeBasicTypeStatement(Type mt, bool isProperty, string val = "", - string space = " ") - // ReSharper restore CognitiveComplexity - { - switch (Type.GetTypeCode(mt)) - { - case TypeCode.Int32: - case TypeCode.UInt32: - case TypeCode.Int64: - case TypeCode.UInt64: - case TypeCode.Byte: - case TypeCode.SByte: - case TypeCode.Int16: - case TypeCode.UInt16: - case TypeCode.Boolean: - case TypeCode.Double: - case TypeCode.Single: - case TypeCode.Decimal: - case TypeCode.Char: - case TypeCode.DateTime: - return isProperty - ? $"{val} = reader.Read<{BeautifulLongTypeName(mt)}>(sizeof({BeautifulLongTypeName(mt)}));" - : $"reader.Read<{BeautifulLongTypeName(mt)}>(ref {val}, sizeof({BeautifulLongTypeName(mt)}));"; - case TypeCode.String: - return $"{val} = reader.ReadString();"; - default: - if (GetValidNinoClass(mt, false)) - { - return $"{val} = {BeautifulLongTypeName(mt)}.NinoSerializationHelper.Deserialize(reader);"; - } - - //enum - if (mt.IsEnum) - { - return isProperty - ? $"{val} = reader.ReadEnum<{BeautifulLongTypeName(mt)}>();" - : $"reader.ReadEnum<{BeautifulLongTypeName(mt)}>(ref {val});"; - } - - if (mt.IsArray || - (mt.IsGenericType && mt.GetGenericTypeDefinition() == ConstMgr.ListDefType)) - { - Type elemType = mt.IsGenericType ? mt.GenericTypeArguments[0] : mt.GetElementType(); - StringBuilder builder = new StringBuilder(); - if (mt.IsArray) - { - //multidimensional array - if (mt.GetArrayRank() > 1) - { - throw new NotSupportedException( - "can not serialize multidimensional array, use jagged array instead"); - } - - builder.Append( - $"{val} = reader.ReadArray<{BeautifulLongTypeName(elemType)}>();\n"); - } - else - { - builder.Append( - $"{val} = reader.ReadList<{BeautifulLongTypeName(elemType)}>();\n"); - } - - return builder.ToString(); - } - - if (mt.IsGenericType && mt.GetGenericTypeDefinition() == ConstMgr.DictDefType) - { - StringBuilder builder = new StringBuilder(); - var args = mt.GetGenericArguments(); - Type keyType = args[0]; - Type valueType = args[1]; - //create field - builder.Append(space).Append( - $"{BeautifulLongTypeName(mt)} {val} = reader.ReadDictionary<{BeautifulLongTypeName(keyType)},{BeautifulLongTypeName(valueType)}>();\n"); - return builder.ToString(); - } - - return $"{val} = reader.ReadCommonVal<{BeautifulLongTypeName(mt)}>();"; - } - } - - // ReSharper disable CognitiveComplexity - private static string GetSerializeBasicTypeStatement(Type mt, string val, bool isProperty, int indent = 0, - string space = " ") - // ReSharper restore CognitiveComplexity - { - switch (Type.GetTypeCode(mt)) - { - case TypeCode.Int32: - case TypeCode.UInt32: - case TypeCode.Int64: - case TypeCode.UInt64: - case TypeCode.Byte: - case TypeCode.SByte: - case TypeCode.Int16: - case TypeCode.UInt16: - case TypeCode.Boolean: - case TypeCode.Double: - case TypeCode.Single: - case TypeCode.Decimal: - case TypeCode.Char: - case TypeCode.DateTime: - return isProperty - ? $"writer.Write({val})" - : $"writer.Write(ref {val}, sizeof({BeautifulLongTypeName(mt)}))"; - case TypeCode.String: - return $"writer.Write({val})"; - default: - if (GetValidNinoClass(mt, false)) - { - return $"{BeautifulLongTypeName(mt)}.NinoSerializationHelper.Serialize({val}, ref writer)"; - } - - if (mt.IsArray || (mt.IsGenericType && mt.GetGenericTypeDefinition() == ConstMgr.ListDefType)) - { - StringBuilder builder = new StringBuilder(); - Type elemType = mt.IsGenericType ? mt.GenericTypeArguments[0] : mt.GetElementType(); - if (elemType == null) - { - throw new InvalidOperationException("Invalid array type"); - } - - builder.Append(space).Append(Repeat(" ", indent)) - .Append($"writer.Write({val});\n"); - return builder.ToString(); - } - - if (mt.IsGenericType && mt.GetGenericTypeDefinition() == ConstMgr.DictDefType) - { - StringBuilder builder = new StringBuilder(); - builder.Append(space).Append(Repeat(" ", indent)) - .Append($"writer.Write({val});\n"); - return builder.ToString(); - } - - if (mt.IsGenericType && mt.GetGenericTypeDefinition() == ConstMgr.NullableDefType) - { - StringBuilder builder = new StringBuilder(); - builder.Append(space).Append(Repeat(" ", indent)) - .Append($"writer.Write({val});\n"); - return builder.ToString(); - } - - return $"writer.WriteCommonVal<{BeautifulLongTypeName(mt)}>({val})"; - } - } - - private static string Repeat(string value, int count) - { - if (count < 1) return string.Empty; - return new StringBuilder(value.Length * count).Insert(0, value, count).ToString(); - } - - private static string BeautifulLongTypeName(this Type mt) - { - return $"{mt.Namespace}{(!string.IsNullOrEmpty(mt.Namespace) ? "." : "")}{mt.GetFriendlyName()}"; - } - - /// - /// 获取类型名字 - /// - /// - /// - private static string GetFriendlyName(this Type type) - { - string friendlyName = type.Name; - if (type.IsGenericType) - { - int iBacktick = friendlyName.IndexOf('`'); - if (iBacktick > 0) - { - friendlyName = friendlyName.Remove(iBacktick); - } - - friendlyName += "<"; - Type[] typeParameters = type.GetGenericArguments(); - for (int i = 0; i < typeParameters.Length; ++i) - { - string typeParamName = - $"{typeParameters[i].Namespace}{(!string.IsNullOrEmpty(typeParameters[i].Namespace) ? "." : "")}{GetFriendlyName(typeParameters[i])}"; - friendlyName += (i == 0 ? typeParamName : "," + typeParamName); - } - - friendlyName += ">"; - } - - return friendlyName; - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/Deserializer.Generic.cs b/Nino_Unity/Assets/Nino/Serialization/Deserializer.Generic.cs deleted file mode 100644 index 7de3e7e..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/Deserializer.Generic.cs +++ /dev/null @@ -1,335 +0,0 @@ -using System; -using System.Collections.Generic; -using Nino.Shared.IO; - -namespace Nino.Serialization -{ - public static partial class Deserializer - { - #region Array - - /// - /// Deserialize an array NinoSerialize object - /// - /// - /// - /// - public static T[] DeserializeArray(byte[] data) - => DeserializeArray(new Span(data)); - - /// - /// Deserialize an array NinoSerialize object - /// - /// - /// - /// - public static T[] DeserializeArray(ArraySegment data) - => DeserializeArray(new Span(data.Array, data.Offset, data.Count)); - - /// - /// Deserialize an array of NinoSerialize object - /// - /// - /// - /// - public static T[] DeserializeArray(Span data) - { - var type = typeof(T[]); - var reader = ObjectPool.Request(); - reader.Init(data, data.Length); - - /* - * NO GC DESERIALIZATION ATTEMPT - */ - //basic type - if (TryDeserializeWrapperType(type, reader, false, true, out T[] ret)) - { - return ret; - } - - //attempt to deserialize using generic method - return reader.ReadArray(); - } - - #endregion - - #region Nullable - - /// - /// Deserialize a nullable of NinoSerialize struct - /// - /// - /// - /// - public static T? DeserializeNullable(byte[] data) - where T : struct - => DeserializeNullable(new Span(data)); - - /// - /// Deserialize a nullable of NinoSerialize struct - /// - /// - /// - /// - public static T? DeserializeNullable(ArraySegment data) - where T : struct - => DeserializeNullable(new Span(data.Array, data.Offset, data.Count)); - - /// - /// Deserialize a nullable of NinoSerialize struct - /// - /// - /// - /// - public static T? DeserializeNullable(Span data) - where T : struct - { - var reader = ObjectPool.Request(); - reader.Init(data, data.Length); - - //attempt to deserialize using generic method - return reader.ReadNullable(); - } - - #endregion - - #region List - - /// - /// Deserialize a list of NinoSerialize object - /// - /// - /// - /// - public static List DeserializeList(byte[] data) - => DeserializeList(new Span(data)); - - /// - /// Deserialize a list of NinoSerialize object - /// - /// - /// - /// - public static List DeserializeList(ArraySegment data) - => DeserializeList(new Span(data.Array, data.Offset, data.Count)); - - /// - /// Deserialize a list of NinoSerialize object - /// - /// - /// - /// - public static List DeserializeList(Span data) - { - var type = typeof(List); - var reader = ObjectPool.Request(); - reader.Init(data, data.Length); - - /* - * NO GC DESERIALIZATION ATTEMPT - */ - //basic type - if (TryDeserializeWrapperType(type, reader, false, true, out List ret)) - { - return ret; - } - - //attempt to deserialize using generic method - return reader.ReadList(); - } - - #endregion - - #region HashSet - - /// - /// Deserialize a HashSet of NinoSerialize object - /// - /// - /// - /// - public static HashSet DeserializeHashSet(byte[] data) - => DeserializeHashSet(new Span(data)); - - /// - /// Deserialize a HashSet of NinoSerialize object - /// - /// - /// - /// - public static HashSet DeserializeHashSet(ArraySegment data) - => DeserializeHashSet(new Span(data.Array, data.Offset, data.Count)); - - /// - /// Deserialize a HashSet of NinoSerialize object - /// - /// - /// - /// - public static HashSet DeserializeHashSet(Span data) - { - var type = typeof(HashSet); - var reader = ObjectPool.Request(); - reader.Init(data, data.Length); - - /* - * NO GC DESERIALIZATION ATTEMPT - */ - //basic type - if (TryDeserializeWrapperType(type, reader, false, true, out HashSet ret)) - { - return ret; - } - - //attempt to deserialize using generic method - return reader.ReadHashSet(); - } - - #endregion - - #region Queue - - /// - /// Deserialize a Queue of NinoSerialize object - /// - /// - /// - /// - public static Queue DeserializeQueue(byte[] data) - => DeserializeQueue(new Span(data)); - - /// - /// Deserialize a Queue of NinoSerialize object - /// - /// - /// - /// - public static Queue DeserializeQueue(ArraySegment data) - => DeserializeQueue(new Span(data.Array, data.Offset, data.Count)); - - /// - /// Deserialize a Queue of NinoSerialize object - /// - /// - /// - /// - public static Queue DeserializeQueue(Span data) - { - var type = typeof(Queue); - var reader = ObjectPool.Request(); - reader.Init(data, data.Length); - - /* - * NO GC DESERIALIZATION ATTEMPT - */ - //basic type - if (TryDeserializeWrapperType(type, reader, false, true, out Queue ret)) - { - return ret; - } - - //attempt to deserialize using generic method - return reader.ReadQueue(); - } - - #endregion - - #region Stack - - /// - /// Deserialize a Stack of NinoSerialize object - /// - /// - /// - /// - public static Stack DeserializeStack(byte[] data) - => DeserializeStack(new Span(data)); - - /// - /// Deserialize a Stack of NinoSerialize object - /// - /// - /// - /// - public static Stack DeserializeStack(ArraySegment data) - => DeserializeStack(new Span(data.Array, data.Offset, data.Count)); - - /// - /// Deserialize a Stack of NinoSerialize object - /// - /// - /// - /// - public static Stack DeserializeStack(Span data) - { - var type = typeof(Stack); - var reader = ObjectPool.Request(); - reader.Init(data, data.Length); - - /* - * NO GC DESERIALIZATION ATTEMPT - */ - //basic type - if (TryDeserializeWrapperType(type, reader, false, true, out Stack ret)) - { - return ret; - } - - //attempt to deserialize using generic method - return reader.ReadStack(); - } - - #endregion - - #region Dictionary - - /// - /// Deserialize a Dictionary of NinoSerialize object - /// - /// - /// - /// - /// - public static Dictionary DeserializeDictionary(byte[] data) - => DeserializeDictionary(new Span(data)); - - /// - /// Deserialize a Dictionary of NinoSerialize object - /// - /// - /// - /// - /// - public static Dictionary DeserializeDictionary(ArraySegment data) - => DeserializeDictionary(new Span(data.Array, data.Offset, data.Count)); - - /// - /// Deserialize a Dictionary of NinoSerialize object - /// - /// - /// - /// - /// - public static Dictionary DeserializeDictionary(Span data) - { - var type = typeof(Dictionary); - var reader = ObjectPool.Request(); - reader.Init(data, data.Length); - - /* - * NO GC DESERIALIZATION ATTEMPT - */ - //basic type - if (TryDeserializeWrapperType(type, reader, false, true, - out Dictionary ret)) - { - return ret; - } - - //attempt to deserialize using generic method - return reader.ReadDictionary(); - } - - #endregion - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/Deserializer.cs b/Nino_Unity/Assets/Nino/Serialization/Deserializer.cs deleted file mode 100644 index 2881141..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/Deserializer.cs +++ /dev/null @@ -1,565 +0,0 @@ -using System; -using Nino.Shared.IO; -using Nino.Shared.Mgr; -using System.Reflection; -using System.Collections; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; - -namespace Nino.Serialization -{ - public static partial class Deserializer - { - /// - /// Deserialize a NinoSerialize object - /// - /// - /// - /// - public static T Deserialize(byte[] data) - => Deserialize(new Span(data), null); - - /// - /// Deserialize a NinoSerialize object - /// - /// - /// - /// - public static T Deserialize(ArraySegment data) - => Deserialize(new Span(data.Array, data.Offset, data.Count), null); - - /// - /// Deserialize a NinoSerialize object - /// - /// - /// - /// - public static T Deserialize(Span data) - => Deserialize(data, null); - - /// - /// Deserialize a NinoSerialize object - /// - /// - /// - /// - public static object Deserialize(Type type, byte[] data) - => Deserialize(type, null, new Span(data), null); - - /// - /// Deserialize a NinoSerialize object - /// - /// - /// - /// - public static object Deserialize(Type type, ArraySegment data) - => Deserialize(type, null, new Span(data.Array, data.Offset, data.Count), null); - - /// - /// Deserialize a NinoSerialize object - /// - /// - /// - /// - public static object Deserialize(Type type, Span data) - => Deserialize(type, null, data, null); - - /// - /// Deserialize a NinoSerialize object - /// - /// - /// - /// - /// - /// - internal static T Deserialize(Span data, Reader reader, - [MarshalAs(UnmanagedType.U1)] bool returnDispose = true) - { - Type type = typeof(T); - - if (reader == null) - { - reader = ObjectPool.Request(); - reader.Init(data, data.Length); - } - - /* - * NO GC DESERIALIZATION ATTEMPT - */ - //basic type - if (TryDeserializeWrapperType(type, reader, false, returnDispose, out T ret)) - { - return ret; - } - - //enum - if (TryDeserializeEnum(type, reader, returnDispose, out var e)) - { - return e; - } - - //code generated type - if (TryDeserializeCodeGenType(type, reader, false, returnDispose, out ret)) - { - return ret; - } - - //unmanaged type - if (TryDeserializeUnmanagedType(type, reader, returnDispose, out var un)) - { - return un; - } - - /* - * GC DESERIALIZATION WHILE T IS STRUCT - */ - var result = Deserialize(type, null, data, reader, returnDispose); - if (result != null) return (T)result; - ObjectPool.Return(reader); - return default; - } - - /// - /// Deserialize a NinoSerialize object - /// - /// - /// - /// - /// - /// - /// - /// - /// - internal static object Deserialize(Type type, object val, Span data, Reader reader, - [MarshalAs(UnmanagedType.U1)] bool returnDispose = true) - { - if (reader == null) - { - reader = ObjectPool.Request(); - reader.Init(data, data.Length); - } - - //array - if (TryDeserializeArray(type, reader, returnDispose, out var arr)) - { - return arr; - } - - //list, dict - if (type.IsGenericType) - { - var genericDefType = type.GetGenericTypeDefinition(); - if (TryDeserializeList(type, genericDefType, reader, returnDispose, out var lst)) - { - return lst; - } - - if (TryDeserializeDict(type, genericDefType, reader, returnDispose, out var dict)) - { - return dict; - } - } - - //basic type - if (TryDeserializeWrapperType(type, reader, true, returnDispose, out object basicObj)) - { - return basicObj; - } - - //enum - if (TryDeserializeEnum(type, reader, returnDispose, out var e)) - { - return e; - } - - //code generated type - if (TryDeserializeCodeGenType(type, reader, true, returnDispose, out object codeGenRet)) - { - return codeGenRet; - } - - //unmanaged type - if (TryDeserializeUnmanagedType(type, reader, returnDispose, out var un)) - { - return un; - } - - /* - * CUSTOM STRUCT/CLASS SERIALIZATION - */ - if (ReadNullCheck(reader, returnDispose, out var nullCheck)) - { - return nullCheck; - } - - //create type - if (val == null || val == ConstMgr.Null) - { -#if UNITY_2017_1_OR_NEWER - //see if type inherits MonoBehaviour - if (type.IsSubclassOf(typeof(UnityEngine.MonoBehaviour))) - { - val = new UnityEngine.GameObject(type.AssemblyQualifiedName).AddComponent(type); - } - else -#endif - { - val = Activator.CreateInstance(type); - } - } - - //Get Attribute that indicates a class/struct to be serialized - TypeModel.TryGetModel(type, out var model); - - //invalid model - if (model != null && !model.Valid) - { - return val; - } - - //generate model - if (model == null) - { - model = TypeModel.CreateModel(type); - } - - //start Deserialize - foreach (var info in model.Members) - { - //if end, skip - if (reader.EndOfReader) - { - break; - } - - type = info.Type; - - //read basic values - SetMember(info.Member, val, Deserialize(type, ConstMgr.Null, Span.Empty, reader, false)); - } - - if (returnDispose) - { - ObjectPool.Return(reader); - } - - return val; - } - - /// - /// Try deserialize wrapper type - /// - /// - /// - /// - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool TryDeserializeWrapperType(Type type, Reader reader, - [MarshalAs(UnmanagedType.U1)] bool boxed, [MarshalAs(UnmanagedType.U1)] bool returnDispose, - out T ret) - { - if (WrapperManifest.TryGetWrapper(type, out var wrapper)) - { - if (boxed) - { - var obj = wrapper.Deserialize(reader); - ret = obj != null ? (T)obj : default; - } - else - { - ret = ((NinoWrapperBase)wrapper).Deserialize(reader); - } - - if (returnDispose) - ObjectPool.Return(reader); - return true; - } - - ret = default; - return false; - } - - /// - /// Try deserialize code generated type (first time only) - /// - /// - /// - /// - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool TryDeserializeCodeGenType(Type type, Reader reader, - [MarshalAs(UnmanagedType.U1)] bool boxed, [MarshalAs(UnmanagedType.U1)] bool returnDispose, - out T ret) - { - if (TypeModel.TryGetWrapper(type, out var wrapper)) - { - //add wrapper - WrapperManifest.AddWrapper(type, wrapper); - //start Deserialize - if (boxed) - { - var obj = wrapper.Deserialize(reader); - ret = obj != null ? (T)obj : default; - } - else - { - ret = ((NinoWrapperBase)wrapper).Deserialize(reader); - } - - if (returnDispose) - ObjectPool.Return(reader); - return true; - } - - ret = default; - return false; - } - - /// - /// Try deserialize array - /// - /// - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool TryDeserializeArray(Type type, Reader reader, - [MarshalAs(UnmanagedType.U1)] bool returnDispose, out Array ret) - { - if (type.IsArray) - { - ret = reader.ReadArray(type); - if (returnDispose) - { - ObjectPool.Return(reader); - } - - return true; - } - - ret = null; - return false; - } - - /// - /// Try deserialize list - /// - /// - /// - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool TryDeserializeList(Type type, Type genericDefType, Reader reader, - [MarshalAs(UnmanagedType.U1)] bool returnDispose, out IList ret) - { - if (genericDefType == ConstMgr.ListDefType) - { - ret = reader.ReadList(type); - if (returnDispose) - { - ObjectPool.Return(reader); - } - - return true; - } - - ret = null; - return false; - } - - /// - /// Try deserialize dictionary - /// - /// - /// - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool TryDeserializeDict(Type type, Type genericDefType, Reader reader, - [MarshalAs(UnmanagedType.U1)] bool returnDispose, out IDictionary ret) - { - if (genericDefType == ConstMgr.DictDefType) - { - ret = reader.ReadDictionary(type); - if (returnDispose) - { - ObjectPool.Return(reader); - } - - return true; - } - - ret = null; - return false; - } - - /// - /// Try deserialize enum - /// - /// - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool TryDeserializeEnum(Type type, Reader reader, - [MarshalAs(UnmanagedType.U1)] bool returnDispose, out T obj) - { - obj = default; - if (TypeModel.IsEnum(type)) - { - reader.ReadEnum(ref obj); - if (returnDispose) - { - ObjectPool.Return(reader); - } - - return true; - } - - return false; - } - - /// - /// Try deserialize enum - /// - /// - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool TryDeserializeEnum(Type type, Reader reader, - [MarshalAs(UnmanagedType.U1)] bool returnDispose, out object obj) - { - if (TypeModel.IsEnum(type)) - { - var underlyingType = Enum.GetUnderlyingType(type); - var ret = reader.ReadEnum(underlyingType); - obj = Enum.ToObject(type, ret); - if (returnDispose) - { - ObjectPool.Return(reader); - } - - return true; - } - - obj = null; - return false; - } - - /// - /// Try deserialize enum - /// - /// - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool TryDeserializeUnmanagedType(Type type, Reader reader, - [MarshalAs(UnmanagedType.U1)] bool returnDispose, out T obj) - { - obj = default; - if (TypeModel.IsUnmanaged(type)) - { - reader.ReadAsUnmanaged(ref obj, Marshal.SizeOf(type)); - if (returnDispose) - { - ObjectPool.Return(reader); - } - - return true; - } - - return false; - } - - /// - /// Try deserialize enum - /// - /// - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool TryDeserializeUnmanagedType(Type type, Reader reader, - [MarshalAs(UnmanagedType.U1)] bool returnDispose, out object obj) - { - obj = default; - if (TypeModel.IsUnmanaged(type)) - { - reader.ReadAsUnmanaged(ref obj, Marshal.SizeOf(type)); - if (returnDispose) - { - ObjectPool.Return(reader); - } - - return true; - } - - return false; - } - - /// - /// Check for null - /// - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool ReadNullCheck(Reader reader, [MarshalAs(UnmanagedType.U1)] bool returnDispose, - out object obj) - { - obj = null; - if (!reader.ReadBool()) // if null -> readBool will give false - { - if (returnDispose) - { - ObjectPool.Return(reader); - } - - return true; - } - - return false; - } - - /// - /// Set value from MemberInfo - /// - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void SetMember(MemberInfo info, object instance, object val) - { - switch (info) - { - case FieldInfo fo: - fo.SetValue(instance, val); - break; - case PropertyInfo po: - po.SetValue(instance, val); - break; - default: - return; - } - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/Enums/CompressOption.cs b/Nino_Unity/Assets/Nino/Serialization/Enums/CompressOption.cs deleted file mode 100644 index 61ec116..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/Enums/CompressOption.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace Nino.Serialization -{ - /// - /// Compress option - /// 压缩类型 - /// - public enum CompressOption : byte - { - /// - /// zlib (gzip/deflate) compression (high compression ratio but low performance) - /// zlib (gzip/deflate) 压缩模式 (高压缩率低性能) - /// - Zlib = 0, - - /// - /// lz4 compression (average compression ration but high performance) - /// lz4 压缩模式 (平均压缩率高性能) - /// - Lz4 = 1, - - /// - /// no compression (very high performance but huge size) - /// 无压缩 (高性能但体积很大) - /// - NoCompression = 2 - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/Interfaces/INinoWrapper.cs b/Nino_Unity/Assets/Nino/Serialization/Interfaces/INinoWrapper.cs deleted file mode 100644 index e88bc93..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/Interfaces/INinoWrapper.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace Nino.Serialization -{ - public interface INinoWrapper - { - void Serialize(T val, ref Writer writer); - T Deserialize(Reader reader); - int GetSize(T val); - } - - public interface INinoWrapper - { - void Serialize(object val, ref Writer writer); - object Deserialize(Reader reader); - int GetSize(object val); - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/Nino.Serialization.asmdef b/Nino_Unity/Assets/Nino/Serialization/Nino.Serialization.asmdef deleted file mode 100644 index 492dba4..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/Nino.Serialization.asmdef +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "Nino.Serialization", - "references": [ - "Nino.Shared", - "ILRuntime" - ], - "includePlatforms": [], - "excludePlatforms": [], - "allowUnsafeCode": true, - "overrideReferences": false, - "precompiledReferences": [], - "autoReferenced": true, - "defineConstraints": [], - "versionDefines": [], - "noEngineReferences": true -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/Reader.Generic.cs b/Nino_Unity/Assets/Nino/Serialization/Reader.Generic.cs deleted file mode 100644 index 03f8fac..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/Reader.Generic.cs +++ /dev/null @@ -1,469 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace Nino.Serialization -{ - /// - /// Generic methods for reader (ILRuntime hotupdate requests wont access here) - /// - public unsafe partial class Reader - { - /// - /// Read primitive value from binary writer, DO NOT USE THIS FOR CUSTOM EXPORTER - /// Compress and write enum - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public T ReadCommonVal() => - Deserializer.Deserialize(buffer.AsSpan(position, _length - position), this, false); - - /// - /// Compress and write enum - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public T ReadEnum() - { - T val = default; - ReadEnum(ref val); - return val; - } - - /// - /// Compress and write enum - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void ReadEnum(ref T val) - { - if (EndOfReader) return; - - switch (TypeModel.GetTypeCode(typeof(T))) - { - case TypeCode.Byte: - Unsafe.As(ref val) = ReadByte(); - return; - case TypeCode.SByte: - Unsafe.As(ref val) = ReadSByte(); - return; - case TypeCode.Int16: - Unsafe.As(ref val) = ReadInt16(); - return; - case TypeCode.UInt16: - Unsafe.As(ref val) = ReadUInt16(); - return; - case TypeCode.Int32: - Unsafe.As(ref val) = ReadInt32(); - return; - case TypeCode.UInt32: - Unsafe.As(ref val) = ReadUInt32(); - return; - case TypeCode.Int64: - Unsafe.As(ref val) = ReadInt64(); - return; - case TypeCode.UInt64: - Unsafe.As(ref val) = ReadUInt64(); - return; - } - } - - /// - /// Read unmanaged type - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public T Read(int len) where T : unmanaged - { - if (EndOfReader) - { - return default; - } - - var ret = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T))); - position += len; - return ret; - } - - /// - /// Read unmanaged type - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - // ReSharper disable UnusedMember.Local - internal void ReadAsUnmanaged(ref T val, int len) - // ReSharper restore UnusedMember.Local - { - if (EndOfReader) - { - return; - } - - Span span = buffer.AsSpan(position, len); - var first = span[0]; - val = Unsafe.ReadUnaligned(ref first); - position += len; - } - - /// - /// Read unmanaged type - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - // ReSharper disable UnusedMember.Local - public void Read(ref T val, int len) where T : unmanaged - // ReSharper restore UnusedMember.Local - { - if (EndOfReader) - { - return; - } - - val = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T))); - position += len; - } - - /// - /// Read unmanaged type - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Read(ref T1 val1, int len1, ref T2 val2, int len2) where T1 : unmanaged where T2 : unmanaged - { - if (EndOfReader) - { - return; - } - - val1 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T1))); - position += len1; - val2 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T2))); - position += len2; - } - - /// - /// Read unmanaged type - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Read(ref T1 val1, int len1, ref T2 val2, int len2, ref T3 val3, int len3) - where T1 : unmanaged where T2 : unmanaged where T3 : unmanaged - { - if (EndOfReader) - { - return; - } - - val1 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T1))); - position += len1; - val2 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T2))); - position += len2; - val3 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T3))); - position += len3; - } - - /// - /// Read unmanaged type - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Read(ref T1 val1, int len1, ref T2 val2, int len2, ref T3 val3, int len3, - ref T4 val4, int len4) where T1 : unmanaged where T2 : unmanaged where T3 : unmanaged where T4 : unmanaged - { - if (EndOfReader) - { - return; - } - - val1 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T1))); - position += len1; - val2 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T2))); - position += len2; - val3 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T3))); - position += len3; - val4 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T4))); - position += len4; - } - - /// - /// Read unmanaged type - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Read(ref T1 val1, int len1, ref T2 val2, int len2, ref T3 val3, int len3, - ref T4 val4, int len4, ref T5 val5, int len5) where T1 : unmanaged - where T2 : unmanaged - where T3 : unmanaged - where T4 : unmanaged - where T5 : unmanaged - { - if (EndOfReader) - { - return; - } - - val1 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T1))); - position += len1; - val2 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T2))); - position += len2; - val3 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T3))); - position += len3; - val4 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T4))); - position += len4; - val5 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T5))); - position += len5; - } - - /// - /// Read unmanaged type - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Read(ref T1 val1, int len1, ref T2 val2, int len2, ref T3 val3, int len3, - ref T4 val4, int len4, ref T5 val5, int len5, ref T6 val6, int len6) where T1 : unmanaged - where T2 : unmanaged - where T3 : unmanaged - where T4 : unmanaged - where T5 : unmanaged - where T6 : unmanaged - { - if (EndOfReader) - { - return; - } - - val1 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T1))); - position += len1; - val2 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T2))); - position += len2; - val3 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T3))); - position += len3; - val4 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T4))); - position += len4; - val5 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T5))); - position += len5; - val6 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T6))); - position += len6; - } - - /// - /// Read unmanaged type - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Read(ref T1 val1, int len1, ref T2 val2, int len2, ref T3 val3, - int len3, ref T4 val4, int len4, ref T5 val5, int len5, ref T6 val6, int len6, ref T7 val7, int len7) - where T1 : unmanaged - where T2 : unmanaged - where T3 : unmanaged - where T4 : unmanaged - where T5 : unmanaged - where T6 : unmanaged - where T7 : unmanaged - { - if (EndOfReader) - { - return; - } - - val1 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T1))); - position += len1; - val2 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T2))); - position += len2; - val3 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T3))); - position += len3; - val4 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T4))); - position += len4; - val5 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T5))); - position += len5; - val6 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T6))); - position += len6; - val7 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T7))); - position += len7; - } - - /// - /// Read unmanaged type - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Read(ref T1 val1, int len1, ref T2 val2, int len2, ref T3 val3, - int len3, ref T4 val4, int len4, ref T5 val5, int len5, ref T6 val6, int len6, ref T7 val7, int len7, - ref T8 val8, int len8) where T1 : unmanaged - where T2 : unmanaged - where T3 : unmanaged - where T4 : unmanaged - where T5 : unmanaged - where T6 : unmanaged - where T7 : unmanaged - where T8 : unmanaged - { - if (EndOfReader) - { - return; - } - - val1 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T1))); - position += len1; - val2 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T2))); - position += len2; - val3 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T3))); - position += len3; - val4 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T4))); - position += len4; - val5 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T5))); - position += len5; - val6 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T6))); - position += len6; - val7 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T7))); - position += len7; - val8 = MemoryMarshal.Read(buffer.AsSpan(position, sizeof(T8))); - position += len8; - } - - /// - /// Read nullable - /// - /// - /// - public T? ReadNullable() where T : struct - { - if (!ReadBool()) - { - return null; - } - - return ReadCommonVal(); - } - - - /// - /// Read Array - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public T[] ReadArray() - { - if (EndOfReader) return default; - //check null - if (!ReadBool()) return null; - - //read len - int len = ReadLength(); - - T[] arr = new T[len]; - //read item - int i = 0; - while (i < len) - { - arr[i++] = ReadCommonVal(); - } - - return arr; - } - - /// - /// Read list - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public List ReadList() - { - if (EndOfReader) return default; - //check null - if (!ReadBool()) return null; - //read len - int len = ReadLength(); - List lst = new List(); - //read item - while (len-- > 0) - { - lst.Add(ReadCommonVal()); - } - - return lst; - } - - /// - /// Read hashset - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public HashSet ReadHashSet() - { - if (EndOfReader) return default; - //check null - if (!ReadBool()) return null; - //read len - int len = ReadLength(); - HashSet lst = new HashSet(); - //read item - while (len-- > 0) - { - lst.Add(ReadCommonVal()); - } - - return lst; - } - - /// - /// Read Queue - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public Queue ReadQueue() - { - if (EndOfReader) return default; - //check null - if (!ReadBool()) return null; - //read len - int len = ReadLength(); - Queue lst = new Queue(); - //read item - while (len-- > 0) - { - lst.Enqueue(ReadCommonVal()); - } - - return lst; - } - - /// - /// Read Stack - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public Stack ReadStack() - { - if (EndOfReader) return default; - //reverse stack - var arr = ReadArray(); - if (arr == null) - { - return null; - } - - Array.Reverse(arr); - var lst = new Stack(arr); - - return lst; - } - - /// - /// Read Dictionary - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public Dictionary ReadDictionary() - { - if (EndOfReader) return default; - if (!ReadBool()) return null; - //read len - int len = ReadLength(); - Dictionary dic = new Dictionary(); - //read item - while (len-- > 0) - { - var key = ReadCommonVal(); - var val = ReadCommonVal(); - dic.Add(key, val); - } - - return dic; - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/Reader.cs b/Nino_Unity/Assets/Nino/Serialization/Reader.cs deleted file mode 100644 index a22f87f..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/Reader.cs +++ /dev/null @@ -1,443 +0,0 @@ -using System; -using Nino.Shared.IO; -using Nino.Shared.Mgr; -using System.Collections; -using System.Runtime.CompilerServices; - -namespace Nino.Serialization -{ - /// - /// A read that Reads serialization Data - /// - public unsafe partial class Reader - { - /// - /// block size when creating buffer - /// - private const ushort BufferBlockSize = ushort.MaxValue; - - /// - /// Buffer that stores data - /// - private ExtensibleBuffer buffer; - - /// - /// Position of the current buffer - /// - private int position; - - /// - /// Length of the current reader - /// - private int _length; - - /// - /// End of Reader - /// - public bool EndOfReader => position >= _length; - - /// - /// Create an empty reader, need to set up values - /// - public Reader() - { - } - - /// - /// Create a nino read - /// - /// - /// - public Reader(byte[] data, int outputLength) - { - Init(data, outputLength); - } - - /// - /// Create a nino read - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void Init(IntPtr data, int outputLength) - { - if (buffer == null) - { - var peak = ObjectPool>.Peak(); - if (peak != null && peak.ExpandSize == BufferBlockSize) - { - buffer = ObjectPool>.Request(); - } - else - { - buffer = new ExtensibleBuffer(BufferBlockSize); - } - } - - buffer.CopyFrom((byte*)data, 0, 0, outputLength); - position = 0; - _length = outputLength; - } - - /// - /// Create a nino reader - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Init(Span data, int outputLength) - { - fixed (byte* ptr = &data.GetPinnableReference()) - { - Init((IntPtr)ptr, outputLength); - } - } - - /// - /// Create a nino reader - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Init(byte[] data, int outputLength) - { - fixed (byte* ptr = data) - { - Init((IntPtr)ptr, outputLength); - } - } - - /// - /// Get Length - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public int ReadLength() => ReadInt32(); - - /// - /// Read primitive value from binary writer, DO NOT USE THIS FOR CUSTOM EXPORTER - /// Compress and write enum - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public object ReadCommonVal(Type type) => - Deserializer.Deserialize(type, ConstMgr.Null, ConstMgr.Null, this, false); - - /// - /// Read a byte - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public byte ReadByte() - { - if (EndOfReader) return default; - - return buffer[position++]; - } - - /// - /// Read byte[] - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public byte[] ReadBytes(int len) - { - if (EndOfReader) return default; - - byte[] ret = new byte[len]; - fixed (byte* ptr = ret) - { - buffer.CopyTo(ptr, position, len); - position += len; - } - - return ret; - } - - /// - /// Copy buffer to a buffer, usually buffer allocated with stackalloc - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void ReadToBuffer(byte* ptr, int len) - { - buffer.CopyTo(ptr, position, len); - position += len; - } - - /// - /// Read sbyte - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public sbyte ReadSByte() => Unsafe.As(ref buffer.Data[position++]); - - /// - /// Read char - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public char ReadChar() => Read(ConstMgr.SizeOfUShort); - - /// - /// Read DateTime - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public DateTime ReadDateTime() - { - if (EndOfReader) return default; - - return Read(ConstMgr.SizeOfLong); - } - - /// - /// Read short - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public short ReadInt16() => Read(ConstMgr.SizeOfShort); - - /// - /// Read ushort - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ushort ReadUInt16() => Read(ConstMgr.SizeOfUShort); - - /// - /// Read int - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public int ReadInt32() => Read(ConstMgr.SizeOfInt); - - /// - /// Read uint - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public uint ReadUInt32() => Read(ConstMgr.SizeOfUInt); - - /// - /// Read long - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public long ReadInt64() => Read(ConstMgr.SizeOfLong); - - /// - /// Read ulong - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ulong ReadUInt64() => Read(ConstMgr.SizeOfULong); - - /// - /// Read float - /// - /// - [System.Security.SecuritySafeCritical] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public float ReadSingle() => Read(ConstMgr.SizeOfUInt); - - /// - /// Read float - /// - /// - [System.Security.SecuritySafeCritical] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public float ReadFloat() => ReadSingle(); - - /// - /// Read double - /// - /// - [System.Security.SecuritySafeCritical] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public double ReadDouble() => Read(ConstMgr.SizeOfULong); - - /// - /// Read decimal - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public decimal ReadDecimal() => Read(ConstMgr.SizeOfDecimal); - - /// - /// Read bool - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool ReadBool() - { - if (EndOfReader) return default; - - return buffer[position++] == 1; - } - - /// - /// Read string - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public string ReadString() - { - if (EndOfReader) return default; - if (!ReadBool()) return null; - - int len = ReadInt32(); - //empty string -> no gc - if (len == 0) - { - return String.Empty; - } - - byte* ptr = buffer.Data + position; - position += len; - char* chars = (char*)ptr; - return new string(chars, 0, len / ConstMgr.SizeOfUShort); - } - - /// - /// Compress and write enum - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ulong ReadEnum(Type enumType) - { - if (EndOfReader) return default; - - switch (TypeModel.GetTypeCode(enumType)) - { - case TypeCode.Byte: - return ReadByte(); - case TypeCode.SByte: - return (ulong)ReadSByte(); - case TypeCode.Int16: - return (ulong)ReadInt16(); - case TypeCode.UInt16: - return ReadUInt16(); - case TypeCode.Int32: - return (ulong)ReadInt32(); - case TypeCode.UInt32: - return ReadUInt32(); - case TypeCode.Int64: - return (ulong)ReadInt64(); - case TypeCode.UInt64: - return ReadUInt64(); - } - - return 0; - } - - /// - /// Read Array - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public Array ReadArray(Type type) - { - if (EndOfReader) return default; - - //basic type - if (WrapperManifest.TryGetWrapper(type, out var wrapper)) - { - var ret = wrapper.Deserialize(this); - return (Array)ret; - } - - //other type - //check null - if (!ReadBool()) return null; - var elemType = type.GetElementType(); - if (elemType == null) - { - throw new NullReferenceException("element type is null, can not make array"); - } - - //read len - int len = ReadLength(); - - Array arr = Array.CreateInstance(elemType, len); - //read item - int i = 0; - while (i < len) - { - var obj = ReadCommonVal(elemType); - arr.SetValue(obj, i++); - } - - return arr; - } - - /// - /// Read list - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public IList ReadList(Type type) - { - if (EndOfReader) return default; - - //basic type - if (WrapperManifest.TryGetWrapper(type, out var wrapper)) - { - var ret = wrapper.Deserialize(this); - return (IList)ret; - } - - //other - //check null - if (!ReadBool()) return null; - var elemType = type.GenericTypeArguments[0]; - - //read len - int len = ReadLength(); - - IList arr = Activator.CreateInstance(type, ConstMgr.EmptyParam) as IList; - //read item - int i = 0; - while (i++ < len) - { - var obj = ReadCommonVal(elemType); - arr?.Add(obj); - } - - return arr; - } - - /// - /// Read Dictionary - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public IDictionary ReadDictionary(Type type) - { - if (EndOfReader) return default; - if (!ReadBool()) return null; - - //parse dict type - var args = type.GetGenericArguments(); - Type keyType = args[0]; - Type valueType = args[1]; - - var dict = Activator.CreateInstance(type) as IDictionary; - - //read len - int len = ReadLength(); - - //read item - int i = 0; - while (i++ < len) - { - //read key - var key = ReadCommonVal(keyType); - //read value - var val = ReadCommonVal(valueType); - - //add - dict?.Add(key, val); - } - - return dict; - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/Serializer.Generic.cs b/Nino_Unity/Assets/Nino/Serialization/Serializer.Generic.cs deleted file mode 100644 index 65dad70..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/Serializer.Generic.cs +++ /dev/null @@ -1,418 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace Nino.Serialization -{ - public static partial class Serializer - { - /// - /// Attempt to serialize hard-coded types + code gen types + custom delegate types - /// - /// - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool TrySerializeWrapperType(Type type, ref T value, ref Writer writer) - { - //basic type - if (!WrapperManifest.TryGetWrapper(type, out var wrapper)) - { - return false; - } - - if (wrapper is NinoWrapperBase @base) - { - @base.Serialize(value, ref writer); - } - else - { - wrapper.Serialize(value, ref writer); - } - - return true; - } - - /// - /// Attempt to serialize enum - /// - /// - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool TrySerializeEnumType(Type type, ref T value, ref Writer writer) - { - //enum - if (!TypeModel.IsEnum(type)) - { - return false; - } - - writer.WriteEnum(value); - return true; - } - - /// - /// Attempt to serialize unmanaged type - /// - /// - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool TrySerializeUnmanagedType(Type type, ref T value, ref Writer writer) - { - //enum - if (!TypeModel.IsUnmanaged(type)) - { - return false; - } - - writer.WriteAsUnmanaged(ref value, Marshal.SizeOf()); - return true; - } - - /// - /// Attempt to serialize code gen type (first time only) - /// - /// - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool TrySerializeCodeGenType(Type type, ref T value, ref Writer writer) - { - //code generated type - if (!TypeModel.TryGetWrapper(type, out var wrapper)) - { - return false; - } - - //add wrapper - WrapperManifest.AddWrapper(type, wrapper); - - //start serialize - if (wrapper is NinoWrapperBase @base) - { - @base.Serialize(value, ref writer); - } - else - { - wrapper.Serialize(value, ref writer); - } - - return true; - } - - /// - /// Attempt to serialize array - /// - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool TrySerializeArray(ref T value, ref Writer writer) - { - //array - if (!(value is Array arr)) - { - return false; - } - - writer.Write(arr); - return true; - } - - /// - /// Attempt to serialize list (boxed) - /// - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool TrySerializeList(ref T value, ref Writer writer) - { - if (!(value is IList lst)) - { - return false; - } - - writer.Write(lst); - return true; - } - - /// - /// Attempt to serialize dict - /// - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool TrySerializeDict(ref T value, ref Writer writer) - { - if (!(value is IDictionary dict)) - { - return false; - } - - writer.Write(dict); - return true; - } - - /// - /// Serialize an array of NinoSerialize object - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static byte[] Serialize(T[] val) - { - int length = GetSize(in val); - if (length == 0) - { - return Array.Empty(); - } - - byte[] ret = new byte[length]; - if (val == null) - { - return ret; - } - - Writer writer = new Writer(ret.AsSpan(), 0); - - /* - * HARD-CODED SERIALIZATION - */ - if (TrySerializeWrapperType(typeof(T[]), ref val, ref writer)) - { - return ret; - } - - //attempt to serialize using generic method - writer.Write(val); - return ret; - } - - /// - /// Serialize a nullable of NinoSerialize struct - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static byte[] Serialize(T? val) where T : struct - { - int length = GetSize(in val); - if (length == 0) - { - return Array.Empty(); - } - - byte[] ret = new byte[length]; - if (val == null) - { - return ret; - } - - Writer writer = new Writer(ret.AsSpan(), 0); - - //attempt to serialize using generic method - writer.Write(val); - return ret; - } - - /// - /// Serialize a list of NinoSerialize object - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static byte[] Serialize(List val) - { - int length = GetSize(in val); - if (length == 0) - { - return Array.Empty(); - } - - byte[] ret = new byte[length]; - if (val == null) - { - return ret; - } - - Writer writer = new Writer(ret.AsSpan(), 0); - - /* - * HARD-CODED SERIALIZATION - */ - if (TrySerializeWrapperType(typeof(List), ref val, ref writer)) - { - return ret; - } - - //attempt to serialize using generic method - writer.Write(val); - return ret; - } - - /// - /// Serialize a hashset of NinoSerialize object - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static byte[] Serialize(HashSet val) - { - int length = GetSize(in val); - if (length == 0) - { - return Array.Empty(); - } - - byte[] ret = new byte[length]; - if (val == null) - { - return ret; - } - - Writer writer = new Writer(ret.AsSpan(), 0); - - /* - * HARD-CODED SERIALIZATION - */ - if (TrySerializeWrapperType(typeof(HashSet), ref val, ref writer)) - { - return ret; - } - - //attempt to serialize using generic method - writer.Write(val); - return ret; - } - - /// - /// Serialize a hashset of NinoSerialize object - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static byte[] Serialize(Queue val) - { - int length = GetSize(in val); - if (length == 0) - { - return Array.Empty(); - } - - byte[] ret = new byte[length]; - if (val == null) - { - return ret; - } - - Writer writer = new Writer(ret.AsSpan(), 0); - - /* - * HARD-CODED SERIALIZATION - */ - if (TrySerializeWrapperType(typeof(Queue), ref val, ref writer)) - { - return ret; - } - - //attempt to serialize using generic method - writer.Write(val); - return ret; - } - - /// - /// Serialize a hashset of NinoSerialize object - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static byte[] Serialize(Stack val) - { - int length = GetSize(in val); - if (length == 0) - { - return Array.Empty(); - } - - byte[] ret = new byte[length]; - if (val == null) - { - return ret; - } - - Writer writer = new Writer(ret.AsSpan(), 0); - - /* - * HARD-CODED SERIALIZATION - */ - if (TrySerializeWrapperType(typeof(Stack), ref val, ref writer)) - { - return ret; - } - - //attempt to serialize using generic method - writer.Write(val); - return ret; - } - - /// - /// Serialize a dictionary of NinoSerialize object - /// - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static byte[] Serialize(Dictionary val) - { - int length = GetSize(in val); - if (length == 0) - { - return Array.Empty(); - } - - byte[] ret = new byte[length]; - if (val == null) - { - return ret; - } - - Writer writer = new Writer(ret.AsSpan(), 0); - - /* - * HARD-CODED SERIALIZATION - */ - if (TrySerializeWrapperType(typeof(Dictionary), ref val, ref writer)) - { - return ret; - } - - //attempt to serialize using generic method - writer.Write(val); - return ret; - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/Serializer.Helper.cs b/Nino_Unity/Assets/Nino/Serialization/Serializer.Helper.cs deleted file mode 100644 index bc20e19..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/Serializer.Helper.cs +++ /dev/null @@ -1,437 +0,0 @@ -// Serializer.Helper.cs -// -// Author: -// JasonXuDeveloper(傑) -// -// Copyright (c) 2023 Nino - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using Nino.Shared.Mgr; - -namespace Nino.Serialization -{ - public static partial class Serializer - { - private static readonly Dictionary FixedSizeCache = new Dictionary() - { - { typeof(bool), 1 }, - { typeof(byte), 1 }, - { typeof(sbyte), 1 }, - { typeof(char), 2 }, - { typeof(short), 2 }, - { typeof(ushort), 2 }, - { typeof(int), 4 }, - { typeof(uint), 4 }, - { typeof(long), 8 }, - { typeof(ulong), 8 }, - { typeof(float), 4 }, - { typeof(double), 8 }, - { typeof(decimal), 16 }, - { typeof(DateTime), 8 }, - { typeof(TimeSpan), 8 }, - { typeof(Guid), 16 }, - { typeof(IntPtr), 8 }, - { typeof(UIntPtr), 8 }, - }; - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static int GetFixedSize() - { - if (FixedSizeCache.TryGetValue(typeof(T), out var size)) - { - return size; - } - - return -1; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static int GetFixedSize(Type type) - { - if (FixedSizeCache.TryGetValue(type, out var size)) - { - return size; - } - - return -1; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void SetFixedSize(int size) - { - FixedSizeCache[typeof(T)] = size; - } - - public static int GetSize(in T[] val = default, Dictionary members = null) - { - if (val == null) return 1; - var type = typeof(T); - int length = val.Length; - - if (!WrapperManifest.TryGetWrapper(type, out var wrapper)) - { - if (TypeModel.TryGetWrapper(type, out wrapper)) - { - WrapperManifest.AddWrapper(type, wrapper); - } - } - - if (TypeModel.IsUnmanaged(type)) - { - return Unsafe.SizeOf() * length + 1 + 4; - } - - if (FixedSizeCache.TryGetValue(type, out var size)) - { - return 1 + 4 + length * size; - } - - return GetSize(typeof(T[]), val, members); - } - - public static int GetSize(in List val = default, Dictionary members = null) - { - if (val == null) return 1; - var type = typeof(T); - int length = val.Count; - - if (!WrapperManifest.TryGetWrapper(type, out var wrapper)) - { - if (TypeModel.TryGetWrapper(type, out wrapper)) - { - WrapperManifest.AddWrapper(type, wrapper); - } - } - - if (TypeModel.IsUnmanaged(type)) - { - return Unsafe.SizeOf() * length + 1 + 4; - } - - if (FixedSizeCache.TryGetValue(type, out var size)) - { - return 1 + 4 + length * size; - } - - return GetSize(typeof(List), val, members); - } - - public static int GetSize(in T? val = default, Dictionary members = null) - where T : struct - { - if (val == null) return 1; - var type = typeof(T); - - if (!WrapperManifest.TryGetWrapper(type, out var wrapper)) - { - if (TypeModel.TryGetWrapper(type, out wrapper)) - { - WrapperManifest.AddWrapper(type, wrapper); - } - } - - if (TypeModel.IsUnmanaged(type)) - { - return Unsafe.SizeOf() + 1; - } - - if (FixedSizeCache.TryGetValue(type, out var size)) - { - return 1 + size; - } - - return GetSize(typeof(T?), val, members); - } - - public static int GetSize(in T val = default, Dictionary members = null) - { - var type = typeof(T); - int size = 0; - if (TypeModel.IsEnum(type)) type = type.GetEnumUnderlyingType(); - - //nullable - if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) - { - type = type.GetGenericArguments()[0]; - size += 1; - } - - if (val == null) return 1; - - if (FixedSizeCache.TryGetValue(type, out var size2)) - { - return size + size2; - } - - if (!WrapperManifest.TryGetWrapper(type, out var wrapper)) - { - //code generated type - if (TypeModel.TryGetWrapper(type, out wrapper)) - { - //add wrapper - WrapperManifest.AddWrapper(type, wrapper); - } - } - - if (wrapper != null) - { - if (wrapper is NinoWrapperBase @base) - { - return size + @base.GetSize(val); - } - - return size + wrapper.GetSize(val); - } - - if (TypeModel.IsUnmanaged(type)) - { - return Unsafe.SizeOf(); - } - - return GetSize(type, val, members); - } - - public static int GetSize(Type type, object obj, Dictionary members = null) - { - if (TypeModel.IsEnum(type)) type = type.GetEnumUnderlyingType(); - - int size = 0; - bool isGeneric = type.IsGenericType; - Type genericTypeDef = null; - Type[] genericArgs = null; - if (isGeneric) - { - genericTypeDef = type.GetGenericTypeDefinition(); - genericArgs = type.GetGenericArguments(); - } - - //nullable - if (genericTypeDef != null && genericTypeDef == typeof(Nullable<>)) - { - type = genericArgs[0]; - size += 1; - } - - if (obj == null) return 1; - - if (FixedSizeCache.TryGetValue(type, out var size2)) - { - return size + size2; - } - - if (!WrapperManifest.TryGetWrapper(type, out var wrapper)) - { - //code generated type - if (TypeModel.TryGetWrapper(type, out wrapper)) - { - //add wrapper - WrapperManifest.AddWrapper(type, wrapper); - } - } - - if (wrapper != null) - { - return size + wrapper.GetSize(obj); - } - - if (TypeModel.IsUnmanaged(type)) - { - return Marshal.SizeOf(type); - } - - size = 1; //null indicator - - if (type == ConstMgr.ObjectType) - { - type = obj.GetType(); - } - - if (type.IsArray) - { - var elementType = type.GetElementType(); - var array = obj as Array; - if (array == null) - { - return size; - } - - size += 4; //length - if (array.Length == 0) return size; - - if (elementType != null && FixedSizeCache.TryGetValue(elementType, out var eleSize)) - { - size += eleSize * array.Length; - return size; - } - - foreach (var item in array) - { - size += GetSize(elementType, item); - } - - return size; - } - - if (isGeneric && genericTypeDef != null) - { - switch (genericTypeDef) - { - case var _ when genericTypeDef.GetInterface(nameof(IList)) != null: - var lstElemType = genericArgs[0]; - var lst = obj as ICollection; - if (lst == null) - { - return size; - } - - size += 4; //length - if (lst.Count == 0) return size; - - if (FixedSizeCache.TryGetValue(lstElemType, out var lstEleSize)) - { - size += lstEleSize * lst.Count; - return size; - } - - foreach (var item in lst) - { - size += GetSize(lstElemType, item); - } - - return size; - case var _ when genericTypeDef.GetInterface(nameof(IDictionary)) != null: - var keyType = genericArgs[0]; - var valueType = genericArgs[1]; - var dict = obj as IDictionary; - if (dict == null) - { - return size; - } - - size += 4; //length - if (dict.Count == 0) return size; - - bool hasKeySize = FixedSizeCache.TryGetValue(keyType, out var keySize); - bool hasValueSize = FixedSizeCache.TryGetValue(valueType, out var valueSize); - - if (hasKeySize && hasValueSize) - { - size += (keySize + valueSize) * dict.Count; - return size; - } - - if (hasKeySize) - { - size += keySize * dict.Count; - foreach (var item in dict.Values) - { - size += GetSize(valueType, item); - } - - return size; - } - - if (hasValueSize) - { - size += valueSize * dict.Count; - foreach (var item in dict.Keys) - { - size += GetSize(keyType, item); - } - - return size; - } - - foreach (DictionaryEntry item in dict) - { - size += GetSize(keyType, item.Key); - size += GetSize(valueType, item.Value); - } - - return size; - case var _ when genericTypeDef.GetInterface(nameof(ICollection)) != null: - var elementType2 = genericArgs[0]; - var collection = obj as ICollection; - if (collection == null) - { - return size; - } - - size += 4; //length - if (collection.Count == 0) return size; - - if (FixedSizeCache.TryGetValue(elementType2, out var eleSize)) - { - size += eleSize * collection.Count; - return size; - } - - foreach (var item in collection) - { - size += GetSize(elementType2, item); - } - - return size; - case var _ when genericTypeDef.GetInterface(nameof(IEnumerable)) != null: - var elementType = genericArgs[0]; - var enumerable = obj as IEnumerable; - if (enumerable == null) - { - return size; - } - - size += 4; //length - - var enumerator = enumerable.GetEnumerator(); - if (!enumerator.MoveNext()) return size; - do - { - size += GetSize(elementType, enumerator.Current); - } while (enumerator.MoveNext()); - - return size; - } - } - - //Nino serializable type - TypeModel.TryGetModel(type, out var model); - - //invalid model - if (model != null && !model.Valid) - { - throw new InvalidOperationException($"Invalid model for type {type}"); - } - - //generate model - if (model == null) - { - model = TypeModel.CreateModel(type); - } - - var isFixed = true; - foreach (var info in model.Members) - { - object memberObj = info.GetValue(obj); - if (members != null) - { - members[info.Member] = memberObj; - } - - size += GetSize(info.Type, memberObj); - if (!FixedSizeCache.ContainsKey(info.Type)) - { - isFixed = false; - } - } - - if (isFixed) - FixedSizeCache[type] = size; - return size; - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/Serializer.cs b/Nino_Unity/Assets/Nino/Serialization/Serializer.cs deleted file mode 100644 index 5b2f0b7..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/Serializer.cs +++ /dev/null @@ -1,196 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Runtime.CompilerServices; -using Nino.Shared.IO; - -namespace Nino.Serialization -{ - public static partial class Serializer - { - /// - /// Serialize a NinoSerialize object - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static byte[] Serialize(in T val) - { - Dictionary fields = ObjectPool>.Request(); - fields.Clear(); - int length = GetSize(in val, fields); - if (length == 0) - { - return Array.Empty(); - } - - byte[] ret = new byte[length]; - if (val == null) - { - ObjectPool>.Return(fields); - return ret; - } - - Serialize(typeof(T), val, fields, ret.AsSpan(), 0); - ObjectPool>.Return(fields); - return ret; - } - - /// - /// Serialize a NinoSerialize object - /// - /// - /// - /// - /// - /// actual written size - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static int Serialize(Span buffer, in T val, Dictionary fields = null) - { - if (val == null) - { - buffer[0] = 0; - return 1; - } - - return Serialize(typeof(T), val, fields, buffer, 0); - } - - /// - /// Serialize a NinoSerialize object - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static byte[] Serialize(object val) - { - Dictionary fields = ObjectPool>.Request(); - fields.Clear(); - int length = GetSize(in val, fields); - if (length == 0) - { - return Array.Empty(); - } - - byte[] ret = new byte[length]; - if (val == null) - { - ObjectPool>.Return(fields); - return ret; - } - - Serialize(val.GetType(), val, fields, ret.AsSpan(), 0); - ObjectPool>.Return(fields); - return ret; - } - - /// - /// Serialize a NinoSerialize object - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static int Serialize(Span buffer, object val) - { - if (val == null) - { - buffer[0] = 0; - return 1; - } - - return Serialize(val.GetType(), val, null, buffer, 0); - } - - internal static int Serialize(Type type, T value, Dictionary fields, Span buffer, - int pos) - { - Writer writer = new Writer(buffer, pos); - - //null check - if (value == null) - { - writer.Write(false); // false -> is null - return writer.Position; - } - - /* - * HARD-CODED SERIALIZATION - */ - - if (TrySerializeWrapperType(type, ref value, ref writer)) - { - return writer.Position; - } - - if (TrySerializeEnumType(type, ref value, ref writer)) - { - return writer.Position; - } - - if (TrySerializeCodeGenType(type, ref value, ref writer)) - { - return writer.Position; - } - - if (TrySerializeUnmanagedType(type, ref value, ref writer)) - { - return writer.Position; - } - - if (TrySerializeArray(ref value, ref writer)) - { - return writer.Position; - } - - //generic - if (type.IsGenericType) - { - if (TrySerializeList(ref value, ref writer)) - { - return writer.Position; - } - - if (TrySerializeDict(ref value, ref writer)) - { - return writer.Position; - } - } - - /* - * CUSTOM STRUCT/CLASS SERIALIZATION - */ - writer.Write(true); //true -> not null - - //Get Attribute that indicates a class/struct to be serialized - TypeModel.TryGetModel(type, out var model); - - //invalid model - if (model != null && !model.Valid) - { - return 0; - } - - //generate model - if (model == null) - { - model = TypeModel.CreateModel(type); - } - - //serialize all recorded members - foreach (var info in model.Members) - { - type = info.Type; - if (fields == null || !fields.TryGetValue(info.Member, out var obj)) - { - obj = info.GetValue(value); - } - - writer.Position = Serialize(type, obj, null, buffer, writer.Position); - } - - return writer.Position; - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/TypeModel.cs b/Nino_Unity/Assets/Nino/Serialization/TypeModel.cs deleted file mode 100644 index 164af57..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/TypeModel.cs +++ /dev/null @@ -1,348 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Concurrent; -using Nino.Shared.Util; -using System.Reflection; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Threading; -using Nino.Shared.IO; - -// ReSharper disable CognitiveComplexity - -namespace Nino.Serialization -{ - /// - /// A model of a serialized type - /// - internal class TypeModel - { - private const string HelperName = "NinoSerializationHelper"; - - private const BindingFlags ReflectionFlags = - BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Default; - - private const BindingFlags StaticReflectionFlags = ReflectionFlags | BindingFlags.Static; - private const BindingFlags FlattenHierarchyReflectionFlags = ReflectionFlags | BindingFlags.FlattenHierarchy; - private static readonly Type NinoSerializeType = typeof(NinoSerializeAttribute); - private static readonly Type NinoMemberType = typeof(NinoMemberAttribute); - private static readonly Type NinoIgnoreType = typeof(NinoIgnoreAttribute); - private static readonly Type CompilerGeneratedType = typeof(CompilerGeneratedAttribute); - - public List Members; - - public struct NinoMember - { - public MemberInfo Member; - public Type Type; - public Func GetValue; - - public NinoMember(MemberInfo member, Type type, Func getValue) - { - Member = member; - Type = type; - GetValue = getValue; - } - } - - public bool Valid; - public bool IncludeAll; - - /// - /// Cached Models - /// - private static readonly Dictionary TypeModels = new Dictionary(10); - - /// - /// Cached Models - /// - private static readonly Dictionary TypeCodes = new Dictionary(30) - { - { typeof(byte).GetTypeHashCode(), TypeCode.Byte }, - { typeof(sbyte).GetTypeHashCode(), TypeCode.SByte }, - { typeof(short).GetTypeHashCode(), TypeCode.Int16 }, - { typeof(ushort).GetTypeHashCode(), TypeCode.UInt16 }, - { typeof(int).GetTypeHashCode(), TypeCode.Int32 }, - { typeof(uint).GetTypeHashCode(), TypeCode.UInt32 }, - { typeof(long).GetTypeHashCode(), TypeCode.Int64 }, - { typeof(ulong).GetTypeHashCode(), TypeCode.UInt64 }, - { typeof(float).GetTypeHashCode(), TypeCode.Single }, - { typeof(double).GetTypeHashCode(), TypeCode.Double }, - { typeof(decimal).GetTypeHashCode(), TypeCode.Decimal }, - { typeof(char).GetTypeHashCode(), TypeCode.Char }, - { typeof(bool).GetTypeHashCode(), TypeCode.Boolean }, - { typeof(string).GetTypeHashCode(), TypeCode.String }, - { typeof(object).GetTypeHashCode(), TypeCode.Object }, - { typeof(DateTime).GetTypeHashCode(), TypeCode.DateTime }, - }; - - /// - /// Generated helpers - /// - private static readonly Dictionary GeneratedWrapper = new Dictionary(50) - { - { typeof(byte).GetTypeHashCode(), null }, - { typeof(sbyte).GetTypeHashCode(), null }, - { typeof(short).GetTypeHashCode(), null }, - { typeof(ushort).GetTypeHashCode(), null }, - { typeof(int).GetTypeHashCode(), null }, - { typeof(uint).GetTypeHashCode(), null }, - { typeof(long).GetTypeHashCode(), null }, - { typeof(ulong).GetTypeHashCode(), null }, - { typeof(bool).GetTypeHashCode(), null }, - { typeof(float).GetTypeHashCode(), null }, - { typeof(double).GetTypeHashCode(), null }, - { typeof(decimal).GetTypeHashCode(), null }, - { typeof(char).GetTypeHashCode(), null }, - { typeof(string).GetTypeHashCode(), null }, - { typeof(DateTime).GetTypeHashCode(), null }, - }; - - /// - /// Cached Models - /// - private static readonly ConcurrentDictionary IsEnumTypeCache = - new ConcurrentDictionary(3, 30); - - /// - /// Get a type code - /// - /// - /// - internal static TypeCode GetTypeCode(Type type) - { - var hash = type.GetTypeHashCode(); - if (TypeCodes.TryGetValue(hash, out var ret)) - { - return ret; - } - - TypeCodes[hash] = ret = Type.GetTypeCode(type); - return ret; - } - - public static bool IsFixedSizeType(Type type) - { - if (type.IsClass) return false; - return IsUnmanaged(type); - } - - private static readonly ConcurrentDictionary IsManagedTypeCache = - new ConcurrentDictionary(); - - public static bool IsUnmanaged(Type type) - { - if (type.IsPrimitive || IsEnum(type)) return true; - if (!type.IsValueType) return false; - // check if we already know the answer - if (!IsManagedTypeCache.TryGetValue(type, out var ret)) - { - ret = true; - // otherwise check recursively - var fields = type - .GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); - foreach (var field in fields) - { - if (field.GetCustomAttributes(CompilerGeneratedType, true).Length > 0 || - !IsUnmanaged(field.FieldType)) - { - ret = false; - break; - } - } - - IsManagedTypeCache[type] = ret; - } - - return ret; - } - - /// - /// Get whether or not a type is enum - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static bool IsEnum(Type type) - { - if (IsEnumTypeCache.TryGetValue(type, out var ret)) return ret; - IsEnumTypeCache[type] = ret = type.IsEnum; - return ret; - } - - /// - /// Get whether or not a type is a code gen type - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static bool TryGetWrapper(Type type, out INinoWrapper helper) - { - var hash = type.GetTypeHashCode(); - if (GeneratedWrapper.TryGetValue(hash, out helper)) return helper != null; - - var field = type.GetField(HelperName, StaticReflectionFlags); - helper = (INinoWrapper)field?.GetValue(null); - GeneratedWrapper[hash] = helper; - return helper != null; - } - - /// - /// Try get cached model - /// - /// - /// - /// - internal static void TryGetModel(Type type, out TypeModel model) - { - var hash = type.GetTypeHashCode(); - if (TypeModels.TryGetValue(hash, out model)) return; - object[] ns = type.GetCustomAttributes(NinoSerializeType, false); - if (ns.Length != 0) return; - model = new TypeModel() - { - Valid = false - }; - TypeModels.Add(hash, model); - throw new InvalidOperationException( - $"The type {type.FullName} does not have NinoSerialize attribute or custom importer/exporter"); - } - - /// - /// Thread safe lock - /// - private static SpinLock _createLock; - - /// - /// Create a typeModel using given type - /// - /// - /// - // ReSharper disable CognitiveComplexity - internal static TypeModel CreateModel(Type type) - // ReSharper restore CognitiveComplexity - { - TypeModel model; - //thread safe - bool lockTaken = false; - try - { - _createLock.Enter(ref lockTaken); - TryGetModel(type, out model); - if (model != null) return model; - model = new TypeModel - { - Valid = true, - //fetch members - Members = new List(), - }; - - //include all or not - object[] ns = type.GetCustomAttributes(NinoSerializeType, true); - model.IncludeAll = ((NinoSerializeAttribute)ns[0]).IncludeAll; - - //flag - ushort index = 0; - //dict - SortedDictionary dict = ObjectPool>.Request(); - dict.Clear(); - - //fetch fields (only public and private fields that declared in the type) - FieldInfo[] fs = type.GetFields(FlattenHierarchyReflectionFlags); - //iterate fields - foreach (var f in fs) - { - if (f.GetCustomAttributes(CompilerGeneratedType, true).Length > 0) - { - continue; - } - - if (model.IncludeAll) - { - //skip nino ignore - var ig = f.GetCustomAttributes(NinoIgnoreType, true); - if (ig.Length > 0) continue; - index++; - } - else - { - ns = f.GetCustomAttributes(NinoMemberType, true); - //not fetch all and no attribute => skip this member - if (ns.Length != 1) continue; - index = ((NinoMemberAttribute)ns[0]).Index; - } - - //record field - dict.Add(index, f); - } - - //fetch properties (only public and private properties that declared in the type) - PropertyInfo[] ps = type.GetProperties(FlattenHierarchyReflectionFlags); - //iterate properties - foreach (var p in ps) - { - if (model.IncludeAll) - { - //skip nino ignore - var ig = p.GetCustomAttributes(NinoIgnoreType, true); - if (ig.Length > 0) continue; - } - - if (model.IncludeAll) - { - index++; - } - else - { - ns = p.GetCustomAttributes(NinoMemberType, true); - //not fetch all and no attribute => skip this member - if (ns.Length != 1) continue; - - //has to have getter and setter - if (!(p.CanRead && p.CanWrite)) - { - if (model.IncludeAll) continue; - throw new InvalidOperationException( - $"Cannot read or write property {p.Name} in {type.FullName}, cannot Serialize or Deserialize this property"); - } - index = ((NinoMemberAttribute)ns[0]).Index; - } - - //record property - dict.Add(index, p); - } - - //add members to model - foreach (var pair in dict) - { - if (pair.Value is FieldInfo fi) - { - model.Members.Add(new NinoMember(fi, fi.FieldType, fi.GetValue)); - } - else if (pair.Value is PropertyInfo pi) - { - model.Members.Add(new NinoMember(pi, pi.PropertyType, pi.GetValue)); - } - } - - //release dict - dict.Clear(); - ObjectPool>.Return(dict); - - if (model.Members.Count == 0) - { - model.Valid = false; - } - - TypeModels[type.GetTypeHashCode()] = model; - } - finally - { - if (lockTaken) _createLock.Exit(false); - } - - return model; - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/Wrappers/Common/NinoWrapperBase.cs b/Nino_Unity/Assets/Nino/Serialization/Wrappers/Common/NinoWrapperBase.cs deleted file mode 100644 index 897f114..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/Wrappers/Common/NinoWrapperBase.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.Runtime.CompilerServices; - -namespace Nino.Serialization -{ - public abstract class NinoWrapperBase : INinoWrapper, INinoWrapper - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public abstract void Serialize(T val, ref Writer writer); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public abstract T Deserialize(Reader reader); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public abstract int GetSize(T val); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Serialize(object val, ref Writer writer) - { - Serialize((T)val, ref writer); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - object INinoWrapper.Deserialize(Reader reader) - { - return Deserialize(reader); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public int GetSize(object val) - { - return GetSize((T)val); - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/Wrappers/Primitives/Basics.cs b/Nino_Unity/Assets/Nino/Serialization/Wrappers/Primitives/Basics.cs deleted file mode 100644 index 66c58ed..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/Wrappers/Primitives/Basics.cs +++ /dev/null @@ -1,395 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Nino.Serialization -{ - internal class BoolWrapper : NinoWrapperBase - { - public override void Serialize(bool val, ref Writer writer) - { - writer.Write(val); - } - - public override bool Deserialize(Reader reader) - { - return reader.ReadBool(); - } - - public override int GetSize(bool val) - { - return 1; - } - } - - internal class BoolArrWrapper : NinoWrapperBase - { - public override void Serialize(bool[] val, ref Writer writer) - { - writer.Write(val.AsSpan()); - } - - public override unsafe bool[] Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - bool[] arr; - if (len == 0) - { - arr = Array.Empty(); - } - else - { - arr = new bool[len]; - fixed (bool* arrPtr = arr) - { - reader.ReadToBuffer((byte*)arrPtr, len); - } - } - - return arr; - } - - public override int GetSize(bool[] val) - { - if (val is null) return 1; - return 1 + 4 + val.Length; - } - } - - internal class BoolListWrapper : NinoWrapperBase> - { - public override void Serialize(List val, ref Writer writer) - { - if (val is null) - { - writer.Write(false); - return; - } - - writer.Write(true); - writer.Write(val.Count); - foreach (var v in val) - { - writer.Write(v); - } - } - - public override List Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - var arr = new List(len); - //read item - int i = 0; - while (i++ < len) - { - arr.Add(reader.ReadBool()); - } - - return arr; - } - - public override int GetSize(List val) - { - if (val is null) return 1; - return 1 + 4 + val.Count; - } - } - - internal class CharWrapper : NinoWrapperBase - { - public override void Serialize(char val, ref Writer writer) - { - writer.Write(val); - } - - public override char Deserialize(Reader reader) - { - return reader.ReadChar(); - } - - public override int GetSize(char val) - { - return 2; - } - } - - internal class CharArrWrapper : NinoWrapperBase - { - public override void Serialize(char[] val, ref Writer writer) - { - writer.Write(val.AsSpan()); - } - - public override unsafe char[] Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - char[] arr; - if (len == 0) - { - arr = Array.Empty(); - } - else - { - arr = new char[len]; - fixed (char* arrPtr = arr) - { - reader.ReadToBuffer((byte*)arrPtr, len * 2); - } - } - - return arr; - } - - public override int GetSize(char[] val) - { - if (val is null) return 1; - return 1 + 4 + val.Length * 2; - } - } - - internal class CharListWrapper : NinoWrapperBase> - { - public override void Serialize(List val, ref Writer writer) - { - if (val is null) - { - writer.Write(false); - return; - } - - writer.Write(true); - writer.Write(val.Count); - foreach (var v in val) - { - writer.Write(v); - } - } - - public override List Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - var arr = new List(len); - //read item - int i = 0; - while (i++ < len) - { - arr.Add(reader.ReadChar()); - } - - return arr; - } - - public override int GetSize(List val) - { - if (val is null) return 1; - return 1 + 4 + val.Count * 2; - } - } - - internal class StringWrapper : NinoWrapperBase - { - public override void Serialize(string val, ref Writer writer) - { - writer.Write(val); - } - - public override string Deserialize(Reader reader) - { - return reader.ReadString(); - } - - public override int GetSize(string val) - { - if (val is null) return 1; - return 1 + 4 + val.Length * 2; - } - } - - internal class StringArrWrapper : NinoWrapperBase - { - public override void Serialize(string[] val, ref Writer writer) - { - if (val is null) - { - writer.Write(false); - return; - } - - writer.Write(true); - writer.Write(val.Length); - foreach (var v in val) - { - writer.Write(v); - } - } - - public override string[] Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - var arr = new string[len]; - int i = 0; - while (i < len) - { - arr[i++] = reader.ReadString(); - } - - return arr; - } - - public override int GetSize(string[] val) - { - if (val is null) return 1; - int size = 1 + 4; - foreach (var v in val) - { - size += 1 + 4 + v.Length * 2; - } - - return size; - } - } - - internal class StringListWrapper : NinoWrapperBase> - { - public override void Serialize(List val, ref Writer writer) - { - if (val is null) - { - writer.Write(false); - return; - } - - writer.Write(true); - writer.Write(val.Count); - foreach (var v in val) - { - writer.Write(v); - } - } - - public override List Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - var arr = new List(len); - //read item - int i = 0; - while (i++ < len) - { - arr.Add(reader.ReadString()); - } - - return arr; - } - - public override int GetSize(List val) - { - if (val is null) return 1; - int size = 1 + 4; - foreach (var v in val) - { - size += 1 + 4 + v.Length * 2; - } - - return size; - } - } - - internal class DateTimeWrapper : NinoWrapperBase - { - public override void Serialize(DateTime val, ref Writer writer) - { - writer.Write(val); - } - - public override DateTime Deserialize(Reader reader) - { - return reader.ReadDateTime(); - } - - public override int GetSize(DateTime val) - { - return 8; - } - } - - internal class DateTimeArrWrapper : NinoWrapperBase - { - public override void Serialize(DateTime[] val, ref Writer writer) - { - writer.Write(val.AsSpan()); - } - - public override unsafe DateTime[] Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - DateTime[] arr; - if (len == 0) - { - arr = Array.Empty(); - } - else - { - arr = new DateTime[len]; - fixed (DateTime* arrPtr = arr) - { - reader.ReadToBuffer((byte*)arrPtr, len * 8); - } - } - - return arr; - } - - public override int GetSize(DateTime[] val) - { - if (val is null) return 1; - return 1 + 4 + val.Length * 8; - } - } - - internal class DateTimeListWrapper : NinoWrapperBase> - { - public override void Serialize(List val, ref Writer writer) - { - if (val is null) - { - writer.Write(false); - return; - } - - writer.Write(true); - writer.Write(val.Count); - foreach (var v in val) - { - writer.Write(v); - } - } - - public override List Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - var arr = new List(len); - int i = 0; - while (i++ < len) - { - arr.Add(reader.ReadDateTime()); - } - - return arr; - } - - public override int GetSize(List val) - { - if (val is null) return 1; - int size = 1 + 4 + val.Count * 8; - - return size; - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/Wrappers/Primitives/Decimals.cs b/Nino_Unity/Assets/Nino/Serialization/Wrappers/Primitives/Decimals.cs deleted file mode 100644 index 6a376bc..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/Wrappers/Primitives/Decimals.cs +++ /dev/null @@ -1,289 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace Nino.Serialization -{ - internal class FloatWrapper : NinoWrapperBase - { - public override void Serialize(float val, ref Writer writer) - { - writer.Write(val); - } - - public override float Deserialize(Reader reader) - { - return reader.ReadSingle(); - } - - public override int GetSize(float val) - { - return 4; - } - } - - internal class FloatArrWrapper : NinoWrapperBase - { - public override void Serialize(float[] val, ref Writer writer) - { - writer.Write(val.AsSpan()); - } - - public override unsafe float[] Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - float[] arr; - if (len == 0) - { - arr = Array.Empty(); - } - else - { - arr = new float[len]; - fixed (float* arrPtr = arr) - { - reader.ReadToBuffer((byte*)arrPtr, len * 4); - } - } - - return arr; - } - - public override int GetSize(float[] val) - { - if (val is null) return 1; - return 1 + 4 + val.Length * 4; - } - } - - internal class FloatListWrapper : NinoWrapperBase> - { - public override void Serialize(List val, ref Writer writer) - { - if (val is null) - { - writer.Write(false); - return; - } - - writer.Write(true); - writer.Write(val.Count); - foreach (var v in val) - { - writer.Write(v); - } - } - - public override List Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - var arr = new List(len); - //read item - for (int i = 0; i < len; i++) - { - arr.Add(reader.ReadSingle()); - } - - return arr; - } - - public override int GetSize(List val) - { - if (val is null) return 1; - int size = 1 + 4 + val.Count * 4; - - return size; - } - } - - internal class DoubleWrapper : NinoWrapperBase - { - public override void Serialize(double val, ref Writer writer) - { - writer.Write(val); - } - - public override double Deserialize(Reader reader) - { - return reader.ReadDouble(); - } - - public override int GetSize(double val) - { - return 8; - } - } - - internal class DoubleArrWrapper : NinoWrapperBase - { - public override void Serialize(double[] val, ref Writer writer) - { - writer.Write(val.AsSpan()); - } - - public override unsafe double[] Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - double[] arr; - if (len == 0) - { - arr = Array.Empty(); - } - else - { - arr = new double[len]; - fixed (double* arrPtr = arr) - { - reader.ReadToBuffer((byte*)arrPtr, len * 8); - } - } - - return arr; - } - - public override int GetSize(double[] val) - { - if (val is null) return 1; - return 1 + 4 + val.Length * 8; - } - } - - internal class DoubleListWrapper : NinoWrapperBase> - { - public override void Serialize(List val, ref Writer writer) - { - if (val is null) - { - writer.Write(false); - return; - } - - writer.Write(true); - writer.Write(val.Count); - foreach (var v in val) - { - writer.Write(v); - } - } - - public override List Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - var arr = new List(len); - //read item - for (int i = 0; i < len; i++) - { - arr.Add(reader.ReadDouble()); - } - - return arr; - } - - public override int GetSize(List val) - { - if (val is null) return 1; - int size = 1 + 4 + val.Count * 8; - - return size; - } - } - - internal class DecimalWrapper : NinoWrapperBase - { - public override void Serialize(decimal val, ref Writer writer) - { - writer.Write(val); - } - - public override decimal Deserialize(Reader reader) - { - return reader.ReadDecimal(); - } - - public override int GetSize(decimal val) - { - return 16; - } - } - - internal class DecimalArrWrapper : NinoWrapperBase - { - public override void Serialize(decimal[] val, ref Writer writer) - { - writer.Write(val.AsSpan()); - } - - public override unsafe decimal[] Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - decimal[] arr; - if (len == 0) - { - arr = Array.Empty(); - } - else - { - arr = new decimal[len]; - fixed (decimal* arrPtr = arr) - { - reader.ReadToBuffer((byte*)arrPtr, len * 16); - } - } - - return arr; - } - - public override int GetSize(decimal[] val) - { - if (val is null) return 1; - return 1 + 4 + val.Length * 16; - } - } - - internal class DecimalListWrapper : NinoWrapperBase> - { - public override void Serialize(List val, ref Writer writer) - { - if (val is null) - { - writer.Write(false); - return; - } - - writer.Write(true); - writer.Write(val.Count); - foreach (var v in val) - { - writer.Write(v); - } - } - - public override List Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - var arr = new List(len); - //read item - for (int i = 0; i < len; i++) - { - arr.Add(reader.ReadDecimal()); - } - - return arr; - } - - public override int GetSize(List val) - { - if (val is null) return 1; - int size = 1 + 4 + val.Count * 16; - - return size; - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/Wrappers/Primitives/Integers.cs b/Nino_Unity/Assets/Nino/Serialization/Wrappers/Primitives/Integers.cs deleted file mode 100644 index be67ac2..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/Wrappers/Primitives/Integers.cs +++ /dev/null @@ -1,707 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Nino.Serialization -{ - internal class ByteWrapper : NinoWrapperBase - { - public override void Serialize(byte val, ref Writer writer) - { - writer.Write(val); - } - - public override byte Deserialize(Reader reader) - { - return reader.ReadByte(); - } - - public override int GetSize(byte val) - { - return 1; - } - } - - internal class ByteArrWrapper : NinoWrapperBase - { - public override void Serialize(byte[] val, ref Writer writer) - { - writer.Write(val.AsSpan()); - } - - public override byte[] Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - return len != 0 ? reader.ReadBytes(len) : Array.Empty(); - } - - public override int GetSize(byte[] val) - { - if (val is null) return 1; - return 1 + 4 + val.Length; - } - } - - internal class ByteListWrapper : NinoWrapperBase> - { - public override void Serialize(List val, ref Writer writer) - { - if (val is null) - { - writer.Write(false); - return; - } - - writer.Write(true); - writer.Write(val.Count); - foreach (var v in val) - { - writer.Write(v); - } - } - - public override List Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - var arr = new List(len); - //read item - int i = 0; - while (i++ < len) - { - arr.Add(reader.ReadByte()); - } - - return arr; - } - - public override int GetSize(List val) - { - if (val is null) return 1; - return 1 + 4 + val.Count; - } - } - - internal class SByteWrapper : NinoWrapperBase - { - public override void Serialize(sbyte val, ref Writer writer) - { - writer.Write(val); - } - - public override sbyte Deserialize(Reader reader) - { - return reader.ReadSByte(); - } - - public override int GetSize(sbyte val) - { - return 1; - } - } - - internal class SByteArrWrapper : NinoWrapperBase - { - public override void Serialize(sbyte[] val, ref Writer writer) - { - writer.Write(val.AsSpan()); - } - - public override unsafe sbyte[] Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - sbyte[] arr; - if (len == 0) - { - arr = Array.Empty(); - } - else - { - arr = new sbyte[len]; - fixed (sbyte* arrPtr = arr) - { - reader.ReadToBuffer((byte*)arrPtr, len); - } - } - - return arr; - } - - public override int GetSize(sbyte[] val) - { - if (val is null) return 1; - return 1 + 4 + val.Length; - } - } - - internal class SByteListWrapper : NinoWrapperBase> - { - public override void Serialize(List val, ref Writer writer) - { - if (val is null) - { - writer.Write(false); - return; - } - - writer.Write(true); - writer.Write(val.Count); - foreach (var v in val) - { - writer.Write(v); - } - } - - public override List Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - var arr = new List(len); - //read item - int i = 0; - while (i++ < len) - { - arr.Add(reader.ReadSByte()); - } - - return arr; - } - - public override int GetSize(List val) - { - if (val is null) return 1; - return 1 + 4 + val.Count; - } - } - - internal class ShortWrapper : NinoWrapperBase - { - public override void Serialize(short val, ref Writer writer) - { - writer.Write(val); - } - - public override short Deserialize(Reader reader) - { - return reader.ReadInt16(); - } - - public override int GetSize(short val) - { - return 2; - } - } - - internal class ShortArrWrapper : NinoWrapperBase - { - public override void Serialize(short[] val, ref Writer writer) - { - writer.Write(val.AsSpan()); - } - - public override unsafe short[] Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - short[] arr; - if (len == 0) - { - arr = Array.Empty(); - } - else - { - arr = new short[len]; - fixed (short* arrPtr = arr) - { - reader.ReadToBuffer((byte*)arrPtr, len * 2); - } - } - - return arr; - } - - public override int GetSize(short[] val) - { - if (val is null) return 1; - return 1 + 4 + val.Length * 2; - } - } - - internal class ShortListWrapper : NinoWrapperBase> - { - public override void Serialize(List val, ref Writer writer) - { - if (val is null) - { - writer.Write(false); - return; - } - - writer.Write(true); - writer.Write(val.Count); - foreach (var v in val) - { - writer.Write(v); - } - } - - public override List Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - var arr = new List(len); - //read item - int i = 0; - while (i++ < len) - { - arr.Add(reader.ReadInt16()); - } - - return arr; - } - - public override int GetSize(List val) - { - if (val is null) return 1; - return 1 + 4 + val.Count * 2; - } - } - - internal class UShortWrapper : NinoWrapperBase - { - public override void Serialize(ushort val, ref Writer writer) - { - writer.Write(val); - } - - public override ushort Deserialize(Reader reader) - { - return reader.ReadUInt16(); - } - - public override int GetSize(ushort val) - { - return 2; - } - } - - internal class UShortArrWrapper : NinoWrapperBase - { - public override void Serialize(ushort[] val, ref Writer writer) - { - writer.Write(val.AsSpan()); - } - - public override unsafe ushort[] Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - ushort[] arr; - if (len == 0) - { - arr = Array.Empty(); - } - else - { - arr = new ushort[len]; - fixed (ushort* arrPtr = arr) - { - reader.ReadToBuffer((byte*)arrPtr, len * 2); - } - } - - return arr; - } - - public override int GetSize(ushort[] val) - { - if (val is null) return 1; - return 1 + 4 + val.Length * 2; - } - } - - internal class UShortListWrapper : NinoWrapperBase> - { - public override void Serialize(List val, ref Writer writer) - { - if (val is null) - { - writer.Write(false); - return; - } - - writer.Write(true); - writer.Write(val.Count); - foreach (var v in val) - { - writer.Write(v); - } - } - - public override List Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - var arr = new List(len); - //read item - int i = 0; - while (i++ < len) - { - arr.Add(reader.ReadUInt16()); - } - - return arr; - } - - public override int GetSize(List val) - { - if (val is null) return 1; - return 1 + 4 + val.Count * 2; - } - } - - internal class IntWrapper : NinoWrapperBase - { - public override void Serialize(int val, ref Writer writer) - { - writer.Write(val); - } - - public override int Deserialize(Reader reader) - { - return reader.ReadInt32(); - } - - public override int GetSize(int val) - { - return 4; - } - } - - internal class IntArrWrapper : NinoWrapperBase - { - public override void Serialize(int[] val, ref Writer writer) - { - writer.Write(val.AsSpan()); - } - - public override unsafe int[] Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - var arr = new int[len]; - //read item - fixed (int* arrPtr = arr) - { - reader.ReadToBuffer((byte*)arrPtr, len * 4); - } - - return arr; - } - - public override int GetSize(int[] val) - { - if (val is null) return 1; - return 1 + 4 + val.Length * 4; - } - } - - internal class IntListWrapper : NinoWrapperBase> - { - public override void Serialize(List val, ref Writer writer) - { - if (val is null) - { - writer.Write(false); - return; - } - - writer.Write(true); - writer.Write(val.Count); - foreach (var v in val) - { - writer.Write(v); - } - } - - public override List Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - var arr = new List(len); - //read item - int i = 0; - while (i++ < len) - { - arr.Add(reader.ReadInt32()); - } - - return arr; - } - - public override int GetSize(List val) - { - if (val is null) return 1; - return 1 + 4 + val.Count * 4; - } - } - - internal class UIntWrapper : NinoWrapperBase - { - public override void Serialize(uint val, ref Writer writer) - { - writer.Write(val); - } - - public override uint Deserialize(Reader reader) - { - return reader.ReadUInt32(); - } - - public override int GetSize(uint val) - { - return 4; - } - } - - internal class UIntArrWrapper : NinoWrapperBase - { - public override void Serialize(uint[] val, ref Writer writer) - { - writer.Write(val.AsSpan()); - } - - public override unsafe uint[] Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - var arr = new uint[len]; - //read item - fixed (uint* arrPtr = arr) - { - reader.ReadToBuffer((byte*)arrPtr, len * 4); - } - - return arr; - } - - public override int GetSize(uint[] val) - { - if (val is null) return 1; - return 1 + 4 + val.Length * 4; - } - } - - internal class UIntListWrapper : NinoWrapperBase> - { - public override void Serialize(List val, ref Writer writer) - { - if (val is null) - { - writer.Write(false); - return; - } - - writer.Write(true); - writer.Write(val.Count); - foreach (var v in val) - { - writer.Write(v); - } - } - - public override List Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - var arr = new List(len); - //read item - int i = 0; - while (i++ < len) - { - arr.Add(reader.ReadUInt32()); - } - - return arr; - } - - public override int GetSize(List val) - { - if (val is null) return 1; - return 1 + 4 + val.Count * 4; - } - } - - internal class LongWrapper : NinoWrapperBase - { - public override void Serialize(long val, ref Writer writer) - { - writer.Write(val); - } - - public override long Deserialize(Reader reader) - { - return reader.ReadInt64(); - } - - public override int GetSize(long val) - { - return 8; - } - } - - internal class LongArrWrapper : NinoWrapperBase - { - public override void Serialize(long[] val, ref Writer writer) - { - writer.Write(val.AsSpan()); - } - - public override unsafe long[] Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - var arr = new long[len]; - //read item - fixed (long* arrPtr = arr) - { - reader.ReadToBuffer((byte*)arrPtr, len * 8); - } - - return arr; - } - - public override int GetSize(long[] val) - { - if (val is null) return 1; - return 1 + 4 + val.Length * 8; - } - } - - internal class LongListWrapper : NinoWrapperBase> - { - public override void Serialize(List val, ref Writer writer) - { - if (val is null) - { - writer.Write(false); - return; - } - - writer.Write(true); - writer.Write(val.Count); - foreach (var v in val) - { - writer.Write(v); - } - } - - public override List Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - var arr = new List(len); - //read item - int i = 0; - while (i++ < len) - { - arr.Add(reader.ReadInt64()); - } - - return arr; - } - - public override int GetSize(List val) - { - if (val is null) return 1; - return 1 + 4 + val.Count * 8; - } - } - - internal class ULongWrapper : NinoWrapperBase - { - public override void Serialize(ulong val, ref Writer writer) - { - writer.Write(val); - } - - public override ulong Deserialize(Reader reader) - { - return reader.ReadUInt64(); - } - - public override int GetSize(ulong val) - { - return 8; - } - } - - internal class ULongArrWrapper : NinoWrapperBase - { - public override void Serialize(ulong[] val, ref Writer writer) - { - writer.Write(val.AsSpan()); - } - - public override unsafe ulong[] Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - var arr = new ulong[len]; - //read item - fixed (ulong* arrPtr = arr) - { - reader.ReadToBuffer((byte*)arrPtr, len * 8); - } - - return arr; - } - - public override int GetSize(ulong[] val) - { - if (val is null) return 1; - return 1 + 4 + val.Length * 8; - } - } - - internal class ULongListWrapper : NinoWrapperBase> - { - public override void Serialize(List val, ref Writer writer) - { - if (val is null) - { - writer.Write(false); - return; - } - - writer.Write(true); - writer.Write(val.Count); - foreach (var v in val) - { - writer.Write(v); - } - } - - public override List Deserialize(Reader reader) - { - if (!reader.ReadBool()) return null; - int len = reader.ReadLength(); - var arr = new List(len); - //read item - int i = 0; - while (i++ < len) - { - arr.Add(reader.ReadUInt64()); - } - - return arr; - } - - public override int GetSize(List val) - { - if (val is null) return 1; - return 1 + 4 + val.Count * 8; - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/Wrappers/WrapperManifest.cs b/Nino_Unity/Assets/Nino/Serialization/Wrappers/WrapperManifest.cs deleted file mode 100644 index 20003a2..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/Wrappers/WrapperManifest.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System; -using Nino.Shared.Util; -using System.Collections.Generic; - -namespace Nino.Serialization -{ - public static class WrapperManifest - { - private static readonly Dictionary Wrappers = new Dictionary(300) - { - { typeof(byte).GetTypeHashCode(), new ByteWrapper() }, - { typeof(byte[]).GetTypeHashCode(), new ByteArrWrapper() }, - { typeof(List).GetTypeHashCode(), new ByteListWrapper() }, - { typeof(sbyte).GetTypeHashCode(), new SByteWrapper() }, - { typeof(sbyte[]).GetTypeHashCode(), new SByteArrWrapper() }, - { typeof(List).GetTypeHashCode(), new SByteListWrapper() }, - { typeof(short).GetTypeHashCode(), new ShortWrapper() }, - { typeof(short[]).GetTypeHashCode(), new ShortArrWrapper() }, - { typeof(List).GetTypeHashCode(), new ShortListWrapper() }, - { typeof(ushort).GetTypeHashCode(), new UShortWrapper() }, - { typeof(ushort[]).GetTypeHashCode(), new UShortArrWrapper() }, - { typeof(List).GetTypeHashCode(), new UShortListWrapper() }, - { typeof(int).GetTypeHashCode(), new IntWrapper() }, - { typeof(int[]).GetTypeHashCode(), new IntArrWrapper() }, - { typeof(List).GetTypeHashCode(), new IntListWrapper() }, - { typeof(uint).GetTypeHashCode(), new UIntWrapper() }, - { typeof(uint[]).GetTypeHashCode(), new UIntArrWrapper() }, - { typeof(List).GetTypeHashCode(), new UIntListWrapper() }, - { typeof(long).GetTypeHashCode(), new LongWrapper() }, - { typeof(long[]).GetTypeHashCode(), new LongArrWrapper() }, - { typeof(List).GetTypeHashCode(), new LongListWrapper() }, - { typeof(ulong).GetTypeHashCode(), new ULongWrapper() }, - { typeof(ulong[]).GetTypeHashCode(), new ULongArrWrapper() }, - { typeof(List).GetTypeHashCode(), new ULongListWrapper() }, - { typeof(float).GetTypeHashCode(), new FloatWrapper() }, - { typeof(float[]).GetTypeHashCode(), new FloatArrWrapper() }, - { typeof(List).GetTypeHashCode(), new FloatListWrapper() }, - { typeof(double).GetTypeHashCode(), new DoubleWrapper() }, - { typeof(double[]).GetTypeHashCode(), new DoubleArrWrapper() }, - { typeof(List).GetTypeHashCode(), new DoubleListWrapper() }, - { typeof(decimal).GetTypeHashCode(), new DecimalWrapper() }, - { typeof(decimal[]).GetTypeHashCode(), new DecimalArrWrapper() }, - { typeof(List).GetTypeHashCode(), new DecimalListWrapper() }, - { typeof(string).GetTypeHashCode(), new StringWrapper() }, - { typeof(string[]).GetTypeHashCode(), new StringArrWrapper() }, - { typeof(List).GetTypeHashCode(), new StringListWrapper() }, - { typeof(char).GetTypeHashCode(), new CharWrapper() }, - { typeof(char[]).GetTypeHashCode(), new CharArrWrapper() }, - { typeof(List).GetTypeHashCode(), new CharListWrapper() }, - { typeof(bool).GetTypeHashCode(), new BoolWrapper() }, - { typeof(bool[]).GetTypeHashCode(), new BoolArrWrapper() }, - { typeof(List).GetTypeHashCode(), new BoolListWrapper() }, - { typeof(DateTime).GetTypeHashCode(), new DateTimeWrapper() }, - { typeof(DateTime[]).GetTypeHashCode(), new DateTimeArrWrapper() }, - { typeof(List).GetTypeHashCode(), new DateTimeListWrapper() }, - }; - - public static bool TryGetWrapper(Type type, out INinoWrapper wrapper) - { - return Wrappers.TryGetValue(type.GetTypeHashCode(), out wrapper); - } - - public static void AddWrapper(Type type, INinoWrapper wrapper) - { - Wrappers[type.GetTypeHashCode()] = wrapper; - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/Writer.Generic.cs b/Nino_Unity/Assets/Nino/Serialization/Writer.Generic.cs deleted file mode 100644 index 5adbdcd..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/Writer.Generic.cs +++ /dev/null @@ -1,537 +0,0 @@ -using System; -using System.IO; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; -using Nino.Shared.Mgr; - -namespace Nino.Serialization -{ - public ref partial struct Writer - { - /// - /// Write primitive values, DO NOT USE THIS FOR CUSTOM IMPORTER - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void WriteCommonVal(T val) => Position = Serializer.Serialize(typeof(T), val, null, buffer, Position); - - /// - /// Write primitive values, DO NOT USE THIS FOR CUSTOM IMPORTER - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void WriteCommonVal(Type type, T val) => - Position = Serializer.Serialize(type, val, null, buffer, Position); - - /// - /// Write unmanaged type - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal void WriteAsUnmanaged(ref T val, int len) - { - Unsafe.WriteUnaligned(ref buffer[Position], val); - Position += len; - } - - /// - /// Write unmanaged type - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(ref T val, int len) where T : unmanaged - { - Unsafe.WriteUnaligned(ref buffer[Position], val); - Position += len; - } - - /// - /// Write unmanaged type - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(ref T1 val1, int len1, ref T2 val2, int len2) - where T1 : unmanaged where T2 : unmanaged - { - Unsafe.WriteUnaligned(ref buffer[Position], val1); - Position += len1; - Unsafe.WriteUnaligned(ref buffer[Position], val2); - Position += len2; - } - - /// - /// Write unmanaged type - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(ref T1 val1, int len1, ref T2 val2, int len2, ref T3 val3, int len3) - where T1 : unmanaged where T2 : unmanaged where T3 : unmanaged - { - Unsafe.WriteUnaligned(ref buffer[Position], val1); - Position += len1; - Unsafe.WriteUnaligned(ref buffer[Position], val2); - Position += len2; - Unsafe.WriteUnaligned(ref buffer[Position], val3); - Position += len3; - } - - /// - /// Write unmanaged type - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(ref T1 val1, int len1, ref T2 val2, int len2, ref T3 val3, int len3, - ref T4 val4, int len4) where T1 : unmanaged where T2 : unmanaged where T3 : unmanaged where T4 : unmanaged - { - Unsafe.WriteUnaligned(ref buffer[Position], val1); - Position += len1; - Unsafe.WriteUnaligned(ref buffer[Position], val2); - Position += len2; - Unsafe.WriteUnaligned(ref buffer[Position], val3); - Position += len3; - Unsafe.WriteUnaligned(ref buffer[Position], val4); - Position += len4; - } - - /// - /// Write unmanaged type - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(ref T1 val1, int len1, ref T2 val2, int len2, ref T3 val3, int len3, - ref T4 val4, int len4, ref T5 val5, int len5) where T1 : unmanaged - where T2 : unmanaged - where T3 : unmanaged - where T4 : unmanaged - where T5 : unmanaged - { - Unsafe.WriteUnaligned(ref buffer[Position], val1); - Position += len1; - Unsafe.WriteUnaligned(ref buffer[Position], val2); - Position += len2; - Unsafe.WriteUnaligned(ref buffer[Position], val3); - Position += len3; - Unsafe.WriteUnaligned(ref buffer[Position], val4); - Position += len4; - Unsafe.WriteUnaligned(ref buffer[Position], val5); - Position += len5; - } - - /// - /// Write unmanaged type - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(ref T1 val1, int len1, ref T2 val2, int len2, ref T3 val3, int len3, - ref T4 val4, int len4, ref T5 val5, int len5, ref T6 val6, int len6) where T1 : unmanaged - where T2 : unmanaged - where T3 : unmanaged - where T4 : unmanaged - where T5 : unmanaged - where T6 : unmanaged - { - Unsafe.WriteUnaligned(ref buffer[Position], val1); - Position += len1; - Unsafe.WriteUnaligned(ref buffer[Position], val2); - Position += len2; - Unsafe.WriteUnaligned(ref buffer[Position], val3); - Position += len3; - Unsafe.WriteUnaligned(ref buffer[Position], val4); - Position += len4; - Unsafe.WriteUnaligned(ref buffer[Position], val5); - Position += len5; - Unsafe.WriteUnaligned(ref buffer[Position], val6); - Position += len6; - } - - /// - /// Write unmanaged type - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(ref T1 val1, int len1, ref T2 val2, int len2, ref T3 val3, - int len3, ref T4 val4, int len4, ref T5 val5, int len5, ref T6 val6, int len6, ref T7 val7, int len7) - where T1 : unmanaged - where T2 : unmanaged - where T3 : unmanaged - where T4 : unmanaged - where T5 : unmanaged - where T6 : unmanaged - where T7 : unmanaged - { - Unsafe.WriteUnaligned(ref buffer[Position], val1); - Position += len1; - Unsafe.WriteUnaligned(ref buffer[Position], val2); - Position += len2; - Unsafe.WriteUnaligned(ref buffer[Position], val3); - Position += len3; - Unsafe.WriteUnaligned(ref buffer[Position], val4); - Position += len4; - Unsafe.WriteUnaligned(ref buffer[Position], val5); - Position += len5; - Unsafe.WriteUnaligned(ref buffer[Position], val6); - Position += len6; - Unsafe.WriteUnaligned(ref buffer[Position], val7); - Position += len7; - } - - /// - /// Write unmanaged type - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(ref T1 val1, int len1, ref T2 val2, int len2, ref T3 val3, - int len3, ref T4 val4, int len4, ref T5 val5, int len5, ref T6 val6, int len6, ref T7 val7, int len7, - ref T8 val8, int len8) where T1 : unmanaged - where T2 : unmanaged - where T3 : unmanaged - where T4 : unmanaged - where T5 : unmanaged - where T6 : unmanaged - where T7 : unmanaged - where T8 : unmanaged - { - Unsafe.WriteUnaligned(ref buffer[Position], val1); - Position += len1; - Unsafe.WriteUnaligned(ref buffer[Position], val2); - Position += len2; - Unsafe.WriteUnaligned(ref buffer[Position], val3); - Position += len3; - Unsafe.WriteUnaligned(ref buffer[Position], val4); - Position += len4; - Unsafe.WriteUnaligned(ref buffer[Position], val5); - Position += len5; - Unsafe.WriteUnaligned(ref buffer[Position], val6); - Position += len6; - Unsafe.WriteUnaligned(ref buffer[Position], val7); - Position += len7; - Unsafe.WriteUnaligned(ref buffer[Position], val8); - Position += len8; - } - - /// - /// Write byte[] - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe void Write(Span data) where T : unmanaged - { - if (data == null) - { - Write(false); - return; - } - - Write(true); - var len = data.Length; - Write(len); - len *= sizeof(T); - MemoryMarshal.AsBytes(data).CopyTo(buffer.Slice(Position, len)); - Position += len; - } - - /// - /// write enum - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void WriteEnum(T val) - { - //boxed - if (typeof(T) == ConstMgr.ObjectType) - { - WriteEnum((object)val); - return; - } - - ref byte p = ref MemoryMarshal.GetReference(buffer); - switch (TypeModel.GetTypeCode(typeof(T))) - { - case TypeCode.Byte: - case TypeCode.SByte: - case TypeCode.Int16: - case TypeCode.UInt16: - case TypeCode.Int32: - case TypeCode.UInt32: - byte len = (byte)Unsafe.SizeOf(); - Unsafe.WriteUnaligned(ref Unsafe.Add(ref p, Position), val); - Position += len; - return; - case TypeCode.Int64: - case TypeCode.UInt64: - Unsafe.WriteUnaligned(ref Unsafe.Add(ref p, Position), val); - Position += 8; - return; - } - } - - /// - /// write enum - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe void WriteEnum(object val) - { - var type = val.GetType(); - ref byte p = ref MemoryMarshal.GetReference(buffer); - switch (TypeModel.GetTypeCode(type)) - { - case TypeCode.Byte: - buffer[Position++] = Unsafe.Unbox(val); - return; - case TypeCode.SByte: - buffer[Position++] = *(byte*)Unsafe.Unbox(val); - return; - case TypeCode.Int16: - Unsafe.WriteUnaligned(ref Unsafe.Add(ref p, Position), Unsafe.Unbox(val)); - Position += 2; - return; - case TypeCode.UInt16: - Unsafe.WriteUnaligned(ref Unsafe.Add(ref p, Position), Unsafe.Unbox(val)); - Position += 2; - return; - case TypeCode.Int32: - Unsafe.WriteUnaligned(ref Unsafe.Add(ref p, Position), Unsafe.Unbox(val)); - Position += 4; - return; - case TypeCode.UInt32: - Unsafe.WriteUnaligned(ref Unsafe.Add(ref p, Position), Unsafe.Unbox(val)); - Position += 4; - return; - case TypeCode.Int64: - Unsafe.WriteUnaligned(ref Unsafe.Add(ref p, Position), Unsafe.Unbox(val)); - Position += 8; - return; - case TypeCode.UInt64: - Unsafe.WriteUnaligned(ref Unsafe.Add(ref p, Position), Unsafe.Unbox(val)); - Position += 8; - return; - } - } - - /// - /// Write array - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(T[] arr) - { - //null - if (arr == null) - { - Write(false); - return; - } - - Write(true); - //write len - int len = arr.Length; - - //empty - if (len == 0) - { - //write len - Write(0); - return; - } - - Write(len); - //write item - int i = 0; - while (i < len) - { - var obj = arr[i++]; - var eType = obj.GetType(); - WriteCommonVal(eType, obj); - } - } - - /// - /// Write nullable - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(T? val) where T : struct - { - //null - if (val == null) - { - Write(false); - return; - } - - Write(true); - WriteCommonVal(val.Value); - } - - /// - /// Write List - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(List lst) - { - //null - if (lst == null) - { - Write(false); - return; - } - - Write(true); - int len = lst.Count; - //write len - Write(lst.Count); - //empty - if (len == 0) - { - return; - } - - //write item - foreach (var c in lst) - { - WriteCommonVal(c); - } - } - - /// - /// Write List - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(HashSet lst) - { - //null - if (lst == null) - { - Write(false); - return; - } - - Write(true); - int len = lst.Count; - //write len - Write(len); - //empty - if (len == 0) - { - //write len - return; - } - - //write item - foreach (var c in lst) - { - WriteCommonVal(c); - } - } - - /// - /// Write List - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(Queue lst) - { - //null - if (lst == null) - { - Write(false); - return; - } - - Write(true); - int len = lst.Count; - //write len - Write(len); - //empty - if (len == 0) - { - //write len - return; - } - - //write item - foreach (var c in lst) - { - WriteCommonVal(c); - } - } - - /// - /// Write List - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(Stack lst) - { - //null - if (lst == null) - { - Write(false); - return; - } - - Write(true); - int len = lst.Count; - //write len - Write(len); - //empty - if (len == 0) - { - //write len - return; - } - - //write item - foreach (var c in lst) - { - WriteCommonVal(c); - } - } - - /// - /// Write dictionary - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(Dictionary dictionary) - { - //null - if (dictionary == null) - { - Write(false); - return; - } - - Write(true); - int len = dictionary.Count; - //write len - Write(len); - //empty - if (len == 0) - { - //write len - return; - } - - //record keys - var keys = dictionary.Keys; - //write items - foreach (var c in keys) - { - //write key - WriteCommonVal(c); - //write val - var val = dictionary[c]; - WriteCommonVal(val); - } - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Serialization/Writer.cs b/Nino_Unity/Assets/Nino/Serialization/Writer.cs deleted file mode 100644 index 3325915..0000000 --- a/Nino_Unity/Assets/Nino/Serialization/Writer.cs +++ /dev/null @@ -1,338 +0,0 @@ -using System; -using System.IO; -using Nino.Shared.Mgr; -using System.Collections; -using System.Runtime.CompilerServices; - -namespace Nino.Serialization -{ - /// - /// A writer that writes serialization Data - /// - public ref partial struct Writer - { - /// - /// Buffer that stores data - /// - private Span buffer; - - /// - /// Position of the current buffer - /// - public int Position; - - /// - /// Create a nino writer - /// - /// - /// - public Writer(Span buffer, int position) - { - this.buffer = buffer; - Position = position; - } - - /// - /// Write primitive values, DO NOT USE THIS FOR CUSTOM IMPORTER - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void WriteCommonVal(Type type, object val) => - Position = Serializer.Serialize(type, val, null, buffer, Position); - - /// - /// Write byte[] - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal unsafe void Write(byte* data, ref int len) - { - if (len <= 8) - { - while (len-- > 0) - { - buffer[Position++] = *data++; - } - - return; - } - - Unsafe.CopyBlockUnaligned(ref buffer[Position], ref *data, (uint)len); - Position += len; - } - - /// - /// Write a double - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(double value) - { - Write(ref value, ConstMgr.SizeOfULong); - } - - /// - /// Write a float - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(float value) - { - Write(ref value, ConstMgr.SizeOfUInt); - } - - /// - /// Write a DateTime - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(DateTime value) - { - Write(ref value, ConstMgr.SizeOfLong); - } - - /// - /// Write decimal - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(decimal d) - { - Write(ref d, ConstMgr.SizeOfDecimal); - } - - /// - /// Writes a boolean to this stream. A single byte is written to the stream - /// with the value 0 representing false or the value 1 representing true. - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(bool value) - { - Unsafe.WriteUnaligned(ref buffer[Position++], value); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(char value) - { - Write(ref value, ConstMgr.SizeOfUShort); - } - - /// - /// Write string - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe void Write(string val) - { - if (val is null) - { - Write(false); - return; - } - - Write(true); - - if (val == string.Empty) - { - Write(0); - return; - } - - var strSpan = val.AsSpan(); // 2*len, utf16 str - int len = strSpan.Length * ConstMgr.SizeOfUShort; - fixed (char* first = &strSpan.GetPinnableReference()) - { - Write(len); - Write((byte*)first, ref len); - } - } - - #region write whole num - - /// - /// Write byte val to binary writer - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(byte num) - { - buffer[Position++] = num; - } - - /// - /// Write byte val to binary writer - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(sbyte num) - { - Unsafe.WriteUnaligned(ref buffer[Position++], num); - } - - /// - /// Write int val to binary writer - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(int num) - { - Write(ref num, ConstMgr.SizeOfInt); - } - - /// - /// Write uint val to binary writer - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(uint num) - { - Write(ref num, ConstMgr.SizeOfUInt); - } - - /// - /// Write short val to binary writer - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(short num) - { - Write(ref num, ConstMgr.SizeOfShort); - } - - /// - /// Write ushort val to binary writer - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(ushort num) - { - Write(ref num, ConstMgr.SizeOfUShort); - } - - /// - /// Write long val to binary writer - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(long num) - { - Write(ref num, ConstMgr.SizeOfLong); - } - - /// - /// Write ulong val to binary writer - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(ulong num) - { - Write(ref num, ConstMgr.SizeOfULong); - } - - #endregion - - /// - /// Write array - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(Array arr) - { - //null - if (arr == null) - { - Write(false); - return; - } - - Write(true); - //write len - int len = arr.Length; - //empty - Write(len); - //write item - int i = 0; - while (i < len) - { - var obj = arr.GetValue(i++); - var eType = obj.GetType(); - WriteCommonVal(eType, obj); - } - } - - /// - /// Write list - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(IList arr) - { - //null - if (arr == null) - { - Write(false); - return; - } - - Write(true); - var len = arr.Count; - //write len - Write(len); - //empty - if (len == 0) - { - return; - } - - //write item - foreach (var c in arr) - { - var eType = c.GetType(); - WriteCommonVal(eType, c); - } - } - - /// - /// Write dictionary - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(IDictionary dictionary) - { - //null - if (dictionary == null) - { - Write(false); - return; - } - - Write(true); - //write len - int len = dictionary.Count; - Write(len); - //empty - if (dictionary.Count == 0) - { - return; - } - - //record keys - var keys = dictionary.Keys; - //write items - foreach (var c in keys) - { - //write key - var eType = c.GetType(); - WriteCommonVal(eType, c); - //write val - var val = dictionary[c]; - eType = val.GetType(); - WriteCommonVal(eType, val); - } - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Shared/Attributes/MonoPInvokeCallbackAttribute.cs b/Nino_Unity/Assets/Nino/Shared/Attributes/MonoPInvokeCallbackAttribute.cs deleted file mode 100644 index 7a8ea37..0000000 --- a/Nino_Unity/Assets/Nino/Shared/Attributes/MonoPInvokeCallbackAttribute.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; - -namespace Nino.Shared.IO -{ - public class MonoPInvokeCallbackAttribute : Attribute - { - public MonoPInvokeCallbackAttribute() - { - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Shared/Collections/FunctorComparer.cs b/Nino_Unity/Assets/Nino/Shared/Collections/FunctorComparer.cs deleted file mode 100644 index d7155aa..0000000 --- a/Nino_Unity/Assets/Nino/Shared/Collections/FunctorComparer.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Nino.Shared -{ - internal sealed class FunctorComparer : IComparer { - Comparison comparison; - - public FunctorComparer(Comparison comparison) { - this.comparison = comparison; - } - - public int Compare(T x, T y) { - return comparison(x, y); - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Shared/Collections/UncheckedList.cs b/Nino_Unity/Assets/Nino/Shared/Collections/UncheckedList.cs deleted file mode 100644 index 170974e..0000000 --- a/Nino_Unity/Assets/Nino/Shared/Collections/UncheckedList.cs +++ /dev/null @@ -1,978 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; - -// ReSharper disable CognitiveComplexity -namespace Nino.Shared -{ - [Serializable] - public class UncheckedList : IList, System.Collections.IList, IReadOnlyList - { - private const int DefaultCapacity = 4; - /// - /// here we made it public for faster access than indexer, but we dont recommend modify this - /// direct calling is way faster in debug mode, when in release mode, calling indexer has same performance as direct call - /// https://stackoverflow.com/questions/17105773/poor-c-sharp-optimizer-performance - /// - internal T[] items; - private int size; - private int version; - [NonSerialized] private Object syncRoot; - - static readonly T[] - EmptyArray = - Array.Empty(); // Constructs a UncheckedList. The UncheckedList is initially empty and has a capacity - - // of zero. Upon adding the first element to the UncheckedList the capacity is - // increased to 16, and then increased in multiples of two as required. - public UncheckedList() - { - items = EmptyArray; - } // Constructs a UncheckedList with a given initial capacity. The UncheckedList is - - // initially empty, but will have room for the given number of elements - // before any reallocations are required. - // - public UncheckedList(int capacity) - { - if (capacity == 0) - items = EmptyArray; - else - items = new T[capacity]; - } // Constructs a UncheckedList, copying the contents of the given collection. The - - // size and capacity of the new UncheckedList will both be equal to the size of the - // given collection. - // - public UncheckedList(IEnumerable collection) - { - ICollection c = collection as ICollection; - if (c != null) - { - int count = c.Count; - if (count == 0) - { - items = EmptyArray; - } - else - { - items = new T[count]; - c.CopyTo(items, 0); - size = count; - } - } - else - { - size = 0; - items = EmptyArray; - // This enumerable could be empty. Let Add allocate a new array, if needed. - // Note it will also go to _defaultCapacity first, not 1, then 2, etc. using (IEnumerator en = collection.GetEnumerator()) - using (IEnumerator en = collection.GetEnumerator()) - { - while (en.MoveNext()) - { - Add(en.Current); - } - } - } - } // Gets and sets the capacity of this UncheckedList. The capacity is the size of - - // the internal array used to hold items. When set, the internal - // array of the UncheckedList is reallocated to the given capacity. - // - public int Capacity - { - get => items.Length; - set - { - if (value != items.Length) - { - if (value > 0) - { - T[] newItems = new T[value]; - if (size > 0) - { - Array.Copy(items, 0, newItems, 0, size); - } - - items = newItems; - } - else - { - items = EmptyArray; - } - } - } - } // Read-only property describing how many elements are in the UncheckedList. - - public int Count => size; - - bool System.Collections.IList.IsFixedSize => false; - - // Is this UncheckedList read-only? - bool ICollection.IsReadOnly => false; - - bool System.Collections.IList.IsReadOnly => false; // Is this UncheckedList synchronized (thread-safe)? - - bool System.Collections.ICollection.IsSynchronized => false; // Synchronization root for this object. - - Object System.Collections.ICollection.SyncRoot - { - get - { - if (syncRoot == null) - { - System.Threading.Interlocked.CompareExchange(ref syncRoot, new Object(), null); - } - - return syncRoot; - } - } // Sets or Gets the element at the given index. - - // - public T this[int index] - { - get => items[index]; - set - { - items[index] = value; - version++; - } - } - - private static bool IsCompatibleObject(object value) - { - // Non-null values are fine. Only accept nulls if T is a class or Nullable. - // Note that default(T) is not equal to null for value types except when T is Nullable. - return ((value is T) || (value == null && default(T) == null)); - } - - Object System.Collections.IList.this[int index] - { - get => this[index]; - set => this[index] = (T)value; - } // Adds the given object to the end of this UncheckedList. The size of the UncheckedList is - - // increased by one. If required, the capacity of the UncheckedList is doubled - // before adding the new element. - // - public void Add(T item) - { - if (size == items.Length) EnsureCapacity(size + 1); - items[size++] = item; - version++; - } - - int System.Collections.IList.Add(Object item) - { - Add((T)item); - return Count - 1; - } - - // Adds the elements of the given collection to the end of this UncheckedList. If - // required, the capacity of the UncheckedList is increased to twice the previous - // capacity or the new size, whichever is larger. - // - public void AddRange(IEnumerable collection) - { - InsertRange(size, collection); - } - - public ReadOnlyCollection AsReadOnly() - { - return new ReadOnlyCollection(this); - } // Searches a section of the UncheckedList for a given element using a binary search - - // algorithm. Elements of the UncheckedList are compared to the search value using - // the given IComparer interface. If comparer is null, elements of - // the UncheckedList are compared to the search value using the IComparable - // interface, which in that case must be implemented by all elements of the - // UncheckedList and the given search value. This method assumes that the given - // section of the UncheckedList is already sorted; if this is not the case, the - // result will be incorrect. - // - // The method returns the index of the given value in the UncheckedList. If the - // UncheckedList does not contain the given value, the method returns a negative - // integer. The bitwise complement operator (~) can be applied to a - // negative result to produce the index of the first element (if any) that - // is larger than the given search value. This is also the index at which - // the search value should be inserted into the UncheckedList in order for the UncheckedList - // to remain sorted. - // - // The method uses the Array.BinarySearch method to perform the - // search. - // - public int BinarySearch(int index, int count, T item, IComparer comparer) - { - return Array.BinarySearch(items, index, count, item, comparer); - } - - public int BinarySearch(T item) - { - return BinarySearch(0, Count, item, null); - } - - public int BinarySearch(T item, IComparer comparer) - { - return BinarySearch(0, Count, item, comparer); - } - - // Clears the contents of UncheckedList. - public void Clear() - { - if (size > 0) - { - Array.Clear(items, 0, - size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. - size = 0; - } - - version++; - } // Contains returns true if the specified element is in the UncheckedList. - - // It does a linear, O(n) search. Equality is determined by calling - // item.Equals(). - // - public bool Contains(T item) - { - if (item == null) - { - for (int i = 0; i < size; i++) - if (items[i] == null) - return true; - return false; - } - else - { - EqualityComparer c = EqualityComparer.Default; - for (int i = 0; i < size; i++) - { - if (c.Equals(items[i], item)) return true; - } - - return false; - } - } - - bool System.Collections.IList.Contains(Object item) - { - if (IsCompatibleObject(item)) - { - return Contains((T)item); - } - - return false; - } - - public UncheckedList ConvertAll(Converter converter) - { - UncheckedList uncheckedList = new UncheckedList(size); - for (int i = 0; i < size; i++) - { - uncheckedList.items[i] = converter(items[i]); - } - - uncheckedList.size = size; - return uncheckedList; - } // Copies this UncheckedList into array, which must be of a - - // compatible array type. - // - // Copies this UncheckedList into array, which must be of a - - // compatible array type. - // - void System.Collections.ICollection.CopyTo(Array array, int arrayIndex) - { - // Array.Copy will check for NULL. - Array.Copy(items, 0, array, arrayIndex, size); - } // Copies a section of this UncheckedList to the given array at the given index. - - // - // The method uses the Array.Copy method to copy the elements. - // - public void CopyTo(int index, T[] array, int arrayIndex, int count) - { - // Delegate rest of error checking to Array.Copy. - Array.Copy(items, index, array, arrayIndex, count); - } - - public void CopyTo(T[] array, int arrayIndex = 0) - { - // Delegate rest of error checking to Array.Copy. - Array.Copy(items, 0, array, arrayIndex, size); - } // Ensures that the capacity of this UncheckedList is at least the given minimum - - // value. If the currect capacity of the UncheckedList is less than min, the - // capacity is increased to twice the current capacity or to min, - // whichever is larger. - private void EnsureCapacity(int min) - { - if (items.Length < min) - { - int newCapacity = items.Length == 0 ? DefaultCapacity : items.Length * 2; - // Allow the UncheckedList to grow to maximum possible capacity (~2G elements) before encountering overflow. - // Note that this check works even when _items.Length overflowed thanks to the (uint) cast - if ((uint)newCapacity > int.MaxValue) newCapacity = int.MaxValue; - if (newCapacity < min) newCapacity = min; - Capacity = newCapacity; - } - } - - public bool Exists(Predicate match) - { - return FindIndex(match) != -1; - } - - public T Find(Predicate match) - { - for (int i = 0; i < size; i++) - { - if (match(items[i])) - { - return items[i]; - } - } - - return default(T); - } - - public UncheckedList FindAll(Predicate match) - { - UncheckedList uncheckedList = new UncheckedList(); - for (int i = 0; i < size; i++) - { - if (match(items[i])) - { - uncheckedList.Add(items[i]); - } - } - - return uncheckedList; - } - - public int FindIndex(Predicate match) - { - return FindIndex(0, size, match); - } - - public int FindIndex(int startIndex, Predicate match) - { - return FindIndex(startIndex, size - startIndex, match); - } - - public int FindIndex(int startIndex, int count, Predicate match) - { - int endIndex = startIndex + count; - for (int i = startIndex; i < endIndex; i++) - { - if (match(items[i])) return i; - } - - return -1; - } - - public T FindLast(Predicate match) - { - for (int i = size - 1; i >= 0; i--) - { - if (match(items[i])) - { - return items[i]; - } - } - - return default(T); - } - - public int FindLastIndex(Predicate match) - { - return FindLastIndex(size - 1, size, match); - } - - public int FindLastIndex(int startIndex, Predicate match) - { - return FindLastIndex(startIndex, startIndex + 1, match); - } - - public int FindLastIndex(int startIndex, int count, Predicate match) - { - int endIndex = startIndex - count; - for (int i = startIndex; i > endIndex; i--) - { - if (match(items[i])) - { - return i; - } - } - - return -1; - } - - public void ForEach(Action action) - { - int ver = this.version; - for (int i = 0; i < size; i++) - { - if (ver != this.version) - { - break; - } - - action(items[i]); - } - } // Returns an enumerator for this UncheckedList with the given - - // permission for removal of elements. If modifications made to the UncheckedList - // while an enumeration is in progress, the MoveNext and - // GetObject methods of the enumerator will throw an exception. - // - public Enumerator GetEnumerator() - { - return new Enumerator(this); - } - - /// - IEnumerator IEnumerable.GetEnumerator() - { - return new Enumerator(this); - } - - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() - { - return new Enumerator(this); - } - - public UncheckedList GetRange(int index, int count) - { - UncheckedList uncheckedList = new UncheckedList(count); - Array.Copy(items, index, uncheckedList.items, 0, count); - uncheckedList.size = count; - return uncheckedList; - } - - // Returns the index of the first occurrence of a given value in a range of - // this UncheckedList. The UncheckedList is searched forwards from beginning to end. - // The elements of the UncheckedList are compared to the given value using the - // Object.Equals method. - // - // This method uses the Array.IndexOf method to perform the - // search. - // - public int IndexOf(T item) - { - return Array.IndexOf(items, item, 0, size); - } - - int System.Collections.IList.IndexOf(Object item) - { - if (IsCompatibleObject(item)) - { - return IndexOf((T)item); - } - - return -1; - } // Returns the index of the first occurrence of a given value in a range of - - // this UncheckedList. The UncheckedList is searched forwards, starting at index - // index and ending at count number of elements. The - // elements of the UncheckedList are compared to the given value using the - // Object.Equals method. - // - // This method uses the Array.IndexOf method to perform the - // search. - // - public int IndexOf(T item, int index) - { - return Array.IndexOf(items, item, index, size - index); - } // Returns the index of the first occurrence of a given value in a range of - - // this UncheckedList. The UncheckedList is searched forwards, starting at index - // index and upto count number of elements. The - // elements of the UncheckedList are compared to the given value using the - // Object.Equals method. - // - // This method uses the Array.IndexOf method to perform the - // search. - // - public int IndexOf(T item, int index, int count) - { - return Array.IndexOf(items, item, index, count); - } // Inserts an element into this UncheckedList at a given index. The size of the UncheckedList - - // is increased by one. If required, the capacity of the UncheckedList is doubled - // before inserting the new element. - // - public void Insert(int index, T item) - { - if (size == items.Length) EnsureCapacity(size + 1); - if (index < size) - { - Array.Copy(items, index, items, index + 1, size - index); - } - - items[index] = item; - size++; - version++; - } - - void System.Collections.IList.Insert(int index, Object item) - { - Insert(index, (T)item); - } // Inserts the elements of the given collection at a given index. If - - // required, the capacity of the UncheckedList is increased to twice the previous - // capacity or the new size, whichever is larger. Ranges may be added - // to the end of the UncheckedList by setting index to the UncheckedList's size. - // - public void InsertRange(int index, IEnumerable collection) - { - if (collection is ICollection c) - { - // if collection is ICollection - int count = c.Count; - if (count > 0) - { - EnsureCapacity(size + count); - if (index < size) - { - Array.Copy(items, index, items, index + count, size - index); - } // If we're inserting a UncheckedList into itself, we want to be able to deal with that. - - // ReSharper disable PossibleUnintendedReferenceComparison - if (this == c) - // ReSharper restore PossibleUnintendedReferenceComparison - { - // Copy first part of _items to insert location - Array.Copy(items, 0, items, index, index); - // Copy last part of _items back to inserted location - Array.Copy(items, index + count, items, index * 2, size - index); - } - else - { - T[] itemsToInsert = new T[count]; - c.CopyTo(itemsToInsert, 0); - itemsToInsert.CopyTo(items, index); - } - - size += count; - } - } - else - { - using (IEnumerator en = collection.GetEnumerator()) - { - while (en.MoveNext()) - { - Insert(index++, en.Current); - } - } - } - - version++; - } // Returns the index of the last occurrence of a given value in a range of - - // this UncheckedList. The UncheckedList is searched backwards, starting at the end - // and ending at the first element in the UncheckedList. The elements of the UncheckedList - // are compared to the given value using the Object.Equals method. - // - // This method uses the Array.LastIndexOf method to perform the - // search. - // - public int LastIndexOf(T item) - { - if (size == 0) - { - // Special case for empty UncheckedList - return -1; - } - else - { - return LastIndexOf(item, size - 1, size); - } - } // Returns the index of the last occurrence of a given value in a range of - - // this UncheckedList. The UncheckedList is searched backwards, starting at index - // index and ending at the first element in the UncheckedList. The - // elements of the UncheckedList are compared to the given value using the - // Object.Equals method. - // - // This method uses the Array.LastIndexOf method to perform the - // search. - // - public int LastIndexOf(T item, int index) - { - return LastIndexOf(item, index, index + 1); - } // Returns the index of the last occurrence of a given value in a range of - - // this UncheckedList. The UncheckedList is searched backwards, starting at index - // index and upto count elements. The elements of - // the UncheckedList are compared to the given value using the Object.Equals - // method. - // - // This method uses the Array.LastIndexOf method to perform the - // search. - // - public int LastIndexOf(T item, int index, int count) - { - if (size == 0) - { - // Special case for empty UncheckedList - return -1; - } - - return Array.LastIndexOf(items, item, index, count); - } // Removes the element at the given index. The size of the UncheckedList is - - // decreased by one. - // - public bool Remove(T item) - { - int index = IndexOf(item); - if (index >= 0) - { - RemoveAt(index); - return true; - } - - return false; - } - - void System.Collections.IList.Remove(Object item) - { - if (IsCompatibleObject(item)) - { - Remove((T)item); - } - } // This method removes all items which matches the predicate. - - // The complexity is O(n). - public int RemoveAll(Predicate match) - { - int freeIndex = - 0; // the first free slot in items array // Find the first item which needs to be removed. - while (freeIndex < size && !match(items[freeIndex])) freeIndex++; - if (freeIndex >= size) return 0; - int current = freeIndex + 1; - while (current < size) - { - // Find the first item which needs to be kept. - while (current < size && match(items[current])) current++; - if (current < size) - { - // copy item to the free slot. - items[freeIndex++] = items[current++]; - } - } - - Array.Clear(items, freeIndex, size - freeIndex); - int result = size - freeIndex; - size = freeIndex; - version++; - return result; - } // Removes the element at the given index. The size of the UncheckedList is - - // decreased by one. - // - public void RemoveAt(int index) - { - size--; - if (index < size) - { - Array.Copy(items, index + 1, items, index, size - index); - } - - items[size] = default(T); - version++; - } // Removes a range of elements from this UncheckedList. - - // - public void RemoveRange(int index, int count) - { - if (count > 0) - { - size -= count; - if (index < size) - { - Array.Copy(items, index + count, items, index, size - index); - } - - Array.Clear(items, size, count); - version++; - } - } // Reverses the elements in this UncheckedList. - - public void Reverse() - { - Reverse(0, Count); - } // Reverses the elements in a range of this UncheckedList. Following a call to this - - // method, an element in the range given by index and count - // which was previously located at index i will now be located at - // index index + (index + count - i - 1). - // - // This method uses the Array.Reverse method to reverse the - // elements. - // - public void Reverse(int index, int count) - { - Array.Reverse(items, index, count); - version++; - } // Sorts the elements in this UncheckedList. Uses the default comparer and - - // Array.Sort. - public void Sort() - { - Sort(0, Count, null); - } // Sorts the elements in this UncheckedList. Uses Array.Sort with the - - // provided comparer. - public void Sort(IComparer comparer) - { - Sort(0, Count, comparer); - } // Sorts the elements in a section of this UncheckedList. The sort compares the - - // elements to each other using the given IComparer interface. If - // comparer is null, the elements are compared to each other using - // the IComparable interface, which in that case must be implemented by all - // elements of the UncheckedList. - // - // This method uses the Array.Sort method to sort the elements. - // - public void Sort(int index, int count, IComparer comparer) - { - Array.Sort(items, index, count, comparer); - version++; - } - - public void Sort(Comparison comparison) - { - if (size > 0) - { - IComparer comparer = new FunctorComparer(comparison); - Array.Sort(items, 0, size, comparer); - } - } // ToArray returns a new Object array containing the contents of the UncheckedList. - - // This requires copying the UncheckedList, which is an O(n) operation. - public T[] ToArray() - { - T[] array = new T[size]; - Array.Copy(items, 0, array, 0, size); - return array; - } // Sets the capacity of this UncheckedList to the size of the UncheckedList. This method can - - // be used to minimize a UncheckedList's memory overhead once it is known that no - // new elements will be added to the UncheckedList. To completely clear a UncheckedList and - // release all memory referenced by the UncheckedList, execute the following - // statements: - // - // UncheckedList.Clear(); - // UncheckedList.TrimExcess(); - // - public void TrimExcess() - { - int threshold = (int)(items.Length * 0.9); - if (size < threshold) - { - Capacity = size; - } - } - - public bool TrueForAll(Predicate match) - { - for (int i = 0; i < size; i++) - { - if (!match(items[i])) - { - return false; - } - } - - return true; - } - - internal static IList Synchronized(UncheckedList uncheckedList) - { - return new SynchronizedList(uncheckedList); - } - - [Serializable()] - internal class SynchronizedList : IList - { - private UncheckedList list; - private Object root; - - internal SynchronizedList(UncheckedList uncheckedList) - { - list = uncheckedList; - root = ((System.Collections.ICollection)uncheckedList).SyncRoot; - } - - public int Count - { - get - { - lock (root) - { - return list.Count; - } - } - } - - // ReSharper disable InconsistentlySynchronizedField - public bool IsReadOnly => ((ICollection)list).IsReadOnly; - // ReSharper restore InconsistentlySynchronizedField - - public void Add(T item) - { - lock (root) - { - list.Add(item); - } - } - - public void Clear() - { - lock (root) - { - list.Clear(); - } - } - - public bool Contains(T item) - { - lock (root) - { - return list.Contains(item); - } - } - - public void CopyTo(T[] array, int arrayIndex) - { - lock (root) - { - list.CopyTo(array, arrayIndex); - } - } - - public bool Remove(T item) - { - lock (root) - { - return list.Remove(item); - } - } - - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() - { - lock (root) - { - return list.GetEnumerator(); - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - lock (root) - { - return ((IEnumerable)list).GetEnumerator(); - } - } - - public T this[int index] - { - get - { - lock (root) - { - return list[index]; - } - } - set - { - lock (root) - { - list[index] = value; - } - } - } - - public int IndexOf(T item) - { - lock (root) - { - return list.IndexOf(item); - } - } - - public void Insert(int index, T item) - { - lock (root) - { - list.Insert(index, item); - } - } - - public void RemoveAt(int index) - { - lock (root) - { - list.RemoveAt(index); - } - } - } - - [Serializable] - public struct Enumerator : IEnumerator - { - private UncheckedList uncheckedList; - private int index; - private int version; - private T current; - - internal Enumerator(UncheckedList uncheckedList) - { - this.uncheckedList = uncheckedList; - index = 0; - version = uncheckedList.version; - current = default(T); - } - - public void Dispose() - { - } - - public bool MoveNext() - { - UncheckedList localList = uncheckedList; - if (version == localList.version && ((uint)index < (uint)localList.size)) - { - current = localList.items[index]; - index++; - return true; - } - - return MoveNextRare(); - } - - private bool MoveNextRare() - { - index = uncheckedList.size + 1; - current = default(T); - return false; - } - - public T Current => current; - - Object System.Collections.IEnumerator.Current => Current; - - void System.Collections.IEnumerator.Reset() - { - index = 0; - current = default(T); - } - } - } - // ReSharper restore CognitiveComplexity -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Shared/Collections/UncheckedStack.cs b/Nino_Unity/Assets/Nino/Shared/Collections/UncheckedStack.cs deleted file mode 100644 index 260ce93..0000000 --- a/Nino_Unity/Assets/Nino/Shared/Collections/UncheckedStack.cs +++ /dev/null @@ -1,261 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Security.Permissions; - -namespace Nino.Shared -{ - [Serializable] - public class UncheckedStack : IEnumerable, - System.Collections.ICollection, - IReadOnlyCollection - { - private T[] _array; // Storage for UncheckedStack elements - private int _size; // Number of items in the UncheckedStack. - private int _version; // Used to keep enumerator in sync w/ collection. - private Object _syncRoot; - - private const int _defaultCapacity = 4; - static T[] _emptyArray = new T[0]; - - public UncheckedStack() - { - _array = _emptyArray; - _size = 0; - _version = 0; - } - - // Create a UncheckedStack with a specific initial capacity. The initial capacity - // must be a non-negative number. - public UncheckedStack(int capacity) - { - _array = new T[capacity]; - _size = 0; - _version = 0; - } - - // Fills a UncheckedStack with the contents of a particular collection. The items are - // pushed onto the UncheckedStack in the same order they are read by the enumerator. - public UncheckedStack(IEnumerable collection) - { - ICollection c = collection as ICollection; - if (c != null) - { - int count = c.Count; - _array = new T[count]; - c.CopyTo(_array, 0); - _size = count; - } - else - { - _size = 0; - _array = new T[_defaultCapacity]; - - using (IEnumerator en = collection.GetEnumerator()) - { - while (en.MoveNext()) - { - Push(en.Current); - } - } - } - } - - public int Count => _size; - - bool System.Collections.ICollection.IsSynchronized => false; - - Object System.Collections.ICollection.SyncRoot - { - get - { - if (_syncRoot == null) - { - System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null); - } - - return _syncRoot; - } - } - - // Removes all Objects from the UncheckedStack. - public void Clear() - { - Array.Clear(_array, 0, - _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. - _size = 0; - _version++; - } - - public bool Contains(T item) - { - int count = _size; - - EqualityComparer c = EqualityComparer.Default; - while (count-- > 0) - { - if (((Object)item) == null) - { - if (((Object)_array[count]) == null) - return true; - } - else if (_array[count] != null && c.Equals(_array[count], item)) - { - return true; - } - } - - return false; - } - - // Copies the UncheckedStack into an array. - public void CopyTo(T[] array, int arrayIndex) - { - Array.Copy(_array, 0, array, arrayIndex, _size); - Array.Reverse(array, arrayIndex, _size); - } - - void System.Collections.ICollection.CopyTo(Array array, int arrayIndex) - { - Array.Copy(_array, 0, array, arrayIndex, _size); - Array.Reverse(array, arrayIndex, _size); - } - - // Returns an IEnumerator for this UncheckedStack. - public Enumerator GetEnumerator() - { - return new Enumerator(this); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return new Enumerator(this); - } - - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() - { - return new Enumerator(this); - } - - public void TrimExcess() - { - int threshold = (int)(((double)_array.Length) * 0.9); - if (_size < threshold) - { - T[] newarray = new T[_size]; - Array.Copy(_array, 0, newarray, 0, _size); - _array = newarray; - _version++; - } - } - - // Returns the top object on the UncheckedStack without removing it. If the UncheckedStack - // is empty, Peek throws an InvalidOperationException. - public T Peek() - { - return _array[_size - 1]; - } - - // Pops an item from the top of the UncheckedStack. If the UncheckedStack is empty, Pop - // throws an InvalidOperationException. - public T Pop() - { - _version++; - T item = _array[--_size]; - _array[_size] = default(T); // Free memory quicker. - return item; - } - - // Pushes an item to the top of the UncheckedStack. - public void Push(T item) - { - if (_size == _array.Length) - { - T[] newArray = new T[(_array.Length == 0) ? _defaultCapacity : 2 * _array.Length]; - Array.Copy(_array, 0, newArray, 0, _size); - _array = newArray; - } - - _array[_size++] = item; - _version++; - } - - // Copies the UncheckedStack to an array, in the same order Pop would return the items. - public T[] ToArray() - { - T[] objArray = new T[_size]; - int i = 0; - while (i < _size) - { - objArray[i] = _array[_size - i - 1]; - i++; - } - - return objArray; - } - - [Serializable()] - [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", - Justification = "not an expected scenario")] - public struct Enumerator : IEnumerator, - System.Collections.IEnumerator - { - private UncheckedStack _stack; - private int _index; - private int _version; - private T currentElement; - - internal Enumerator(UncheckedStack UncheckedStack) - { - _stack = UncheckedStack; - _version = _stack._version; - _index = -2; - currentElement = default(T); - } - - public void Dispose() - { - _index = -1; - } - - public bool MoveNext() - { - bool retval; - if (_index == -2) - { - // First call to enumerator. - _index = _stack._size - 1; - retval = (_index >= 0); - if (retval) - currentElement = _stack._array[_index]; - return retval; - } - - if (_index == -1) - { - // End of enumeration. - return false; - } - - retval = (--_index >= 0); - if (retval) - currentElement = _stack._array[_index]; - else - currentElement = default(T); - return retval; - } - - public T Current => currentElement; - - Object System.Collections.IEnumerator.Current => currentElement; - - void System.Collections.IEnumerator.Reset() - { - _index = -2; - currentElement = default(T); - } - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Shared/IO/Buffer/ExtensibleBuffer.cs b/Nino_Unity/Assets/Nino/Shared/IO/Buffer/ExtensibleBuffer.cs deleted file mode 100644 index 4302438..0000000 --- a/Nino_Unity/Assets/Nino/Shared/IO/Buffer/ExtensibleBuffer.cs +++ /dev/null @@ -1,208 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; - -namespace Nino.Shared.IO -{ - /// - /// A buffer that can dynamically extend - /// - /// - public sealed unsafe class ExtensibleBuffer where T : unmanaged - { - /// - /// Default size of the buffer - /// - private const int DefaultBufferSize = 128; - - /// - /// Data that stores everything - /// - public T* Data { get; private set; } - - /// - /// Size of T - /// - private readonly byte sizeOfT; - - /// - /// expand size for each block - /// - public readonly int ExpandSize; - - /// - /// Total length of the buffer - /// - public int TotalLength { get; private set; } - - /// - /// Init buffer - /// - public ExtensibleBuffer() : this(DefaultBufferSize) - { - - } - - /// - /// Init extensible buffer with a capacity - /// - /// - public ExtensibleBuffer([In] int size = DefaultBufferSize) - { - sizeOfT = (byte)sizeof(T); - ExpandSize = size; - Data = (T*)Marshal.AllocHGlobal(sizeOfT * ExpandSize); - TotalLength = ExpandSize; - GC.AddMemoryPressure(sizeOfT * ExpandSize); - } - - /// - /// Get element at index - /// - /// - public T this[in int index] - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => *(Data + index); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - set - { - EnsureCapacity(in index); - *(Data + index) = value; - } - } - - /// - /// Ensure index exists - /// - /// - private void EnsureCapacity(in int index) - { - if (index < TotalLength) return; - GC.RemoveMemoryPressure(TotalLength * sizeOfT); - while (index >= TotalLength) - { - TotalLength += ExpandSize; - } - Extend(); - GC.AddMemoryPressure(TotalLength * sizeOfT); - } - - /// - /// Extend buffer - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void Extend() - { - Data = (T*)Marshal.ReAllocHGlobal((IntPtr)Data, new IntPtr(TotalLength * sizeOfT)); - } - - /// - /// Convert buffer data to an Array (will create a new array and copy values) - /// - /// - /// - /// - public T[] ToArray([In] int startIndex, [In] int length) - { - T[] ret = new T[length]; - CopyTo(ref ret, startIndex, length); - return ret; - } - - /// - /// convert an extensible to buffer from start index with provided length - /// - /// - /// - /// - public Span AsSpan([In] int startIndex, [In] int length) - { - var l = startIndex + length; - //size check - EnsureCapacity(in l); - return new Span(Data + startIndex, length); - } - - /// - /// Convert to span - /// - /// - /// - public static implicit operator Span(ExtensibleBuffer buffer) => buffer.AsSpan(0, buffer.TotalLength); - - /// - /// Copy data to extensible buffer - /// - /// - /// - /// - /// - /// - public void CopyFrom(T[] src, [In] int srcIndex, [In] int dstIndex, [In] int length) - { - fixed (T* ptr = src) - { - CopyFrom(ptr, srcIndex, dstIndex, length); - } - } - - /// - /// Copy data to extensible buffer - /// why unaligned? https://stackoverflow.com/a/72418388 - /// - /// - /// - /// - /// - /// - public void CopyFrom([In] T* src, [In] int srcIndex, [In] int dstIndex, [In] int length) - { - var l = dstIndex + length; - //size check - EnsureCapacity(in l); - //copy - Unsafe.CopyBlock(Data + dstIndex, src + srcIndex, (uint)length); - } - - /// - /// Copy data from buffer to dst from dst[0] - /// - /// - /// - /// - /// - public void CopyTo(ref T[] dst, [In] int srcIndex, [In] int length) - { - fixed (T* ptr = dst) - { - CopyTo(ptr, srcIndex, length); - } - } - - /// - /// Copy data from buffer to dst from dst[0] - /// - /// - /// - /// - /// - public void CopyTo([In] T* dst, [In] int srcIndex, [In] int length) - { - var l = srcIndex + length; - //size check - EnsureCapacity(in l); - //copy - Unsafe.CopyBlock(dst, Data + srcIndex, (uint)length); - } - - /// - /// Free allocated memories - /// - ~ExtensibleBuffer() - { - Marshal.FreeHGlobal((IntPtr)Data); - GC.RemoveMemoryPressure(sizeOfT * TotalLength); - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Shared/IO/Buffer/ExtensibleBufferExtensions.cs b/Nino_Unity/Assets/Nino/Shared/IO/Buffer/ExtensibleBufferExtensions.cs deleted file mode 100644 index 643f2e2..0000000 --- a/Nino_Unity/Assets/Nino/Shared/IO/Buffer/ExtensibleBufferExtensions.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using System.IO; - -namespace Nino.Shared.IO -{ - /// - /// Extensible buffer ext - /// - public static class ExtensibleBufferExtensions - { - /// - /// Write data to stream - /// - /// - /// - /// - public static void WriteToStream(this ExtensibleBuffer buffer, Stream stream, int length) - { - byte[] bytes = ArrayPool.Request(4096); - if (length <= 4096) - { - buffer.CopyTo(ref bytes, 0, length); - stream.Write(bytes, 0, length); - ArrayPool.Return(bytes); - return; - } - - int wrote = 0; - while(length > 0) - { - int sizeToWrite = length <= 4096 ? length : 4096; - buffer.CopyTo(ref bytes, wrote, sizeToWrite); - stream.Write(bytes, 0, sizeToWrite); - length -= sizeToWrite; - wrote += sizeToWrite; - } - ArrayPool.Return(bytes); - } - - /// - /// Write data to stream - /// - /// - /// - /// - // ReSharper disable RedundantNameQualifier - public static unsafe void WriteToStream(this ExtensibleBuffer buffer, Nino.Shared.IO.DeflateStream stream, int length) - // ReSharper restore RedundantNameQualifier - { - stream.Write(buffer.Data, 0, length); - } - -#if !NETSTANDARD && !NET461 && !UNITY_2017_1_OR_NEWER - /// - /// Write data to stream - /// - /// - /// - /// - public static unsafe void WriteToStream(this ExtensibleBuffer buffer, System.IO.Compression.DeflateStream stream, int length) - { - stream.Write(new ReadOnlySpan(buffer.Data,length)); - } -#endif - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Shared/IO/Pool/ArrayPool.cs b/Nino_Unity/Assets/Nino/Shared/IO/Pool/ArrayPool.cs deleted file mode 100644 index d3b6957..0000000 --- a/Nino_Unity/Assets/Nino/Shared/IO/Pool/ArrayPool.cs +++ /dev/null @@ -1,90 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Nino.Shared.IO -{ - /// - /// Thread safe array pool - /// - /// - public static class ArrayPool - { - /// - /// Shared pool - /// - private static readonly Dictionary> Pool = new Dictionary>(3); - - /// - /// lock obj - /// - // ReSharper disable StaticMemberInGenericType - private static readonly object Lock = new object(); - // ReSharper restore StaticMemberInGenericType - - /// - /// Check pool size - /// - /// - private static void CheckPool(int size) - { - lock (Lock) - { - if (!Pool.TryGetValue(size, out _)) - { - //new queue - Pool.Add(size, new UncheckedStack()); - } - } - } - - /// - /// Request a T arr with internal length of size - /// - /// - /// - public static T[] Request(int size) - { - CheckPool(size); - lock (Lock) - { - var queue = Pool[size]; - //get from queue - if (queue.Count > 0) - { - var ret = queue.Pop(); - //double check - if (ret.Length != size) - { - Array.Resize(ref ret, size); - } - return ret; - } - //return new obj[] - return new T[size]; - } - } - - /// - /// Return arr to pool - /// - /// - /// - public static void Return(int size, T[] arr) - { - CheckPool(size); - lock (Lock) - { - Pool[size].Push(arr); - } - } - - /// - /// Return arr to pool - /// - /// - public static void Return(T[] arr) - { - Return(arr.Length, arr); - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Shared/IO/Pool/BufferPool.cs b/Nino_Unity/Assets/Nino/Shared/IO/Pool/BufferPool.cs deleted file mode 100644 index 18f01d4..0000000 --- a/Nino_Unity/Assets/Nino/Shared/IO/Pool/BufferPool.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System; - -namespace Nino.Shared.IO -{ - /// - /// Thread safe byte array (buffer) pool - /// - public static class BufferPool - { - /// - /// A shared buffer queue - /// - private static readonly UncheckedStack Buffers = new UncheckedStack(3); - - /// - /// Request a buffer - /// - /// - /// - public static byte[] RequestBuffer(int size = 0) - { - lock (Buffers) - { - byte[] ret; - if (Buffers.Count > 0) - { - ret = Buffers.Peek(); - if (ret.Length < size) - { - byte[] buffer = new byte[size]; - return buffer; - } - - ret = Buffers.Pop(); - } - else - { - ret = new byte[size]; - } - - return ret; - } - } - - /// - /// Request a buffer from a source - /// - /// - /// - public static byte[] RequestBuffer(byte[] original) - { - byte[] ret = RequestBuffer(original.Length); - Buffer.BlockCopy(original,0,ret,0,original.Length); - return ret; - } - - /// - /// Request a buffer from a source - /// - /// - /// - /// - public static byte[] RequestBuffer(int len, byte[] original) - { - byte[] ret = RequestBuffer(len); - var bLen = Math.Min(original.Length, len); - Buffer.BlockCopy(original,0,ret,0,bLen); - return ret; - } - - /// - /// Return buffer to the pool - /// - /// - public static void ReturnBuffer(byte[] buffer) - { - lock (Buffers) - { - Buffers.Push(buffer); - } - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Shared/IO/Pool/ObjectPool.cs b/Nino_Unity/Assets/Nino/Shared/IO/Pool/ObjectPool.cs deleted file mode 100644 index 203beda..0000000 --- a/Nino_Unity/Assets/Nino/Shared/IO/Pool/ObjectPool.cs +++ /dev/null @@ -1,73 +0,0 @@ -namespace Nino.Shared.IO -{ - /// - /// Thread safe object pool - /// - /// - public static class ObjectPool where T: class, new() - { - /// - /// A shared buffer queue - /// - private static readonly UncheckedStack Pool = new UncheckedStack(3); - - /// - /// lock obj - /// - // ReSharper disable StaticMemberInGenericType - private static readonly object Lock = new object(); - // ReSharper restore StaticMemberInGenericType - - /// - /// Request an obj - /// - /// - public static T Request() - { - lock (Lock) - { - T ret; - if (Pool.Count > 0) - { - ret = Pool.Pop(); - return ret; - } - else - { - ret = new T(); - } - - return ret; - } - } - - /// - /// Preview the next object from stack, wont take - /// - /// - public static T Peak() - { - lock (Lock) - { - if (Pool.Count > 0) - { - return Pool.Peek(); - } - - return null; - } - } - - /// - /// Return an obj to pool - /// - /// - public static void Return(T obj) - { - lock (Lock) - { - Pool.Push(obj); - } - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Shared/IO/Stream/DeflateStream.cs b/Nino_Unity/Assets/Nino/Shared/IO/Stream/DeflateStream.cs deleted file mode 100644 index f361f5f..0000000 --- a/Nino_Unity/Assets/Nino/Shared/IO/Stream/DeflateStream.cs +++ /dev/null @@ -1,608 +0,0 @@ -using System; -using System.IO; -using System.Threading; -using System.IO.Compression; -using System.Runtime.InteropServices; - -namespace Nino.Shared.IO -{ - public class DeflateStream : Stream - { - private delegate int ReadMethod(byte[] array, int offset, int count); - - private delegate void WriteMethod(byte[] array, int offset, int count); - - private FlexibleStream baseStream; - - private CompressionMode mode; - - private readonly bool leaveOpen; - - private bool disposed; - - private readonly DeflateStreamNative native; - - public FlexibleStream BaseStream => baseStream; - - public override bool CanRead - { - get - { - if (!disposed && mode == CompressionMode.Decompress) - { - return baseStream.CanRead; - } - return false; - } - } - - public override bool CanSeek => false; - - public override bool CanWrite - { - get - { - if (!disposed && mode == CompressionMode.Compress) - { - return baseStream.CanWrite; - } - return false; - } - } - - public override long Length => throw new NotSupportedException(); - - public override long Position - { - get => throw new NotSupportedException(); - set => throw new NotSupportedException(); - } - - public DeflateStream(FlexibleStream stream, CompressionMode mode) - : this(stream, mode, false, false) - { - } - - public DeflateStream(FlexibleStream stream, CompressionMode mode, bool leaveOpen) - : this(stream, mode, leaveOpen, false) - { - } - - private DeflateStream(FlexibleStream compressedStream, CompressionMode mode, bool leaveOpen, bool gzip) - { - if (mode != CompressionMode.Compress && mode != 0) - { - throw new ArgumentException("mode"); - } - baseStream = compressedStream ?? throw new ArgumentNullException(nameof(compressedStream)); - native = DeflateStreamNative.Create(compressedStream, mode, gzip); - if (native == null) - { - throw new NotImplementedException("Failed to initialize zlib. You probably have an old zlib installed. Version 1.2.0.4 or later is required."); - } - this.mode = mode; - this.leaveOpen = leaveOpen; - } - - ~DeflateStream() - { - Dispose(false); - } - - /// - /// Finish compressing - /// - public void Finish() - { - native.DisposeZStream(); - } - - /// - /// Reset deflate stream - /// - public void Reset() - { - baseStream.Position = 0; - baseStream.SetLength(0); - native.ResetZStream(mode, false); - } - - /// - /// Get decompressed bytes - /// - /// - /// - /// - public unsafe IntPtr GetDecompressedBytes(out int length, int minLen) - { - int read; - length = 0; - var expandSize = minLen * 10; - IntPtr buffer = Marshal.AllocHGlobal(expandSize); - int maxLen = minLen * 5; - //开始写 - while ((read = Read((byte*)buffer, length, expandSize)) != 0) - { - length += read; - //如果目前读取的长度达到了buffer的一半,就需要扩容 - if (length >= maxLen) - { - maxLen += expandSize; - buffer = Marshal.ReAllocHGlobal(buffer, new IntPtr(maxLen + expandSize)); - } - } - - return buffer; - } - - protected override void Dispose(bool disposing) - { - if (disposing) - { - GC.SuppressFinalize(this); - } - native?.Dispose(disposing); - if (disposing && !disposed) - { - disposed = true; - if (!leaveOpen) - { - baseStream?.Close(); - baseStream = null; - } - } - base.Dispose(disposing); - } - - private unsafe int ReadInternal(byte[] array, int offset, int count) - { - if (count == 0) - { - return 0; - } - fixed (byte* ptr = array) - { - IntPtr buffer = new IntPtr(ptr + offset); - return native.ReadZStream(buffer, count); - } - } - - private unsafe int ReadInternal(byte* ptr, int offset, int count) - { - if (count == 0) - { - return 0; - } - IntPtr buffer = new IntPtr(ptr + offset); - return native.ReadZStream(buffer, count); - } - - public unsafe int Read(byte* array, int offset, int count) - { - if (disposed) - { - throw new ObjectDisposedException(GetType().FullName); - } - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } - if (!CanRead) - { - throw new InvalidOperationException("Stream does not support reading."); - } - if (offset < 0 || count < 0) - { - throw new ArgumentException("Dest or count is negative."); - } - return ReadInternal(array, offset, count); - } - - public override int Read(byte[] array, int offset, int count) - { - if (disposed) - { - throw new ObjectDisposedException(GetType().FullName); - } - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } - if (!CanRead) - { - throw new InvalidOperationException("Stream does not support reading."); - } - int num = array.Length; - if (offset < 0 || count < 0) - { - throw new ArgumentException("Dest or count is negative."); - } - if (offset > num) - { - throw new ArgumentException("destination offset is beyond array size"); - } - if (offset + count > num) - { - throw new ArgumentException("Reading would overrun buffer"); - } - return ReadInternal(array, offset, count); - } - - private unsafe void WriteInternal(byte[] array, int offset, int count) - { - if (count != 0) - { - fixed (byte* ptr = array) - { - IntPtr buffer = new IntPtr(ptr + offset); - native.WriteZStream(buffer, count); - } - } - } - - public unsafe void Write(byte* array, int offset, int count) - { - if (count != 0) - { - IntPtr buffer = new IntPtr(array + offset); - native.WriteZStream(buffer, count); - } - } - - public override void Write(byte[] array, int offset, int count) - { - if (disposed) - { - throw new ObjectDisposedException(GetType().FullName); - } - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } - if (offset < 0) - { - throw new ArgumentOutOfRangeException(nameof(offset)); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (!CanWrite) - { - throw new NotSupportedException("Stream does not support writing"); - } - if (offset > array.Length - count) - { - throw new ArgumentException("Buffer too small. count/offset wrong."); - } - WriteInternal(array, offset, count); - } - - public override void Flush() - { - if (disposed) - { - throw new ObjectDisposedException(GetType().FullName); - } - if (CanWrite) - { - native.Flush(); - } - } - - public override IAsyncResult BeginRead(byte[] array, int offset, int count, AsyncCallback asyncCallback, object asyncState) - { - if (disposed) - { - throw new ObjectDisposedException(GetType().FullName); - } - if (!CanRead) - { - throw new NotSupportedException("This stream does not support reading"); - } - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), "Must be >= 0"); - } - if (offset < 0) - { - throw new ArgumentOutOfRangeException(nameof(offset), "Must be >= 0"); - } - if (count + offset > array.Length) - { - throw new ArgumentException("Buffer too small. count/offset wrong."); - } - return new ReadMethod(ReadInternal).BeginInvoke(array, offset, count, asyncCallback, asyncState); - } - - public override IAsyncResult BeginWrite(byte[] array, int offset, int count, AsyncCallback asyncCallback, object asyncState) - { - if (disposed) - { - throw new ObjectDisposedException(GetType().FullName); - } - if (!CanWrite) - { - throw new InvalidOperationException("This stream does not support writing"); - } - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), "Must be >= 0"); - } - if (offset < 0) - { - throw new ArgumentOutOfRangeException(nameof(offset), "Must be >= 0"); - } - if (count + offset > array.Length) - { - throw new ArgumentException("Buffer too small. count/offset wrong."); - } - return new WriteMethod(WriteInternal).BeginInvoke(array, offset, count, asyncCallback, asyncState); - } - - public override long Seek(long offset, SeekOrigin origin) - { - throw new NotSupportedException(); - } - - public override void SetLength(long value) - { - throw new NotSupportedException(); - } - } - - internal class DeflateStreamNative - { -#if UNITY_2017_1_OR_NEWER - private const string DllName = "MonoPosixHelper"; -#else - private const string DllName = "Deflate"; -#endif - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate int UnmanagedReadOrWrite(IntPtr buffer, int length, IntPtr data); - - // ReSharper disable ClassNeverInstantiated.Local - private sealed class SafeDeflateStreamHandle : SafeHandle - // ReSharper restore ClassNeverInstantiated.Local - { -#if NET7_0_OR_GREATER - public override bool IsInvalid => handle.Equals(IntPtr.Zero); -#else - public override bool IsInvalid => handle == IntPtr.Zero; -#endif - - - // ReSharper disable UnusedMember.Local - private SafeDeflateStreamHandle() - : base(IntPtr.Zero, true) - { - } - - internal SafeDeflateStreamHandle(IntPtr handle) - : base(handle, true) - { - } - // ReSharper restore UnusedMember.Local - - [MonoPInvokeCallback] - protected override bool ReleaseHandle() - { - try - { - CloseZStream(handle); - } - catch - { - // ignored - } - - return true; - } - } - - private const int BufferSize = 4096; - - private UnmanagedReadOrWrite feeder; - - private FlexibleStream baseStream; - - private SafeDeflateStreamHandle zStream; - - private GCHandle data; - - private bool disposed; - - private Exception lastError; - - private DeflateStreamNative() - { - } - - [MonoPInvokeCallback] - public static DeflateStreamNative Create(FlexibleStream compressedStream, CompressionMode mode, bool gzip) - { - DeflateStreamNative deflateStreamNative = new DeflateStreamNative(); - deflateStreamNative.data = GCHandle.Alloc(deflateStreamNative); - deflateStreamNative.feeder = ((mode == CompressionMode.Compress) ? UnmanagedWrite : new UnmanagedReadOrWrite(UnmanagedRead)); - deflateStreamNative.zStream = CreateZStream(mode, gzip, deflateStreamNative.feeder, GCHandle.ToIntPtr(deflateStreamNative.data)); - if (deflateStreamNative.zStream.IsInvalid) - { - deflateStreamNative.Dispose(true); - return null; - } - deflateStreamNative.baseStream = compressedStream; - return deflateStreamNative; - } - - [MonoPInvokeCallback] - public void DisposeZStream() - { - if (zStream != null && !zStream.IsInvalid) - { - zStream.Dispose(); - } - } - - [MonoPInvokeCallback] - public void ResetZStream(CompressionMode mode, bool gzip) - { - zStream = CreateZStream(mode, gzip, this.feeder, GCHandle.ToIntPtr(this.data)); - } - - ~DeflateStreamNative() - { - Dispose(false); - } - - [MonoPInvokeCallback] - public void Dispose(bool disposing) - { - if (disposing && !disposed) - { - disposed = true; - GC.SuppressFinalize(this); - } - else - { - baseStream = Stream.Null as FlexibleStream; - } - if (zStream != null && !zStream.IsInvalid) - { - zStream.Dispose(); - } - _ = data; - if (data.IsAllocated) - { - data.Free(); - } - } - - [MonoPInvokeCallback] - public void Flush() - { - int result = Flush(zStream); - CheckResult(result, "Flush"); - } - - [MonoPInvokeCallback] - public int ReadZStream(IntPtr buffer, int length) - { - int result = ReadZStream(zStream, buffer, length); - CheckResult(result, "ReadInternal"); - return result; - } - - [MonoPInvokeCallback] - public void WriteZStream(IntPtr buffer, int length) - { - int result = WriteZStream(zStream, buffer, length); - CheckResult(result, "WriteInternal"); - } - - [MonoPInvokeCallback] - private static int UnmanagedRead(IntPtr buffer, int length, IntPtr data) - { - if (!(GCHandle.FromIntPtr(data).Target is DeflateStreamNative deflateStreamNative)) - { - return -1; - } - return deflateStreamNative.UnmanagedRead(buffer, length); - } - - [MonoPInvokeCallback] - private unsafe int UnmanagedRead(IntPtr buffer, int length) - { - int count = Math.Min(length, BufferSize); - int num; - try - { - num = baseStream.Read((byte*)buffer, 0, count); - } - catch - { - return -12; - } - return num; - } - - [MonoPInvokeCallback] - private static int UnmanagedWrite(IntPtr buffer, int length, IntPtr data) - { - if (!(GCHandle.FromIntPtr(data).Target is DeflateStreamNative deflateStreamNative)) - { - return -1; - } - return deflateStreamNative.UnmanagedWrite(buffer, length); - } - - [MonoPInvokeCallback] - private unsafe int UnmanagedWrite(IntPtr buffer, int length) - { - baseStream.Write((byte*)buffer, 0, length); - return length; - } - - private void CheckResult(int result, string where) - { - if (result >= 0) - { - return; - } - Exception ex = Interlocked.Exchange(ref lastError, null); - if (ex != null) - { - throw ex; - } - - string R() - { - switch(result) - { - case -1: - return "Unknown error"; - case -2 : - return "Internal error"; - case -3 : - return "Corrupted data"; - case -4 : - return "Not enough memory"; - case -5 : - return "Internal error (no progress possible)"; - case -6 : - return "Invalid version"; - case -10 : - return "Invalid argument(s)"; - case -11 : - return "IO error"; - default: - return "Unknown error"; - } - } - throw new IOException( R() + " " + where); - } - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] - private static extern SafeDeflateStreamHandle CreateZStream(CompressionMode compress, bool gzip, UnmanagedReadOrWrite feeder, IntPtr data); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] - private static extern int CloseZStream(IntPtr stream); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] - private static extern int Flush(SafeDeflateStreamHandle stream); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] - private static extern int ReadZStream(SafeDeflateStreamHandle stream, IntPtr buffer, int length); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] - private static extern int WriteZStream(SafeDeflateStreamHandle stream, IntPtr buffer, int length); - } -} diff --git a/Nino_Unity/Assets/Nino/Shared/IO/Stream/FlexibleStream.cs b/Nino_Unity/Assets/Nino/Shared/IO/Stream/FlexibleStream.cs deleted file mode 100644 index d6fd07a..0000000 --- a/Nino_Unity/Assets/Nino/Shared/IO/Stream/FlexibleStream.cs +++ /dev/null @@ -1,533 +0,0 @@ -using System; -using System.IO; -using Nino.Shared.Mgr; -using Nino.Shared.Util; - -namespace Nino.Shared.IO -{ - /// - /// Can change the buffer in anytime - /// This stream provides no GC write and read method, require to use it with stackalloc - /// - public sealed class FlexibleStream : Stream - { - private byte[] internalBuffer; // Either allocated internally or externally. - private int origin; // For user-provided arrays, start at this origin - private int position; // read/write head. - private int length; // Number of bytes within the memory stream - private int capacity; // length of usable portion of buffer for stream - - // Note that _capacity == _buffer.Length for non-user-provided byte[]'s - - private bool expandable; // User-provided buffers aren't expandable. - private readonly bool exposable; // Whether the array can be returned to the user. - private bool isOpen; // Is this stream open or closed? - - private readonly uint maxLength = 2147483648; - private const int MemStreamMaxLength = Int32.MaxValue; - - public void ChangeBuffer(byte[] data, int offset, int count) - { - Reset(); - internalBuffer = data; - origin = offset; - position = offset; - length = data.Length; - capacity = length; - } - - public void ChangeBuffer(ArraySegment data) - { - ChangeBuffer(data.Array, data.Offset, data.Count); - } - - public void Reset() - { - position = 0; - origin = 0; - length = 0; - isOpen = true; - expandable = true; - } - - public FlexibleStream(): this(ConstMgr.Null) - { - //for object pool to be able to call - } - - public FlexibleStream(byte[] internalBuffer) - { - this.internalBuffer = internalBuffer ?? throw new ArgumentNullException(nameof(internalBuffer), "buffer == null"); - length = capacity = internalBuffer.Length; - exposable = true; - expandable = true; - isOpen = true; - origin = 0; - } - - public FlexibleStream(ArraySegment internalBuffer) - { - this.internalBuffer = internalBuffer.Array ?? throw new ArgumentNullException(nameof(internalBuffer), "buffer == null"); - length = capacity = internalBuffer.Array.Length; - exposable = true; - expandable = true; - isOpen = true; - origin = internalBuffer.Offset; - position = internalBuffer.Offset; - } - - public override bool CanRead => isOpen; - - public override bool CanSeek => isOpen; - - public override bool CanWrite => isOpen; - - protected override void Dispose(bool disposing) - { - try - { - if (disposing) - { - isOpen = false; - expandable = false; - // Don't set buffer to null - allow TryGetBuffer, GetBuffer & ToArray to work. - } - } - finally - { - // Call base.Close() to cleanup async IO resources - base.Dispose(disposing); - } - } - - // returns a bool saying whether we allocated a new array. - private bool EnsureCapacity(int value) - { - // Check for overflow - if (value < 0) - throw new IOException("Stream too long, value < capacity of stream is invalid"); - if (value > capacity) - { - int newCapacity = value; - if (newCapacity < 256) - newCapacity = 256; - // We are ok with this overflowing since the next statement will deal - // with the cases where _capacity*2 overflows. - if (newCapacity < capacity * 2) - newCapacity = capacity * 2; - // We want to expand the array up to Array.MaxArrayLengthOneDimensional - // And we want to give the user the value that they asked for - if ((uint)(capacity * 2) > maxLength) - newCapacity = value < maxLength ? value : (int)(maxLength / 2); - - Capacity = newCapacity; - return true; - } - - return false; - } - - public override void Flush() - { - } - - /// - /// Get original buffer - /// - /// - /// - public byte[] GetBuffer() - { - if (!exposable) - throw new UnauthorizedAccessException("UnauthorizedAccess to get member buffer"); - return internalBuffer; - } - - /// - /// Try get original buffer - /// - /// - /// - public bool TryGetBuffer(out ArraySegment buffer) - { - if (!exposable) - { - buffer = default(ArraySegment); - return false; - } - - buffer = new ArraySegment(this.internalBuffer, offset: origin, count: (length - origin)); - return true; - } - - // Gets & sets the capacity (number of bytes allocated) for this stream. - // The capacity cannot be set to a value less than the current length - // of the stream. - // - public int Capacity - { - get - { - if (!isOpen) Logger.E("stream is closed"); - return capacity - origin; - } - set - { - // Only update the capacity if the MS is expandable and the value is different than the current capacity. - // Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity - if (value < Length) - throw new ArgumentOutOfRangeException(nameof(value), "value < capcacity is invalid"); - - if (!isOpen) Logger.E("stream is closed"); - if (!expandable && (value != Capacity)) Logger.E("FlexibleStream is not expandable"); - - // FlexibleStream has this invariant: _origin > 0 => !expandable (see ctors) - if (expandable && value != capacity) - { - if (value > 0) - { - byte[] newBuffer = new byte[value]; - if (length > 0) Buffer.BlockCopy(internalBuffer, 0, newBuffer, 0, length); - internalBuffer = newBuffer; - } - else - { - internalBuffer = null; - } - - capacity = value; - } - } - } - - /// - /// Length of written buffer or the buffer provided - /// - public override long Length - { - get - { - if (!isOpen) Logger.E("stream is closed"); - return length - origin; - } - } - - /// - /// Position of the current stream - /// - /// - public override long Position - { - get - { - if (!isOpen) Logger.E("stream is closed"); - return position - origin; - } - set - { - if (value < 0) - throw new ArgumentOutOfRangeException(nameof(value), "value < 0 is invalid"); - if (!isOpen) Logger.E("stream is closed"); - - if (value > MemStreamMaxLength) - throw new ArgumentOutOfRangeException(nameof(value), "value > stream length is invalid"); - position = origin + (int)value; - } - } - - /// - /// Read a byte from current position - /// - /// - public override int ReadByte() - { - if (!isOpen) Logger.E("stream is closed"); - - if (position >= length) return -1; - - return internalBuffer[position++]; - } - - /// - /// Read and copy some bytes to the provided buffer - has gc if buffer is a new byte[count] or byte[moreThanCount] - /// - /// - /// - /// - /// - /// - /// - /// - public override int Read(byte[] buffer, int offset, int count) - { - if (buffer == null) - throw new ArgumentNullException(nameof(buffer), "buffer == null"); - if (offset < 0) - throw new ArgumentOutOfRangeException(nameof(offset), "offset < 0"); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), "count < 0"); - if (buffer.Length - offset < count) - throw new ArgumentException("invalid buffer length"); - - if (!isOpen) Logger.E("stream is closed"); - - int n = length - position; - if (n > count) n = count; - if (n <= 0) - return 0; - - if (n <= 8) - { - int byteCount = n; - while (--byteCount >= 0) - buffer[offset + byteCount] = this.internalBuffer[position + byteCount]; - } - else - Buffer.BlockCopy(this.internalBuffer, position, buffer, offset, n); - - position += n; - - return n; - } - - /// - /// Read and copy some bytes to a byte array pointer - has no gc when buffer is stackalloc byte[count] - /// - /// - /// - /// - /// - public unsafe int Read(byte* buffer, int offset, int count) - { - if (!isOpen) Logger.E("stream is closed"); - - int n = length - position; - if (n > count) n = count; - if (n <= 0) - return 0; - - fixed (byte* internalPtr = internalBuffer) - { - Buffer.MemoryCopy(internalPtr + position, buffer + offset, count,n); - } - position += n; - - return n; - } - - /// - /// Write a byte to the stream - /// - /// - /// - public override void WriteByte(byte value) { - if (!isOpen) - throw new InvalidOperationException("this stream is closed"); - - if (position >= length) { - int newLength = position + 1; - bool mustZero = position > length; - if (newLength >= capacity) { - bool allocatedNewArray = EnsureCapacity(newLength); - if (allocatedNewArray) - mustZero = false; - } - if (mustZero) - Array.Clear(internalBuffer, length, position - length); - length = newLength; - } - internalBuffer[position++] = value; - } - - /// - /// Write some bytes to the stream from a byte[count] or byte[moreThanCount] - /// - /// - /// - /// - /// - /// - /// - /// - /// - public override void Write(byte[] buffer, int offset, int count) - { - if (buffer==null) - throw new ArgumentNullException(nameof(buffer),"null"); - if (offset < 0) - throw new ArgumentOutOfRangeException(nameof(offset), "cannot be negative"); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count),"cannot be negative"); - if (buffer.Length - offset < count) - throw new ArgumentException("invalid length"); - - if (!isOpen) - throw new InvalidOperationException("this stream is closed"); - - int i = position + count; - // Check for overflow - if (i < 0) - throw new IOException("Stream Too Long"); - - if (i > length) { - bool mustZero = position > length; - if (i > capacity) { - bool allocatedNewArray = EnsureCapacity(i); - if (allocatedNewArray) - mustZero = false; - } - if (mustZero) - Array.Clear(internalBuffer, length, i - length); - length = i; - } - if ((count <= 8) && (buffer != internalBuffer)) - { - int byteCount = count; - while (--byteCount >= 0) - internalBuffer[position + byteCount] = buffer[offset + byteCount]; - } - else - Buffer.BlockCopy(buffer, offset, internalBuffer, position, count); - position = i; - } - - /// - /// Write some bytes to the stream from a stackalloc byte[count] - /// - /// - /// - /// - /// - /// - /// - /// - /// - public unsafe void Write(byte* buffer, int offset, int count) - { - if (buffer==null) - throw new ArgumentNullException(nameof(buffer),"null"); - if (offset < 0) - throw new ArgumentOutOfRangeException(nameof(offset), "cannot be negative"); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count),"cannot be negative"); - - if (!isOpen) - throw new InvalidOperationException("this stream is closed"); - - int i = position + count; - // Check for overflow - if (i < 0) - throw new IOException("Stream Too Long"); - - if (i > length) { - bool mustZero = position > length; - if (i > capacity) { - bool allocatedNewArray = EnsureCapacity(i); - if (allocatedNewArray) - mustZero = false; - } - if (mustZero) - Array.Clear(internalBuffer, length, i - length); - length = i; - } - - fixed (byte* internalPtr = internalBuffer) - { - Buffer.MemoryCopy(buffer + offset, internalPtr + position, count, count); - } - - position = i; - } - - /// - /// Seek the stream - /// - /// - /// - /// - /// - /// - /// - public override long Seek(long offset, SeekOrigin loc) - { - if (!isOpen) Logger.E("stream is closed"); - - if (offset > MemStreamMaxLength) - throw new ArgumentOutOfRangeException(nameof(offset), "offset > stream length is invalid"); - switch (loc) - { - case SeekOrigin.Begin: - { - int tempPosition = unchecked(origin + (int)offset); - if (offset < 0 || tempPosition < origin) - throw new IOException("offset < 0 from the beginning of stream is invalid"); - position = tempPosition; - break; - } - case SeekOrigin.Current: - { - int tempPosition = unchecked(position + (int)offset); - if (unchecked(position + offset) < origin || tempPosition < origin) - throw new IOException("offset is before the stream which is invalid"); - position = tempPosition; - break; - } - case SeekOrigin.End: - { - int tempPosition = unchecked(length + (int)offset); - if (unchecked(length + offset) < origin || tempPosition < origin) - throw new IOException("offset is before the stream which is invalid"); - position = tempPosition; - break; - } - default: - throw new ArgumentException("invalid seek origin"); - } - - return position; - } - - // Sets the length of the stream to a given value. The new - // value must be nonnegative and less than the space remaining in - // the array, Int32.MaxValue - origin - // Origin is 0 in all cases other than a FlexibleStream created on - // top of an existing array and a specific starting offset was passed - // into the FlexibleStream constructor. The upper bounds prevents any - // situations where a stream may be created on top of an array then - // the stream is made longer than the maximum possible length of the - // array (Int32.MaxValue). - // - public override void SetLength(long value) - { - if (value < 0 || value > Int32.MaxValue) - { - throw new ArgumentOutOfRangeException(nameof(value), "value does not fit the length (out of range)"); - } - - // Origin wasn't publicly exposed above. - if (value > (Int32.MaxValue - origin)) - { - throw new ArgumentOutOfRangeException(nameof(value), "value is too big"); - } - - int newLength = origin + (int)value; - bool allocatedNewArray = EnsureCapacity(newLength); - if (!allocatedNewArray && newLength > length) - Array.Clear(internalBuffer, length, newLength - length); - length = newLength; - if (position > newLength) position = newLength; - - } - - /// - /// Get written bytes to array - will cause GC - /// - /// - public byte[] ToArray() - { - byte[] copy = new byte[length - origin]; - Buffer.BlockCopy(internalBuffer, origin, copy, 0, length - origin); - return copy; - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Shared/Mgr/CompressMgr.cs b/Nino_Unity/Assets/Nino/Shared/Mgr/CompressMgr.cs deleted file mode 100644 index 59e9703..0000000 --- a/Nino_Unity/Assets/Nino/Shared/Mgr/CompressMgr.cs +++ /dev/null @@ -1,352 +0,0 @@ -using System; -using System.IO; -using Nino.Shared.IO; -using System.IO.Compression; -using System.Runtime.InteropServices; -using DeflateStream = Nino.Shared.IO.DeflateStream; -// ReSharper disable UnusedMember.Local -// ReSharper disable HeuristicUnreachableCode -#pragma warning disable 162 - -namespace Nino.Shared.Mgr -{ - public static class CompressMgr - { - /// - /// static ctor - /// - static CompressMgr() - { - if (!ConstMgr.EnableNativeDeflate) return; - GetCompressInformation(out _, out _); - var compressedStream = new FlexibleStream(BufferPool.RequestBuffer(10240)); - var zipStream = new DeflateStream(compressedStream, CompressionMode.Compress, true); - CompressStreams.Push(zipStream); - var empty = new ArraySegment(Array.Empty()); - GetDecompressInformation(out _, ref empty); - compressedStream = new FlexibleStream(BufferPool.RequestBuffer(10240)); - zipStream = new DeflateStream(compressedStream, CompressionMode.Decompress, true); - DecompressStreams.Push(zipStream); - } - - /// - /// compress stream pool (deflateStream compress + flexibleStream) - /// - private static readonly UncheckedStack CompressStreams = new UncheckedStack(); - - /// - /// decompress stream pool (deflateStream decompress + flexibleStream) - /// - private static readonly UncheckedStack DecompressStreams = new UncheckedStack(); - - /// - /// lock compressed streams - /// - private static readonly object CompressedLock = new object(); - - - /// - /// lock decompressed streams - /// - private static readonly object DecompressedLock = new object(); - - /// - /// Compress the given bytes - /// - /// - /// - public static byte[] Compress(byte[] data) - { - return Compress(new ArraySegment(data)); - } - - /// - /// Compress the given bytes - /// - /// - /// - public static byte[] Compress(ArraySegment data) - { - lock (CompressedLock) - { - if (!ConstMgr.EnableNativeDeflate) - { - return CompressOnNative(data); - } - - GetCompressInformation(out var zipStream, out var compressedStream); - // ReSharper disable AssignNullToNotNullAttribute - zipStream.Write(data.Array, data.Offset, data.Count); - // ReSharper restore AssignNullToNotNullAttribute - return GetCompressBytes(zipStream, compressedStream); - } - } - - /// - /// Compress the given bytes - /// - /// - /// - /// - public static byte[] Compress(ExtensibleBuffer data, int length) - { - lock (CompressedLock) - { - if (!ConstMgr.EnableNativeDeflate) - { - return CompressOnNative(data, length); - } - - GetCompressInformation(out var zipStream, out var compressedStream); - data.WriteToStream(zipStream, length); - return GetCompressBytes(zipStream, compressedStream); - } - } - - - /// - /// Get compressed data - /// - /// - /// - /// - private static byte[] GetCompressBytes(DeflateStream zipStream, FlexibleStream compressedStream) - { - zipStream.Finish(); - //push - CompressStreams.Push(zipStream); - return compressedStream.ToArray(); - } - - /// - /// Get relevant data - /// - /// - /// - private static void GetCompressInformation(out DeflateStream zipStream, out FlexibleStream compressedStream) - { - lock (CompressedLock) - { - //try get stream - if (CompressStreams.Count > 0) - { - zipStream = CompressStreams.Pop(); - zipStream.Reset(); - compressedStream = zipStream.BaseStream; - } - else - { - //create - compressedStream = new FlexibleStream(); - zipStream = new DeflateStream(compressedStream, CompressionMode.Compress, true); - } - } - } - - /// - /// Decompress thr given bytes (NEED TO BE AWARE OF UNMANAGED INTPTR, REMEMBER TO FREE IT) - /// - /// - /// - /// - public static IntPtr Decompress(byte[] data, out int outputLength) - { - lock (DecompressedLock) - { - var seg = new ArraySegment(data); - if (!ConstMgr.EnableNativeDeflate) - { - return DecompressOnNative(seg, out outputLength); - } - - GetDecompressInformation(out var zipStream, ref seg); - var ret = zipStream.GetDecompressedBytes(out outputLength, data.Length); - //push - DecompressStreams.Push(zipStream); - return ret; - } - } - - /// - /// Decompress thr given bytes (NEED TO BE AWARE OF UNMANAGED INTPTR, REMEMBER TO FREE IT) - /// - /// - /// - /// - public static IntPtr Decompress(ArraySegment data, out int outputLength) - { - lock (DecompressedLock) - { - if (!ConstMgr.EnableNativeDeflate) - { - return DecompressOnNative(data, out outputLength); - } - - GetDecompressInformation(out var zipStream, ref data); - var ret = zipStream.GetDecompressedBytes(out outputLength, data.Count); - //push - DecompressStreams.Push(zipStream); - return ret; - } - } - - /// - /// Decompress thr given bytes - /// - /// - /// - public static byte[] Decompress(byte[] data) - { - lock (DecompressedLock) - { - var seg = new ArraySegment(data); - if (!ConstMgr.EnableNativeDeflate) - { - var ptr = DecompressOnNative(seg, out var length); - byte[] buf = new byte[length]; - Marshal.Copy(ptr, buf, 0, length); - Marshal.FreeHGlobal(ptr); - return buf; - } - - GetDecompressInformation(out var zipStream, ref seg); - var ret = zipStream.GetDecompressedBytes(out var len, data.Length); - //push - DecompressStreams.Push(zipStream); - var buffer = new byte[len]; - Marshal.Copy(ret, buffer, 0, len); - Marshal.FreeHGlobal(ret); - return buffer; - } - } - - /// - /// Decompress thr given bytes - /// - /// - /// - public static byte[] Decompress(ArraySegment data) - { - lock (DecompressedLock) - { - if (!ConstMgr.EnableNativeDeflate) - { - var ptr = DecompressOnNative(data, out var length); - byte[] buf = new byte[length]; - Marshal.Copy(ptr, buf, 0, length); - Marshal.FreeHGlobal(ptr); - return buf; - } - - GetDecompressInformation(out var zipStream, ref data); - var ret = zipStream.GetDecompressedBytes(out var len, data.Count); - //push - DecompressStreams.Push(zipStream); - var buffer = new byte[len]; - Marshal.Copy(ret, buffer, 0, len); - Marshal.FreeHGlobal(ret); - return buffer; - } - } - - - /// - /// Get relevant data - /// - /// - /// - private static void GetDecompressInformation(out DeflateStream zipStream, ref ArraySegment data) - { - lock (DecompressedLock) - { - //try get stream - if (DecompressStreams.Count > 0) - { - zipStream = DecompressStreams.Pop(); - zipStream.Reset(); - var dataStream = zipStream.BaseStream; - dataStream.ChangeBuffer(data); - } - else - { - //create - var dataStream = new FlexibleStream(data); - zipStream = new DeflateStream(dataStream, CompressionMode.Decompress, true); - } - } - } - - #region NON_UNITY - - /// - /// Compress the given bytes - /// - /// - /// - private static byte[] CompressOnNative(ArraySegment data) - { - using (var compressedStream = new MemoryStream()) - using (var zipStream = new System.IO.Compression.DeflateStream(compressedStream, CompressionMode.Compress)) - { - // ReSharper disable AssignNullToNotNullAttribute - zipStream.Write(data.Array, data.Offset, data.Count); - // ReSharper restore AssignNullToNotNullAttribute - zipStream.Close(); - return compressedStream.ToArray(); - } - } - - /// - /// Compress the given bytes - /// - /// - /// - /// - private static byte[] CompressOnNative(ExtensibleBuffer data, int length) - { - using (var compressedStream = new MemoryStream(length)) - using (var zipStream = new System.IO.Compression.DeflateStream(compressedStream, CompressionMode.Compress)) - { - data.WriteToStream(zipStream, length); - zipStream.Close(); - return compressedStream.ToArray(); - } - } - - /// - /// Decompress thr given bytes - /// - /// - /// - /// - private static IntPtr DecompressOnNative(ArraySegment data, out int len) - { - FlexibleStream result = ObjectPool.Request(); - result.Reset(); - FlexibleStream compressedStream; - if (ObjectPool.Peak() != null) - { - compressedStream = ObjectPool.Request(); - compressedStream.ChangeBuffer(data.Array, data.Offset, data.Count); - } - else - { - compressedStream = new FlexibleStream(data); - } - - using (var zipStream = - new System.IO.Compression.DeflateStream(compressedStream, CompressionMode.Decompress)) - { - zipStream.CopyTo(result); - ObjectPool.Return(compressedStream); - len = (int)result.Length; - IntPtr ptr = Marshal.AllocHGlobal(len); - Marshal.Copy(result.GetBuffer(), 0, ptr, len); - ObjectPool.Return(result); - return ptr; - } - } - - #endregion - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Shared/Mgr/ConstMgr.cs b/Nino_Unity/Assets/Nino/Shared/Mgr/ConstMgr.cs deleted file mode 100644 index 8d3780d..0000000 --- a/Nino_Unity/Assets/Nino/Shared/Mgr/ConstMgr.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Nino.Shared.Mgr -{ - public static class ConstMgr - { -#if UNITY_2017_1_OR_NEWER - /// - /// Asset path - /// - public static string AssetPath => UnityEngine.Application.dataPath; - - /// - /// Whether or not enable native deflate (no gc compress/decompress) - /// - public static bool EnableNativeDeflate - { - get => true; - set - { - //ignore - } - } -#else - /// - /// Asset path - /// - public static string AssetPath => System.IO.Directory.GetCurrentDirectory(); - - /// - /// Whether or not enable native deflate (no gc compress/decompress) - /// - public static bool EnableNativeDeflate = false; -#endif - /// - /// Whether is mono or not - /// - public static readonly bool IsMono = Type.GetType("Mono.Runtime") != null; - - /// - /// Null value - /// - public static readonly byte[] Null = Array.Empty(); - - /// - /// Empty param - /// - public static readonly object[] EmptyParam = Array.Empty(); - - #region basic types - - public static readonly Type ObjectType = typeof(object); - public static readonly Type ByteType = typeof(byte); - public static readonly Type SByteType = typeof(sbyte); - public static readonly Type ShortType = typeof(short); - public static readonly Type UShortType = typeof(ushort); - public static readonly Type IntType = typeof(int); - public static readonly Type UIntType = typeof(uint); - public static readonly Type LongType = typeof(long); - public static readonly Type ULongType = typeof(ulong); - public static readonly Type StringType = typeof(string); - public static readonly Type BoolType = typeof(bool); - public static readonly Type DecimalType = typeof(decimal); - public static readonly Type DoubleType = typeof(double); - public static readonly Type FloatType = typeof(float); - public static readonly Type CharType = typeof(char); - public static readonly Type DateTimeType = typeof(DateTime); - public static readonly Type ByteArrType = typeof(byte[]); - public static readonly Type ByteListType = typeof(List); - public static readonly Type ListDefType = typeof(List<>); - public static readonly Type DictDefType = typeof(Dictionary<,>); - public static readonly Type NullableDefType = typeof(Nullable<>); - - #endregion - - public const byte SizeOfUInt = sizeof(uint); - public const byte SizeOfInt = sizeof(int); - public const byte SizeOfUShort = sizeof(ushort); - public const byte SizeOfShort = sizeof(short); - public const byte SizeOfULong = sizeof(ulong); - public const byte SizeOfLong = sizeof(long); - public const byte SizeOfDecimal = sizeof(decimal); - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Shared/Mgr/StringMgr.cs b/Nino_Unity/Assets/Nino/Shared/Mgr/StringMgr.cs deleted file mode 100644 index 60384f4..0000000 --- a/Nino_Unity/Assets/Nino/Shared/Mgr/StringMgr.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using Nino.Shared.IO; - -namespace Nino.Shared.Mgr -{ - public static class StringMgr - { - /// - /// Use Span to optimize string split - /// Useless since .net core 6.0, but useful for .net framework - /// - /// - /// - /// - public static unsafe string[] Split(this ReadOnlySpan str, char separator) - { - if (str.IsEmpty) - { - return Array.Empty(); - } - - var indexes = ObjectPool>.Request(); - var index = 0; - int i = 0; - int max = str.Length; - fixed (char* ptr = &str.GetPinnableReference()) - { - var cPtr = ptr; - while (i < max) - { - if (*cPtr++ == separator) - { - indexes[index++] = i; - } - - i++; - } - - string[] ret = new string[index + 1]; - var retSpan = ret.AsSpan(); - - int start = 0; - - for (i = 0; i < index; i++) - { - ref int end = ref indexes.Data[i]; - if(start >= max || start == end) - { - retSpan[i] = string.Empty; - } - else - { - retSpan[i] = new string(ptr, start, end - start); - } - start = end + 1; - } - - if (start < max) - { - retSpan[index] = new string(ptr, start, max - start); - } - else - { - retSpan[index] = string.Empty; - } - - ObjectPool>.Return(indexes); - return ret; - } - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Shared/Nino.Shared.asmdef b/Nino_Unity/Assets/Nino/Shared/Nino.Shared.asmdef deleted file mode 100644 index 962fe85..0000000 --- a/Nino_Unity/Assets/Nino/Shared/Nino.Shared.asmdef +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "Nino.Shared", - "references": [], - "includePlatforms": [], - "excludePlatforms": [], - "allowUnsafeCode": true, - "overrideReferences": false, - "precompiledReferences": [], - "autoReferenced": true, - "defineConstraints": [], - "versionDefines": [], - "noEngineReferences": false -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Shared/ThirdParty/System.IO.Pipelines.dll b/Nino_Unity/Assets/Nino/Shared/ThirdParty/System.IO.Pipelines.dll deleted file mode 100755 index ddb8567..0000000 Binary files a/Nino_Unity/Assets/Nino/Shared/ThirdParty/System.IO.Pipelines.dll and /dev/null differ diff --git a/Nino_Unity/Assets/Nino/Shared/ThirdParty/System.Numerics.Vectors.dll b/Nino_Unity/Assets/Nino/Shared/ThirdParty/System.Numerics.Vectors.dll deleted file mode 100755 index 0865972..0000000 Binary files a/Nino_Unity/Assets/Nino/Shared/ThirdParty/System.Numerics.Vectors.dll and /dev/null differ diff --git a/Nino_Unity/Assets/Nino/Shared/ThirdParty/System.Numerics.dll b/Nino_Unity/Assets/Nino/Shared/ThirdParty/System.Numerics.dll deleted file mode 100644 index 39c5d51..0000000 Binary files a/Nino_Unity/Assets/Nino/Shared/ThirdParty/System.Numerics.dll and /dev/null differ diff --git a/Nino_Unity/Assets/Nino/Shared/ThirdParty/System.Threading.Tasks.Extensions.dll b/Nino_Unity/Assets/Nino/Shared/ThirdParty/System.Threading.Tasks.Extensions.dll deleted file mode 100755 index e059050..0000000 Binary files a/Nino_Unity/Assets/Nino/Shared/ThirdParty/System.Threading.Tasks.Extensions.dll and /dev/null differ diff --git a/Nino_Unity/Assets/Nino/Shared/Util/Hash.cs b/Nino_Unity/Assets/Nino/Shared/Util/Hash.cs deleted file mode 100644 index b1b2569..0000000 --- a/Nino_Unity/Assets/Nino/Shared/Util/Hash.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System; - -namespace Nino.Shared.Util -{ - public static class Hash - { - /// - /// Get hash code of a string - /// - /// - /// - public static unsafe int GetStringHashCode(this string key) { - int i; - int len = key.Length; - int hash = 1315423911; - fixed (char* ptr = key) - { - for(i = 0; i < len; i++) - { - hash ^= ((hash << 5) + *(ptr + i) + (hash >> 2)); - } - - return hash; - } - } - - public static int GetTypeHashCode(this Type type) - { -#if ILRuntime - return type.GetHashCode(); -#else - //TODO a faster way to get the hash code of a type - return type.TypeHandle.Value.GetHashCode(); -#endif - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Shared/Util/PowOf2.cs b/Nino_Unity/Assets/Nino/Shared/Util/PowOf2.cs deleted file mode 100644 index 82c4622..0000000 --- a/Nino_Unity/Assets/Nino/Shared/Util/PowOf2.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; - -namespace Nino.Shared -{ - public static class PowerOf2 - { - /// - /// Get whether or not n is power of 2 - /// - /// - /// - public static bool IsPowerOf2(int n) - { - /* - * 4 -> 100 - * 3 -> 011 - * 4 & 3 -> 000 - * - * 8 -> 1000 - * 7 -> 0111 - * 8 & 7 -> 0000 - * - * 15 -> 1111 - * 14 -> 1110 - * 15 & 14 -> 1110 - */ - return (n & (n - 1)) == 0; - } - - /// - /// if n is power of 2, get its power - /// - /// - /// - public static byte GetPower(int n) - { - byte ret = 0; - while (n >> 1 != 0) - { - ret++; - n = n >> 1; - } - - return ret; - } - - /// - /// if n is not power of 2, get the next power of 2 from n - /// - /// - /// - /// - public static int RoundUpToPowerOf2(int n) - { - if (n < 0 || n > 0x40000000) - { - throw new ArgumentOutOfRangeException("n"); - } - - n = n - 1; - n = n | (n >> 1); - n = n | (n >> 2); - n = n | (n >> 4); - n = n | (n >> 8); - n = n | (n >> 16); - return n + 1; - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test5.cs b/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test5.cs deleted file mode 100644 index 1736345..0000000 --- a/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test5.cs +++ /dev/null @@ -1,248 +0,0 @@ -using System; -using System.IO; -using System.Text; -using Nino.Shared.Util; -using MongoDB.Bson.IO; -using System.Diagnostics; -using MongoDB.Bson.Serialization; - -// ReSharper disable RedundantJumpStatement - -namespace Nino.Test.Editor.Serialization -{ - public class Test5 - { - private const string SerializationTest5 = - "Nino/Test/Serialization/Test5 - Serialize and Deserialize (Nino vs MongoDB.Bson)"; - - private static string GetString(int len) - { - StringBuilder sb = new StringBuilder(); - sb.Append('a', len); - return sb.ToString(); - } - -#if UNITY_2017_1_OR_NEWER - [UnityEditor.MenuItem(SerializationTest5, priority = 5)] -#endif - public static void Main() - { - //reg - BsonClassMap.RegisterClassMap(); - BsonClassMap.RegisterClassMap(); - BsonClassMap.RegisterClassMap(); - Logger.W("1/5"); - DoTest(10); - Logger.W("2/5"); - DoTest(100); - Logger.W("3/5"); - DoTest(1000); - Logger.W("4/5"); - DoTest(10000); - Logger.W("5/5"); - DoTest(100000); - } - - private static void BeginSample(string name) - { -#if UNITY_2017_1_OR_NEWER - UnityEngine.Profiling.Profiler.BeginSample(name); -#endif - return; - } - - private static void EndSample() - { -#if UNITY_2017_1_OR_NEWER - UnityEngine.Profiling.Profiler.EndSample(); -#endif - return; - } - - private static void DoTest(int max) - { - #region Test data - - Data[] ps = new Data[max]; - for (int i = 0, cnt = max; i < cnt; i++) - { - ps[i] = new Data() - { - x = short.MaxValue, - y = byte.MaxValue, - z = short.MaxValue, - f = 1234.56789f, - d = 66.66666666m, - db = 999.999999999999, - bo = true, - en = TestEnum.A, - }; - } - - NestedData points = new NestedData() - { - name = "测试", - ps = ps - }; - - #endregion - - #region Test - - Logger.D("Serialization Test", $"testing {max} objs"); - Logger.D("Serialization Test", "======================================"); - - //Nino - var sw = new Stopwatch(); - BeginSample("Nino - Serialize"); - sw.Restart(); - int size = Nino.Serialization.Serializer.GetSize(points); - long len; - byte[] bs; - if (size <= 1024) - { - Span ret = stackalloc byte[size]; - Nino.Serialization.Serializer.Serialize(ret, points); - sw.Stop(); - EndSample(); - Logger.D("Serialization Test", $"Nino: {ret.Length} bytes in {sw.ElapsedMilliseconds}ms"); - len = ret.Length; - var tm = sw.ElapsedMilliseconds; - //Logger.D("Serialization Test",string.Join(",", bs)); - - //MongoDB.Bson - BeginSample("MongoDB.Bson - Serialize"); - byte[] bs2; - sw.Restart(); - //we want byte[], MongoDB.Bson returns stream - //to be able to make it fair, we need to convert stream to byte[] - using (MemoryStream ms = new MemoryStream()) - { - using (BsonBinaryWriter bsonWriter = new BsonBinaryWriter(ms, BsonBinaryWriterSettings.Defaults)) - { - BsonSerializationContext context = BsonSerializationContext.CreateRoot(bsonWriter); - BsonSerializationArgs args = default; - args.NominalType = typeof(object); - IBsonSerializer serializer = BsonSerializer.LookupSerializer(args.NominalType); - serializer.Serialize(context, args, points); - bs2 = ms.ToArray(); - } - } - - sw.Stop(); - EndSample(); - - Logger.D("Serialization Test", $"MongoDB.Bson: {bs2.Length} bytes in {sw.ElapsedMilliseconds}ms"); - //Logger.D("Serialization Test",string.Join(",", bs)); - - Logger.D("Serialization Test", "======================================"); - Logger.D("Serialization Test", $"size diff (nino - MongoDB.Bson): {len - bs2.Length} bytes"); - Logger.D("Serialization Test", - $"size diff pct => diff/MongoDB.Bson : {((len - bs2.Length) * 100f / bs2.Length):F2}%"); - - Logger.D("Serialization Test", "======================================"); - Logger.D("Serialization Test", $"time diff (nino - MongoDB.Bson): {tm - sw.ElapsedMilliseconds} ms"); - Logger.D("Serialization Test", - $"time diff pct => time/MongoDB.Bson : {((tm - sw.ElapsedMilliseconds) * 100f / sw.ElapsedMilliseconds):F2}%"); - - BeginSample("Nino - Deserialize"); - sw.Restart(); - var d = Nino.Serialization.Deserializer.Deserialize(ret); - sw.Stop(); - EndSample(); - Logger.D("Deserialization Test", d); - Logger.D("Deserialization Test", - $"Nino: extracted {len} bytes and deserialized {points.ps.Length} entries in {sw.ElapsedMilliseconds}ms"); - tm = sw.ElapsedMilliseconds; - - //MongoDB.Bson - BeginSample("MongoDB.Bson - Deserialize"); - sw.Restart(); - d = (NestedData)BsonSerializer.Deserialize(bs2, typeof(NestedData)); - sw.Stop(); - EndSample(); - Logger.D("Deserialization Test", d); - Logger.D("Deserialization Test", - $"MongoDB.Bson: extracted {bs2.Length} bytes and deserialized {points.ps.Length} entries in {sw.ElapsedMilliseconds}ms"); - - Logger.D("Deserialization Test", "======================================"); - Logger.D("Deserialization Test", $"time diff (nino - MongoDB.Bson): {tm - sw.ElapsedMilliseconds} ms"); - Logger.D("Deserialization Test", - $"time diff pct => time/MongoDB.Bson : {((tm - sw.ElapsedMilliseconds) * 100f / sw.ElapsedMilliseconds):F2}%"); - } - else - { - byte[] ret = new byte[size]; - Nino.Serialization.Serializer.Serialize(ret, points); - sw.Stop(); - EndSample(); - Logger.D("Serialization Test", $"Nino: {ret.Length} bytes in {sw.ElapsedMilliseconds}ms"); - len = ret.Length; - var tm = sw.ElapsedMilliseconds; - //Logger.D("Serialization Test",string.Join(",", bs)); - - //MongoDB.Bson - BeginSample("MongoDB.Bson - Serialize"); - byte[] bs2; - sw.Restart(); - //we want byte[], MongoDB.Bson returns stream - //to be able to make it fair, we need to convert stream to byte[] - using (MemoryStream ms = new MemoryStream()) - { - using (BsonBinaryWriter bsonWriter = new BsonBinaryWriter(ms, BsonBinaryWriterSettings.Defaults)) - { - BsonSerializationContext context = BsonSerializationContext.CreateRoot(bsonWriter); - BsonSerializationArgs args = default; - args.NominalType = typeof(object); - IBsonSerializer serializer = BsonSerializer.LookupSerializer(args.NominalType); - serializer.Serialize(context, args, points); - bs2 = ms.ToArray(); - } - } - - sw.Stop(); - EndSample(); - - Logger.D("Serialization Test", $"MongoDB.Bson: {bs2.Length} bytes in {sw.ElapsedMilliseconds}ms"); - //Logger.D("Serialization Test",string.Join(",", bs)); - - Logger.D("Serialization Test", "======================================"); - Logger.D("Serialization Test", $"size diff (nino - MongoDB.Bson): {len - bs2.Length} bytes"); - Logger.D("Serialization Test", - $"size diff pct => diff/MongoDB.Bson : {((len - bs2.Length) * 100f / bs2.Length):F2}%"); - - Logger.D("Serialization Test", "======================================"); - Logger.D("Serialization Test", $"time diff (nino - MongoDB.Bson): {tm - sw.ElapsedMilliseconds} ms"); - Logger.D("Serialization Test", - $"time diff pct => time/MongoDB.Bson : {((tm - sw.ElapsedMilliseconds) * 100f / sw.ElapsedMilliseconds):F2}%"); - - BeginSample("Nino - Deserialize"); - sw.Restart(); - var d = Nino.Serialization.Deserializer.Deserialize(ret); - sw.Stop(); - EndSample(); - Logger.D("Deserialization Test", d); - Logger.D("Deserialization Test", - $"Nino: extracted {ret.Length} bytes and deserialized {points.ps.Length} entries in {sw.ElapsedMilliseconds}ms"); - tm = sw.ElapsedMilliseconds; - - //MongoDB.Bson - BeginSample("MongoDB.Bson - Deserialize"); - sw.Restart(); - d = (NestedData)BsonSerializer.Deserialize(bs2, typeof(NestedData)); - sw.Stop(); - EndSample(); - Logger.D("Deserialization Test", d); - Logger.D("Deserialization Test", - $"MongoDB.Bson: extracted {bs2.Length} bytes and deserialized {points.ps.Length} entries in {sw.ElapsedMilliseconds}ms"); - - Logger.D("Deserialization Test", "======================================"); - Logger.D("Deserialization Test", $"time diff (nino - MongoDB.Bson): {tm - sw.ElapsedMilliseconds} ms"); - Logger.D("Deserialization Test", - $"time diff pct => time/MongoDB.Bson : {((tm - sw.ElapsedMilliseconds) * 100f / sw.ElapsedMilliseconds):F2}%"); - } - - #endregion - } - } -} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test9.cs b/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test9.cs deleted file mode 100644 index 40986fd..0000000 --- a/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test9.cs +++ /dev/null @@ -1,59 +0,0 @@ -using Nino.Shared.Util; -using Nino.Serialization; -using System.Collections.Generic; -using System.Linq; - -// ReSharper disable RedundantTypeArgumentsOfMethod -namespace Nino.Test.Editor.Serialization -{ - public class Test9 - { - private const string SerializationTest9 = "Nino/Test/Serialization/Test9 - Basic Types"; - -#if UNITY_2017_1_OR_NEWER - [UnityEditor.MenuItem(SerializationTest9,priority=9)] -#endif - public static void Main() - { - int a = int.MaxValue; - uint b = uint.MaxValue; - long c = long.MaxValue; - ulong d = ulong.MaxValue; - float e = float.MaxValue; - double f = double.MaxValue; - decimal g = decimal.MaxValue; - string h = "Hello World"; - bool i = true; - char j = 'a'; - byte k = byte.MaxValue; - sbyte l = sbyte.MaxValue; - ushort m = ushort.MaxValue; - short n = short.MaxValue; - int[] o = new int[]{ 1, 2, 3, 4, 5 }; - List p = new List() { 1, 2, 3, 4, 5 }; - Dictionary q = new Dictionary() - { { "a", 1 }, { "b", 2 }, { "c", 3 }, { "d", 4 }, { "e", 5 } }; - - Logger.D($"Serialized a as: {(Serializer.Serialize(((a))).Length)} bytes: {(string.Join(",",Serializer.Serialize(((a)))))}, deserialized as:{Deserializer.Deserialize(Serializer.Serialize(a))}"); - Logger.D($"Serialized b as: {(Serializer.Serialize(((b))).Length)} bytes: {(string.Join(",",Serializer.Serialize(((b)))))}, deserialized as:{Deserializer.Deserialize(Serializer.Serialize(b))}"); - Logger.D($"Serialized c as: {(Serializer.Serialize(((c))).Length)} bytes: {(string.Join(",",Serializer.Serialize(((c)))))}, deserialized as:{Deserializer.Deserialize(Serializer.Serialize(c))}"); - Logger.D($"Serialized d as: {(Serializer.Serialize(((d))).Length)} bytes: {(string.Join(",",Serializer.Serialize(((d)))))}, deserialized as:{Deserializer.Deserialize(Serializer.Serialize(d))}"); - Logger.D($"Serialized e as: {(Serializer.Serialize(((e))).Length)} bytes: {(string.Join(",",Serializer.Serialize(((e)))))}, deserialized as:{Deserializer.Deserialize(Serializer.Serialize(e))}"); - Logger.D($"Serialized f as: {(Serializer.Serialize(((f))).Length)} bytes: {(string.Join(",",Serializer.Serialize(((f)))))}, deserialized as:{Deserializer.Deserialize(Serializer.Serialize(f))}"); - Logger.D($"Serialized g as: {(Serializer.Serialize(((g))).Length)} bytes: {(string.Join(",",Serializer.Serialize(((g)))))}, deserialized as:{Deserializer.Deserialize(Serializer.Serialize(g))}"); - Logger.D($"Serialized h as: {(Serializer.Serialize(((h))).Length)} bytes: {(string.Join(",",Serializer.Serialize(((h)))))}, deserialized as:{Deserializer.Deserialize(Serializer.Serialize(h))}"); - Logger.D($"Serialized i as: {(Serializer.Serialize(((i))).Length)} bytes: {(string.Join(",",Serializer.Serialize(((i)))))}, deserialized as:{Deserializer.Deserialize(Serializer.Serialize(i))}"); - Logger.D($"Serialized j as: {(Serializer.Serialize(((j))).Length)} bytes: {(string.Join(",",Serializer.Serialize(((j)))))}, deserialized as:{Deserializer.Deserialize(Serializer.Serialize(j))}"); - Logger.D($"Serialized k as: {(Serializer.Serialize(((k))).Length)} bytes: {(string.Join(",",Serializer.Serialize(((k)))))}, deserialized as:{Deserializer.Deserialize(Serializer.Serialize(k))}"); - Logger.D($"Serialized l as: {(Serializer.Serialize(((l))).Length)} bytes: {(string.Join(",",Serializer.Serialize(((l)))))}, deserialized as:{Deserializer.Deserialize(Serializer.Serialize(l))}"); - Logger.D($"Serialized m as: {(Serializer.Serialize(((m))).Length)} bytes: {(string.Join(",",Serializer.Serialize(((m)))))}, deserialized as:{Deserializer.Deserialize(Serializer.Serialize(m))}"); - Logger.D($"Serialized n as: {(Serializer.Serialize(((n))).Length)} bytes: {(string.Join(",",Serializer.Serialize(((n)))))}, deserialized as:{Deserializer.Deserialize(Serializer.Serialize(n))}"); - Logger.D($"Serialized o as: {(Serializer.Serialize(((o))).Length)} bytes: {(string.Join(",",Serializer.Serialize(((o)))))}, deserialized as:{Deserializer.Deserialize(Serializer.Serialize(o))}"); - Logger.D($"Serialized p as: {(Serializer.Serialize(((p))).Length)} bytes: {(string.Join(",",Serializer.Serialize(((p)))))}, deserialized as:{string.Join(",",Deserializer.Deserialize>(Serializer.Serialize(p)))}"); - Logger.D( - $"Serialized q as: {(Serializer.Serialize(((q))).Length)} bytes: {(string.Join(",", Serializer.Serialize(((q)))))}, " + - $"deserialized as:{string.Join(",", Deserializer.Deserialize>(Serializer.Serialize(q)).ToList().SelectMany(kvp => $"{kvp.Key}-{kvp.Value}"))}"); - } - } -} -// ReSharper restore RedundantTypeArgumentsOfMethod \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Test/BuildTest.cs b/Nino_Unity/Assets/Test/BuildTest.cs similarity index 56% rename from Nino_Unity/Assets/Nino/Test/BuildTest.cs rename to Nino_Unity/Assets/Test/BuildTest.cs index ed13cd1..ef6d25e 100644 --- a/Nino_Unity/Assets/Nino/Test/BuildTest.cs +++ b/Nino_Unity/Assets/Test/BuildTest.cs @@ -1,5 +1,4 @@ using System; -using System.Buffers; using System.IO; using System.Linq; using UnityEngine; @@ -12,11 +11,12 @@ using MongoDB.Bson.Serialization; using UnityEngine.SceneManagement; using System.Runtime.Serialization.Formatters.Binary; -using Logger = Nino.Shared.Util.Logger; +using Test_Nino; +using Debug = UnityEngine.Debug; namespace Nino.Test { - public class BuildTest: MonoBehaviour + public class BuildTest : MonoBehaviour { public Text ninoResultText; public Text pbNetResultText; @@ -34,10 +34,8 @@ public class BuildTest: MonoBehaviour private byte[] ninoBuffer = Array.Empty(); private byte[] pbNetBuffer = Array.Empty(); private byte[] binaryFormatterBuffer1 = Array.Empty(); - private byte[] binaryFormatterBuffer2 = Array.Empty(); private byte[] bsonBuffer = Array.Empty(); private byte[] msgPackBuffer = Array.Empty(); - private BuildTestDataNoCodeGen d1; private BuildTestDataCodeGen d2; private void OnGUI() @@ -104,68 +102,16 @@ private void Awake() }, v = new Dictionary() { - { new NotIncludeAllClass() { a = 30, b = 20, c = 12938, d = 19283 }, new NotIncludeAllClass() { a = 30, b = 20, c = 12938, d = 19283 } } - } - }; - d1 = new BuildTestDataNoCodeGen() - { - a = 1, - b = 2, - c = 100, - d = 500, - e = 666, - f = 99999999, - g = 123456788765, - h = 123456321, - i = 6.6f, - j = 9.9, - k = 1.23456789012345m, - l = true, - m = 'a', - n = "aksjdfhgheuwi", - o = new List() { 1, 2, 3, 4, 5 }, - p = new List() - { - new NotIncludeAllClass() - { - a = 30, b = 20, c = 12938, d = 19283 - } - }, - q = new byte[] { 1, 2, 3 }, - r = new NotIncludeAllClass[] - { - new NotIncludeAllClass() { - a = 30, b = 20, c = 12938, d = 19283 + new NotIncludeAllClass() { a = 30, b = 20, c = 12938, d = 19283 }, + new NotIncludeAllClass() { a = 30, b = 20, c = 12938, d = 19283 } } - }, - s = new Dictionary() - { - { - "ks", new NotIncludeAllClass() - { - a = 30, b = 20, c = 12938, d = 19283 - } - } - }, - t = new Dictionary() - { - { new NotIncludeAllClass() { a = 30, b = 20, c = 12938, d = 19283 }, 39 } - }, - u = new Dictionary() - { - { "usd", 7 } - }, - v = new Dictionary() - { - { new NotIncludeAllClass() { a = 30, b = 20, c = 12938, d = 19283 }, new NotIncludeAllClass() { a = 30, b = 20, c = 12938, d = 19283 } } } }; //reg try { BsonClassMap.RegisterClassMap(); - BsonClassMap.RegisterClassMap(); BsonClassMap.RegisterClassMap(); StaticCompositeResolver.Instance.Register( GeneratedResolver.Instance, @@ -200,53 +146,32 @@ private void Start() { sw.Reset(); sw.Start(); - var dd1 = Nino.Serialization.Deserializer.Deserialize(ninoBuffer); + Deserializer.Deserialize(ninoBuffer, out BuildTestDataCodeGen dd1); sw.Stop(); var m1 = sw.ElapsedTicks; sw.Reset(); - sw.Start(); - //as everything are same, buffer can be shared across two classes - var dd2 = Nino.Serialization.Deserializer.Deserialize(ninoBuffer); - sw.Stop(); - var m2 = sw.ElapsedTicks; - ninoBuffer = Array.Empty(); ninoResultText.text = - $"Deserialized BuildTestDataCodeGen in {((float)m1 / Stopwatch.Frequency) * 1000} ms: \n{dd1}\n" + - $"Deserialized BuildTestDataNoCodeGen in {((float)m2 / Stopwatch.Frequency) * 1000} ms:\n{dd2}"; + $"Deserialized BuildTestDataCodeGen in {((float)m1 / Stopwatch.Frequency) * 1000} ms: \n{dd1}"; ninoBtn.GetComponentInChildren().text = "NinoSerialize"; + ninoBuffer = Array.Empty(); } //serialize else { - if(ninoBuffer.Length == 0) - { - ninoBuffer = new byte[Nino.Serialization.Serializer.GetSize(d2)]; - } sw.Reset(); sw.Start(); - Span arr = stackalloc byte[Nino.Serialization.Serializer.GetSize(d2)]; - Nino.Serialization.Serializer.Serialize(arr, d2); + ninoBuffer = d2.Serialize(); sw.Stop(); - arr.CopyTo(ninoBuffer); var m1 = sw.ElapsedTicks; - sw.Reset(); - sw.Start(); - //as everything are same, buffer has same length - arr = stackalloc byte[Nino.Serialization.Serializer.GetSize(d1)]; - Nino.Serialization.Serializer.Serialize(arr, d1); - sw.Stop(); - arr.CopyTo(ninoBuffer); - var m2 = sw.ElapsedTicks; ninoResultText.text = - $"Serialized BuildTestDataCodeGen as {ninoBuffer.Length} bytes in {((float)m1 / Stopwatch.Frequency) * 1000} ms,\n" + - $"Serialized BuildTestDataNoCodeGen as {ninoBuffer.Length} bytes in {((float)m2 / Stopwatch.Frequency) * 1000} ms:\n{string.Join(",", ninoBuffer)}"; + $"Serialized BuildTestDataCodeGen as {ninoBuffer.Length} bytes in {((float)m1 / Stopwatch.Frequency) * 1000} ms\n{string.Join(",", ninoBuffer)}"; ninoBtn.GetComponentInChildren().text = "NinoDeserialize"; } } catch (Exception ex) { ninoResultText.text = ex.ToString(); - Logger.D(ex); + Debug.LogException(ex); } }); pbNetBtn.onClick.AddListener(() => @@ -256,7 +181,6 @@ private void Start() //deserialize if (pbNetBuffer.Length > 0) { - BuildTestDataNoCodeGen dd1; BuildTestDataCodeGen dd2; sw.Reset(); sw.Start(); @@ -267,22 +191,11 @@ private void Start() sw.Stop(); var m1 = sw.ElapsedTicks; - sw.Reset(); - sw.Start(); - //as everything are same, buffer can be shared across two classes - using (MemoryStream ms = new MemoryStream(pbNetBuffer)) - { - dd1 = ProtoBuf.Serializer.Deserialize(ms); - } - sw.Stop(); - sw.Stop(); - var m2 = sw.ElapsedTicks; - pbNetBuffer = Array.Empty(); pbNetResultText.text = - $"Deserialized BuildTestDataCodeGen (no code gen for this class for pbnet) in {((float)m1 / Stopwatch.Frequency) * 1000} ms: \n{dd2}\n" + - $"Deserialized BuildTestDataNoCodeGen in {((float)m2 / Stopwatch.Frequency) * 1000} ms:\n{dd1}"; + $"Deserialized BuildTestDataCodeGen (no code gen for this class for pbnet) in {((float)m1 / Stopwatch.Frequency) * 1000} ms: \n{dd2}"; pbNetBtn.GetComponentInChildren().text = "PbNetSerialize"; + pbNetBuffer = Array.Empty(); } //serialize else @@ -291,33 +204,22 @@ private void Start() sw.Start(); using (MemoryStream ms = new MemoryStream()) { - ProtoBuf.Serializer.Serialize(ms, d2); + ProtoBuf.Serializer.Serialize(ms, d2); pbNetBuffer = ms.ToArray(); } sw.Stop(); var m1 = sw.ElapsedTicks; - sw.Reset(); - sw.Start(); - //as everything are same, buffer has same length - using (MemoryStream ms = new MemoryStream()) - { - ProtoBuf.Serializer.Serialize(ms, d1); - pbNetBuffer = ms.ToArray(); - } - sw.Stop(); - var m2 = sw.ElapsedTicks; pbNetResultText.text = - $"Serialized BuildTestDataCodeGen (no code gen for this class for pbnet) as {pbNetBuffer.Length} bytes in {((float)m1 / Stopwatch.Frequency) * 1000} ms,\n" + - $"Serialized BuildTestDataNoCodeGen as {pbNetBuffer.Length} bytes in {((float)m2 / Stopwatch.Frequency) * 1000} ms:\n{string.Join(",", pbNetBuffer.Take(300))}"; + $"Serialized BuildTestDataCodeGen (no code gen for this class for pbnet) as {pbNetBuffer.Length} bytes in {((float)m1 / Stopwatch.Frequency) * 1000} ms:\n{string.Join(",", pbNetBuffer.Take(300))}"; pbNetBtn.GetComponentInChildren().text = "PbNetDeserialize"; } } - catch(Exception ex) + catch (Exception ex) { pbNetResultText.text = ex.ToString(); - Logger.D(ex); + Debug.LogException(ex); } }); binaryFormatterBtn.onClick.AddListener(() => @@ -327,7 +229,6 @@ private void Start() //deserialize if (binaryFormatterBuffer1.Length > 0) { - BuildTestDataNoCodeGen dd1; BuildTestDataCodeGen dd2; sw.Reset(); sw.Start(); @@ -339,23 +240,10 @@ private void Start() sw.Stop(); var m1 = sw.ElapsedTicks; - sw.Reset(); - sw.Start(); - //as everything are same, buffer can be shared across two classes - using (var ms = new MemoryStream(binaryFormatterBuffer2)) - { - BinaryFormatter bFormatter = new BinaryFormatter(); - dd1 = (BuildTestDataNoCodeGen)bFormatter.Deserialize(ms); - } - - sw.Stop(); - var m2 = sw.ElapsedTicks; - binaryFormatterBuffer1 = Array.Empty(); - binaryFormatterBuffer2 = Array.Empty(); binaryFormatterResultText.text = - $"Deserialized BuildTestDataCodeGen in {((float)m1 / Stopwatch.Frequency) * 1000} ms: \n{dd2}\n" + - $"Deserialized BuildTestDataNoCodeGen in {((float)m2 / Stopwatch.Frequency) * 1000} ms:\n{dd1}"; + $"Deserialized BuildTestDataCodeGen in {((float)m1 / Stopwatch.Frequency) * 1000} ms: \n{dd2}"; binaryFormatterBtn.GetComponentInChildren().text = "BinaryFormatterSerialize"; + binaryFormatterBuffer1 = Array.Empty(); } //serialize else @@ -371,20 +259,8 @@ private void Start() sw.Stop(); var m1 = sw.ElapsedTicks; - sw.Reset(); - sw.Start(); - using (var ms = new MemoryStream()) - { - BinaryFormatter bFormatter = new BinaryFormatter(); - bFormatter.Serialize(ms, d1); - binaryFormatterBuffer2 = ms.ToArray(); - } - - sw.Stop(); - var m2 = sw.ElapsedTicks; binaryFormatterResultText.text = - $"Serialized BuildTestDataCodeGen (no code gen for this class for bf) as {binaryFormatterBuffer1.Length} bytes in {((float)m1 / Stopwatch.Frequency) * 1000} ms,\n" + - $"Serialized BuildTestDataNoCodeGen as {binaryFormatterBuffer2.Length} bytes in {((float)m2 / Stopwatch.Frequency) * 1000} ms:\n" + + $"Serialized BuildTestDataCodeGen (no code gen for this class for bf) as {binaryFormatterBuffer1.Length} bytes in {((float)m1 / Stopwatch.Frequency) * 1000} ms:\n" + $"{string.Join(",", binaryFormatterBuffer1.Length > 300 ? binaryFormatterBuffer1.Take(300) : binaryFormatterBuffer1)}"; binaryFormatterBtn.GetComponentInChildren().text = "BinaryFormatterDeserialize"; } @@ -392,7 +268,7 @@ private void Start() catch (Exception ex) { binaryFormatterResultText.text = ex.ToString(); - Logger.D(ex); + Debug.LogException(ex); } }); bsonBtn.onClick.AddListener(() => @@ -402,7 +278,6 @@ private void Start() //deserialize if (bsonBuffer.Length > 0) { - BuildTestDataNoCodeGen dd1; BuildTestDataCodeGen dd2; sw.Reset(); sw.Start(); @@ -411,19 +286,10 @@ private void Start() sw.Stop(); var m1 = sw.ElapsedTicks; - sw.Reset(); - sw.Start(); - //as everything are same, buffer can be shared across two classes - dd1 = (BuildTestDataNoCodeGen)BsonSerializer.Deserialize(bsonBuffer, - typeof(BuildTestDataNoCodeGen)); - - sw.Stop(); - var m2 = sw.ElapsedTicks; - bsonBuffer = Array.Empty(); bsonResultText.text = - $"Deserialized BuildTestDataCodeGen (no code gen for this class for bson) in {((float)m1 / Stopwatch.Frequency) * 1000} ms: \n{dd1}\n" + - $"Deserialized BuildTestDataNoCodeGen in {((float)m2 / Stopwatch.Frequency) * 1000} ms:\n{dd2}"; + $"Deserialized BuildTestDataCodeGen (no code gen for this class for bson) in {((float)m1 / Stopwatch.Frequency) * 1000} ms: \n{dd2}\n"; bsonBtn.GetComponentInChildren().text = "BsonSerialize"; + bsonBuffer = Array.Empty(); } //serialize else @@ -433,7 +299,7 @@ private void Start() using (MemoryStream ms = new MemoryStream()) { using (BsonBinaryWriter bsonWriter = - new BsonBinaryWriter(ms, BsonBinaryWriterSettings.Defaults)) + new BsonBinaryWriter(ms, BsonBinaryWriterSettings.Defaults)) { BsonSerializationContext context = BsonSerializationContext.CreateRoot(bsonWriter); BsonSerializationArgs args = default; @@ -446,35 +312,15 @@ private void Start() sw.Stop(); var m1 = sw.ElapsedTicks; - sw.Reset(); - sw.Start(); - //as everything are same, buffer has same length - using (MemoryStream ms = new MemoryStream()) - { - using (BsonBinaryWriter bsonWriter = - new BsonBinaryWriter(ms, BsonBinaryWriterSettings.Defaults)) - { - BsonSerializationContext context = BsonSerializationContext.CreateRoot(bsonWriter); - BsonSerializationArgs args = default; - args.NominalType = typeof(object); - IBsonSerializer serializer = BsonSerializer.LookupSerializer(args.NominalType); - serializer.Serialize(context, args, d1); - bsonBuffer = ms.ToArray(); - } - } - - sw.Stop(); - var m2 = sw.ElapsedTicks; bsonResultText.text = - $"Serialized BuildTestDataCodeGen (no code gen for this class for bson) as {bsonBuffer.Length} bytes in {((float)m1 / Stopwatch.Frequency) * 1000} ms,\n" + - $"Serialized BuildTestDataNoCodeGen as {bsonBuffer.Length} bytes in {((float)m2 / Stopwatch.Frequency) * 1000} ms:\n{string.Join(",", bsonBuffer)}"; + $"Serialized BuildTestDataCodeGen (no code gen for this class for bson) as {bsonBuffer.Length} bytes in {((float)m1 / Stopwatch.Frequency) * 1000} ms:\n{string.Join(",", bsonBuffer)}"; bsonBtn.GetComponentInChildren().text = "BsonDeserialize"; } } - catch(Exception ex) + catch (Exception ex) { bsonResultText.text = ex.ToString(); - Logger.D(ex); + Debug.LogException(ex); } }); msgPackBtn.onClick.AddListener(() => @@ -484,7 +330,6 @@ private void Start() //deserialize if (msgPackBuffer.Length > 0) { - BuildTestDataNoCodeGen dd1; BuildTestDataCodeGen dd2; sw.Reset(); sw.Start(); @@ -492,46 +337,31 @@ private void Start() sw.Stop(); var m1 = sw.ElapsedTicks; - sw.Reset(); - sw.Start(); - //as everything are same, buffer can be shared across two classes - dd1 = MessagePackSerializer.Deserialize(msgPackBuffer); - - sw.Stop(); - var m2 = sw.ElapsedTicks; - msgPackBuffer = Array.Empty(); msgPackResultText.text = - $"Deserialized BuildTestDataCodeGen in {((float)m1 / Stopwatch.Frequency) * 1000} ms: \n{dd1}\n" + - $"Deserialized BuildTestDataNoCodeGen (THIS CLASS HAS CODE GEN OTHERWISE WONT WORK IN IL2CPP) in {((float)m2 / Stopwatch.Frequency) * 1000} ms:\n{dd2}"; + $"Deserialized BuildTestDataCodeGen in {((float)m1 / Stopwatch.Frequency) * 1000} ms: \n{dd2}\n"; msgPackBtn.GetComponentInChildren().text = "MsgPackSerialize"; + msgPackBuffer = Array.Empty(); } //serialize else { sw.Reset(); sw.Start(); - var lz4Options = MessagePackSerializerOptions.Standard.WithCompression(MessagePackCompression.None); + var lz4Options = + MessagePackSerializerOptions.Standard.WithCompression(MessagePackCompression.None); msgPackBuffer = MessagePackSerializer.Serialize(d2, lz4Options); sw.Stop(); var m1 = sw.ElapsedTicks; - sw.Reset(); - sw.Start(); - //as everything are same, buffer has same length - msgPackBuffer = MessagePackSerializer.Serialize(d1); - - sw.Stop(); - var m2 = sw.ElapsedTicks; msgPackResultText.text = - $"Serialized BuildTestDataCodeGen as {msgPackBuffer.Length} bytes in {((float)m1 / Stopwatch.Frequency) * 1000} ms,\n" + - $"Serialized BuildTestDataCodeGen (THIS CLASS HAS CODE GEN OTHERWISE WONT WORK IN IL2CPP) as {msgPackBuffer.Length} bytes in {((float)m2 / Stopwatch.Frequency) * 1000} ms:\n{string.Join(",", msgPackBuffer)}"; + $"Serialized BuildTestDataCodeGen as {msgPackBuffer.Length} bytes in {((float)m1 / Stopwatch.Frequency) * 1000} ms:\n{string.Join(",", msgPackBuffer)}"; msgPackBtn.GetComponentInChildren().text = "MsgPackDeserialize"; } } catch (Exception ex) { msgPackResultText.text = ex.ToString(); - Logger.D(ex); + Debug.LogException(ex); } }); } diff --git a/Nino_Unity/Assets/Nino/Test/BuildTest2.cs b/Nino_Unity/Assets/Test/BuildTest2.cs similarity index 92% rename from Nino_Unity/Assets/Nino/Test/BuildTest2.cs rename to Nino_Unity/Assets/Test/BuildTest2.cs index 099e8fa..c69a06c 100644 --- a/Nino_Unity/Assets/Nino/Test/BuildTest2.cs +++ b/Nino_Unity/Assets/Test/BuildTest2.cs @@ -11,7 +11,9 @@ using MongoDB.Bson.Serialization; using UnityEngine.SceneManagement; using System.Runtime.Serialization.Formatters.Binary; -using Logger = Nino.Shared.Util.Logger; +using Test_Nino; +using Debug = UnityEngine.Debug; + namespace Nino.Test { @@ -36,7 +38,7 @@ public class BuildTest2 : MonoBehaviour private byte[] bsonBuffer = Array.Empty(); private byte[] msgPackBuffer = Array.Empty(); private NestedData nd; - + private void OnGUI() { if (GUI.Button(new Rect(Screen.width - 300, Screen.height - 100, 200, 50), "Small Object Test")) @@ -44,7 +46,7 @@ private void OnGUI() SceneManager.LoadScene(0); } } - + /// /// Prepare data /// @@ -111,7 +113,7 @@ private void Start() { sw.Reset(); sw.Start(); - var dd1 = Nino.Serialization.Deserializer.Deserialize(ninoBuffer); + Deserializer.Deserialize(ninoBuffer, out NestedData dd1); sw.Stop(); var m1 = sw.ElapsedTicks; sw.Reset(); @@ -123,17 +125,10 @@ private void Start() //serialize else { - if(ninoBuffer.Length == 0) - { - ninoBuffer = new byte[Nino.Serialization.Serializer.GetSize(nd)]; - } sw.Reset(); sw.Start(); - var arr = ArrayPool.Shared.Rent(Nino.Serialization.Serializer.GetSize(nd)); - Nino.Serialization.Serializer.Serialize(arr, nd); + ninoBuffer = nd.Serialize(); sw.Stop(); - Array.Copy(arr, ninoBuffer, ninoBuffer.Length); - ArrayPool.Shared.Return(arr); var m1 = sw.ElapsedTicks; ninoResultText.text = $"Serialized NestedData as {ninoBuffer.Length} bytes in {((float)m1 / Stopwatch.Frequency) * 1000} ms,\n{string.Join(",", ninoBuffer.Take(200))}"; @@ -143,7 +138,7 @@ private void Start() catch (Exception ex) { ninoResultText.text = ex.ToString(); - Logger.D(ex); + Debug.LogException(ex); } }); pbNetBtn.onClick.AddListener(() => @@ -190,7 +185,7 @@ private void Start() catch (Exception ex) { pbNetResultText.text = ex.ToString(); - Logger.D(ex); + Debug.LogException(ex); } }); binaryFormatterBtn.onClick.AddListener(() => @@ -239,7 +234,7 @@ private void Start() catch (Exception ex) { binaryFormatterResultText.text = ex.ToString(); - Logger.D(ex); + Debug.LogException(ex); } }); bsonBtn.onClick.AddListener(() => @@ -270,7 +265,7 @@ private void Start() using (MemoryStream ms = new MemoryStream()) { using (BsonBinaryWriter bsonWriter = - new BsonBinaryWriter(ms, BsonBinaryWriterSettings.Defaults)) + new BsonBinaryWriter(ms, BsonBinaryWriterSettings.Defaults)) { BsonSerializationContext context = BsonSerializationContext.CreateRoot(bsonWriter); BsonSerializationArgs args = default; @@ -291,7 +286,7 @@ private void Start() catch (Exception ex) { bsonResultText.text = ex.ToString(); - Logger.D(ex); + Debug.LogException(ex); } }); msgPackBtn.onClick.AddListener(() => @@ -319,8 +314,9 @@ private void Start() { sw.Reset(); sw.Start(); - - var lz4Options = MessagePackSerializerOptions.Standard.WithCompression(MessagePackCompression.None); + + var lz4Options = + MessagePackSerializerOptions.Standard.WithCompression(MessagePackCompression.None); msgPackBuffer = MessagePackSerializer.Serialize(nd, lz4Options); sw.Stop(); @@ -333,7 +329,7 @@ private void Start() catch (Exception ex) { msgPackResultText.text = ex.ToString(); - Logger.D(ex); + Debug.LogException(ex); } }); } diff --git a/Nino_Unity/Assets/Nino/Test/Data.cs b/Nino_Unity/Assets/Test/Data.cs similarity index 66% rename from Nino_Unity/Assets/Nino/Test/Data.cs rename to Nino_Unity/Assets/Test/Data.cs index 706c9da..b7fe7d0 100644 --- a/Nino_Unity/Assets/Nino/Test/Data.cs +++ b/Nino_Unity/Assets/Test/Data.cs @@ -3,15 +3,15 @@ using System.Linq; using UnityEngine; using MessagePack; -using Nino.Serialization; using System.Collections.Generic; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.Options; +using Nino.Core; namespace Nino.Test { - [NinoSerialize()] - public partial class CollectionTest + [NinoType()] + public class CollectionTest { [NinoMember(0)] public List a = new List(); [NinoMember(1)] public List b = new List(); @@ -20,8 +20,8 @@ public partial class CollectionTest [NinoMember(4)] public Dictionary e = new Dictionary(); } - [NinoSerialize] - public partial class ComplexData + [NinoType] + public class ComplexData { [NinoMember(0)] public int[][] a; @@ -67,9 +67,9 @@ private string GetDictString(Dictionary> ddd) [Serializable] [ProtoContract] - [NinoSerialize] + [NinoType] [MessagePackObject] - public partial struct Data + public struct Data { [ProtoMember(1)] [NinoMember(1)] [BsonElement] [Key(1)] public int x; @@ -111,9 +111,9 @@ public enum TestEnum : byte [Serializable] [ProtoContract] - [NinoSerialize] + [NinoType] [MessagePackObject] - public partial class NestedData + public class NestedData { [ProtoMember(1)] [NinoMember(1)] [BsonElement] [Key(1)] public string name; @@ -129,8 +129,8 @@ public override string ToString() [Serializable] [ProtoContract] - [NinoSerialize] - public partial class NestedData2 + [NinoType] + public class NestedData2 { [ProtoMember(1)] [NinoMember(1)] public string name; @@ -144,8 +144,8 @@ public override string ToString() } } - [NinoSerialize(false)] - public partial class CustomTypeTest + [NinoType(false)] + public class PrimitiveTypeTest { [NinoMember(1)] public Vector3 v3; @@ -170,23 +170,8 @@ public override string ToString() } } - [NinoSerialize(true)] - [CodeGenIgnore] - public partial class IncludeAllClass - { - public int a; - public long b; - public float c; - public double d; - - public override string ToString() - { - return $"{a}, {b}, {c}, {d}"; - } - } - - [NinoSerialize(true)] - public partial class IncludeAllClassCodeGen + [NinoType] + public class IncludeAllClassCodeGen { public int a; public long b; @@ -201,9 +186,9 @@ public override string ToString() [Serializable] [ProtoContract] - [NinoSerialize] + [NinoType] [MessagePackObject] - public partial class NotIncludeAllClass + public class NotIncludeAllClass { [ProtoMember(10)] [BsonElement] [Key(0)] [NinoMember(0)] public int a; @@ -225,122 +210,9 @@ public override string ToString() [Serializable] [ProtoContract] - [CodeGenIgnore] - [NinoSerialize] - [MessagePackObject] - public partial class BuildTestDataNoCodeGen - { - [ProtoMember(100)] [BsonElement] [Key(0)] [NinoMember(0)] - public byte a; - - [ProtoMember(1)] [BsonElement] [Key(1)] [NinoMember(1)] - public sbyte b; - - [ProtoMember(2)] [BsonElement] [Key(2)] [NinoMember(2)] - public short c; - - [ProtoMember(3)] [BsonElement] [Key(3)] [NinoMember(3)] - public ushort d; - - [ProtoMember(4)] [BsonElement] [Key(4)] [NinoMember(4)] - public int e; - - [ProtoMember(5)] [BsonElement] [Key(5)] [NinoMember(5)] - public uint f; - - [ProtoMember(6)] [BsonElement] [Key(6)] [NinoMember(6)] - public long g; - - [ProtoMember(7)] [BsonElement] [Key(7)] [NinoMember(7)] - public ulong h; - - [ProtoMember(8)] [BsonElement] [Key(8)] [NinoMember(8)] - public float i; - - [ProtoMember(9)] [BsonElement] [Key(9)] [NinoMember(9)] - public double j; - - [ProtoMember(10)] [BsonElement] [Key(10)] [NinoMember(10)] - public decimal k; - - [ProtoMember(11)] [BsonElement] [Key(11)] [NinoMember(11)] - public bool l; - - [ProtoMember(12)] [BsonElement] [Key(12)] [NinoMember(12)] - public char m; - - [ProtoMember(13)] [BsonElement] [Key(13)] [NinoMember(13)] - public string n; - - [ProtoMember(14)] [BsonElement] [Key(14)] [NinoMember(14)] - public List o = new List(); - - [ProtoMember(15)] [BsonElement] [Key(15)] [NinoMember(15)] - public List p = new List(); - - [ProtoMember(16)] [BsonElement] [Key(16)] [NinoMember(16)] - public byte[] q = Array.Empty(); - - [ProtoMember(17)] [BsonElement] [Key(17)] [NinoMember(17)] - public NotIncludeAllClass[] r = Array.Empty(); - - [Key(18)] - [NinoMember(18)] - -#if !IL2CPP || UNITY_EDITOR - [ProtoMember(18)] - [BsonElement] - [BsonDictionaryOptions(DictionaryRepresentation.ArrayOfArrays)] -#endif - public Dictionary s = new Dictionary(); - - [Key(19)] - [NinoMember(19)] - -#if !IL2CPP || UNITY_EDITOR - [ProtoMember(19)] - [BsonElement] - [BsonDictionaryOptions(DictionaryRepresentation.ArrayOfArrays)] -#endif - public Dictionary t = new Dictionary(); - - [Key(20)] - [NinoMember(20)] - -#if !IL2CPP || UNITY_EDITOR - [ProtoMember(20)] - [BsonElement] - [BsonDictionaryOptions(DictionaryRepresentation.ArrayOfArrays)] -#endif - public Dictionary u = new Dictionary(); - - [Key(21)] - [NinoMember(21)] - -#if !IL2CPP || UNITY_EDITOR - [ProtoMember(21)] - [BsonElement] - [BsonDictionaryOptions(DictionaryRepresentation.ArrayOfArrays)] -#endif - public Dictionary v = - new Dictionary(); - - public override string ToString() - { - return $"{a},{b},{c},{d},{e},{f},{g},{h},{i},{j},{k},{l},{m},{n},{string.Join("/", o)}," + - $"{string.Join("/", p)},{string.Join("/", q)},{string.Join("/", r.ToList())}," + - $"{string.Join("/", s.Keys.ToList())}-{string.Join("/", s.Values.ToList())}," + - $"{string.Join("/", t.Keys.ToList())}-{string.Join("/", t.Values.ToList())}," + - $"{string.Join("/", u.Keys.ToList())}-{string.Join("/", v.Values.ToList())}," + - $"{string.Join("/", v.Keys.ToList())}-{string.Join("/", v.Values.ToList())}"; - } - } - - [Serializable] - [ProtoContract] - [NinoSerialize] + [NinoType] [MessagePackObject] - public partial class BuildTestDataCodeGen + public class BuildTestDataCodeGen { [ProtoMember(100)] [BsonElement] [Key(0)] [NinoMember(0)] public byte a; diff --git a/Nino_Unity/Assets/Nino/Shared/Util/Logger.cs b/Nino_Unity/Assets/Test/Editor/Logger.cs similarity index 98% rename from Nino_Unity/Assets/Nino/Shared/Util/Logger.cs rename to Nino_Unity/Assets/Test/Editor/Logger.cs index 848d494..38004e7 100644 --- a/Nino_Unity/Assets/Nino/Shared/Util/Logger.cs +++ b/Nino_Unity/Assets/Test/Editor/Logger.cs @@ -1,10 +1,11 @@ #if UNITY_2017_1_OR_NEWER using UnityEngine; + #else using System; #endif -namespace Nino.Shared.Util +namespace Nino.Test.Editor { public static class Logger { diff --git a/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test1.cs b/Nino_Unity/Assets/Test/Editor/Serialization/Test1.cs similarity index 81% rename from Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test1.cs rename to Nino_Unity/Assets/Test/Editor/Serialization/Test1.cs index 9f2d3eb..7494b04 100644 --- a/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test1.cs +++ b/Nino_Unity/Assets/Test/Editor/Serialization/Test1.cs @@ -1,8 +1,10 @@ using System; using System.IO; using System.Text; -using Nino.Shared.Util; using System.Diagnostics; +using Test_Nino; + + // ReSharper disable RedundantJumpStatement namespace Nino.Test.Editor.Serialization @@ -88,26 +90,11 @@ private static void DoTest(int max) var sw = new Stopwatch(); BeginSample("Nino"); sw.Restart(); - int size = Nino.Serialization.Serializer.GetSize(points); - long len; - if (size <= 1024) - { - Span ret = stackalloc byte[size]; - Nino.Serialization.Serializer.Serialize(ret, points); - sw.Stop(); - EndSample(); - Logger.D("Serialization Test", $"Nino: {ret.Length} bytes in {sw.ElapsedMilliseconds}ms"); - len = ret.Length; - } - else - { - byte[] ret = new byte[size]; - Nino.Serialization.Serializer.Serialize(ret, points); - sw.Stop(); - EndSample(); - Logger.D("Serialization Test", $"Nino: {ret.Length} bytes in {sw.ElapsedMilliseconds}ms"); - len = ret.Length; - } + var ret = points.Serialize(); + sw.Stop(); + EndSample(); + Logger.D("Serialization Test", $"Nino: {ret.Length} bytes in {sw.ElapsedMilliseconds}ms"); + var len = ret.Length; var tm = sw.ElapsedMilliseconds; //Logger.D("Serialization Test",string.Join(",", bs)); diff --git a/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test10.cs b/Nino_Unity/Assets/Test/Editor/Serialization/Test10.cs similarity index 98% rename from Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test10.cs rename to Nino_Unity/Assets/Test/Editor/Serialization/Test10.cs index 1c29e8b..972d619 100644 --- a/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test10.cs +++ b/Nino_Unity/Assets/Test/Editor/Serialization/Test10.cs @@ -1,6 +1,6 @@ -using Nino.Shared.Util; -using Nino.Serialization; using System.Collections.Generic; +using Test_Nino; + // ReSharper disable RedundantTypeArgumentsOfMethod namespace Nino.Test.Editor.Serialization @@ -226,7 +226,8 @@ public static void Main() Logger.D(data); var buf = Serializer.Serialize(data); Logger.D($"Serialized data: {buf.Length} bytes, {string.Join(",",buf)}"); - Logger.D($"Deserialized as: {Deserializer.Deserialize(buf)}"); + Deserializer.Deserialize(buf, out ComplexData result); + Logger.D($"Deserialized as: {result}"); } } } diff --git a/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test2.cs b/Nino_Unity/Assets/Test/Editor/Serialization/Test2.cs similarity index 82% rename from Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test2.cs rename to Nino_Unity/Assets/Test/Editor/Serialization/Test2.cs index 05d812e..5896ce0 100644 --- a/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test2.cs +++ b/Nino_Unity/Assets/Test/Editor/Serialization/Test2.cs @@ -1,9 +1,9 @@ -using System; using System.IO; using System.Text; -using Nino.Shared.Util; using System.Diagnostics; using System.Runtime.Serialization.Formatters.Binary; +using Test_Nino; + // ReSharper disable RedundantJumpStatement namespace Nino.Test.Editor.Serialization @@ -89,27 +89,12 @@ private static void DoTest(int max) var sw = new Stopwatch(); BeginSample("Nino"); sw.Restart(); - int size = Nino.Serialization.Serializer.GetSize(points); - long len; byte[] bs; - if (size <= 1024) - { - Span ret = stackalloc byte[size]; - Nino.Serialization.Serializer.Serialize(ret, points); - sw.Stop(); - EndSample(); - Logger.D("Serialization Test", $"Nino: {ret.Length} bytes in {sw.ElapsedMilliseconds}ms"); - len = ret.Length; - } - else - { - byte[] ret = new byte[size]; - Nino.Serialization.Serializer.Serialize(ret, points); - sw.Stop(); - EndSample(); - Logger.D("Serialization Test", $"Nino: {ret.Length} bytes in {sw.ElapsedMilliseconds}ms"); - len = ret.Length; - } + var ret = points.Serialize(); + sw.Stop(); + EndSample(); + Logger.D("Serialization Test", $"Nino: {ret.Length} bytes in {sw.ElapsedMilliseconds}ms"); + var len = ret.Length; var tm = sw.ElapsedMilliseconds; //Logger.D("Serialization Test",string.Join(",", bs)); diff --git a/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test3.cs b/Nino_Unity/Assets/Test/Editor/Serialization/Test3.cs similarity index 91% rename from Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test3.cs rename to Nino_Unity/Assets/Test/Editor/Serialization/Test3.cs index a46fdd1..2724ed4 100644 --- a/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test3.cs +++ b/Nino_Unity/Assets/Test/Editor/Serialization/Test3.cs @@ -1,8 +1,10 @@ using System.IO; using System.Text; -using Nino.Shared.Util; using System.Diagnostics; using System.Collections.Generic; +using Test_Nino; + + // ReSharper disable RedundantJumpStatement namespace Nino.Test.Editor.Serialization @@ -19,7 +21,7 @@ private static string GetString(int len) } #if UNITY_2017_1_OR_NEWER - [UnityEditor.MenuItem(SerializationTest3,priority=3)] + [UnityEditor.MenuItem(SerializationTest3, priority = 3)] #endif public static void Main() { @@ -82,14 +84,13 @@ private static void DoTest(int max) #region Test Logger.D("Deserialization Test", $"testing {max} objs"); - NestedData2 d; //Nino var sw = new Stopwatch(); - var bs = Nino.Serialization.Serializer.Serialize(points); + var bs = points.Serialize(); BeginSample("Nino"); sw.Restart(); - d = Nino.Serialization.Deserializer.Deserialize(bs); + Deserializer.Deserialize(bs, out NestedData d); sw.Stop(); EndSample(); Logger.D("Deserialization Test", d); @@ -108,7 +109,7 @@ private static void DoTest(int max) BeginSample("PB-net"); sw.Restart(); - d = ProtoBuf.Serializer.Deserialize(new MemoryStream(bs)); + d = ProtoBuf.Serializer.Deserialize(new MemoryStream(bs)); sw.Stop(); EndSample(); Logger.D("Deserialization Test", d); diff --git a/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test4.cs b/Nino_Unity/Assets/Test/Editor/Serialization/Test4.cs similarity index 95% rename from Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test4.cs rename to Nino_Unity/Assets/Test/Editor/Serialization/Test4.cs index 5b17464..d816623 100644 --- a/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test4.cs +++ b/Nino_Unity/Assets/Test/Editor/Serialization/Test4.cs @@ -1,11 +1,13 @@ using System.IO; using System.Text; -using Nino.Shared.Util; using System.Diagnostics; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; +using Test_Nino; + // ReSharper disable RedundantJumpStatement + namespace Nino.Test.Editor.Serialization { public class Test4 @@ -86,14 +88,13 @@ private static void DoTest(int max) Logger.D("Deserialization Test", $"testing {max} objs"); Logger.D("Deserialization Test", "======================================"); - NestedData2 d; //Nino var sw = new Stopwatch(); - var bs = Nino.Serialization.Serializer.Serialize(points); + var bs = points.Serialize(); BeginSample("Nino"); sw.Restart(); - d = Nino.Serialization.Deserializer.Deserialize(bs); + Deserializer.Deserialize(bs, out NestedData2 d); sw.Stop(); EndSample(); Logger.D("Deserialization Test", d); diff --git a/Nino_Unity/Assets/Test/Editor/Serialization/Test5.cs b/Nino_Unity/Assets/Test/Editor/Serialization/Test5.cs new file mode 100644 index 0000000..81559be --- /dev/null +++ b/Nino_Unity/Assets/Test/Editor/Serialization/Test5.cs @@ -0,0 +1,171 @@ +using System; +using System.IO; +using System.Text; +using MongoDB.Bson.IO; +using System.Diagnostics; +using Test_Nino; +using MongoDB.Bson.Serialization; + + +// ReSharper disable RedundantJumpStatement + +namespace Nino.Test.Editor.Serialization +{ + public class Test5 + { + private const string SerializationTest5 = + "Nino/Test/Serialization/Test5 - Serialize and Deserialize (Nino vs MongoDB.Bson)"; + + private static string GetString(int len) + { + StringBuilder sb = new StringBuilder(); + sb.Append('a', len); + return sb.ToString(); + } + +#if UNITY_2017_1_OR_NEWER + [UnityEditor.MenuItem(SerializationTest5, priority = 5)] +#endif + public static void Main() + { + //reg + BsonClassMap.RegisterClassMap(); + BsonClassMap.RegisterClassMap(); + BsonClassMap.RegisterClassMap(); + Logger.W("1/5"); + DoTest(10); + Logger.W("2/5"); + DoTest(100); + Logger.W("3/5"); + DoTest(1000); + Logger.W("4/5"); + DoTest(10000); + Logger.W("5/5"); + DoTest(100000); + } + + private static void BeginSample(string name) + { +#if UNITY_2017_1_OR_NEWER + UnityEngine.Profiling.Profiler.BeginSample(name); +#endif + return; + } + + private static void EndSample() + { +#if UNITY_2017_1_OR_NEWER + UnityEngine.Profiling.Profiler.EndSample(); +#endif + return; + } + + private static void DoTest(int max) + { + #region Test data + + Data[] ps = new Data[max]; + for (int i = 0, cnt = max; i < cnt; i++) + { + ps[i] = new Data() + { + x = short.MaxValue, + y = byte.MaxValue, + z = short.MaxValue, + f = 1234.56789f, + d = 66.66666666m, + db = 999.999999999999, + bo = true, + en = TestEnum.A, + }; + } + + NestedData points = new NestedData() + { + name = "测试", + ps = ps + }; + + #endregion + + #region Test + + Logger.D("Serialization Test", $"testing {max} objs"); + Logger.D("Serialization Test", "======================================"); + + //Nino + var sw = new Stopwatch(); + BeginSample("Nino - Serialize"); + sw.Restart(); + byte[] ret = Serializer.Serialize(points); + sw.Stop(); + EndSample(); + Logger.D("Serialization Test", $"Nino: {ret.Length} bytes in {sw.ElapsedMilliseconds}ms"); + var len = ret.Length; + var tm = sw.ElapsedMilliseconds; + //Logger.D("Serialization Test",string.Join(",", bs)); + + //MongoDB.Bson + BeginSample("MongoDB.Bson - Serialize"); + byte[] bs2; + sw.Restart(); + //we want byte[], MongoDB.Bson returns stream + //to be able to make it fair, we need to convert stream to byte[] + using (MemoryStream ms = new MemoryStream()) + { + using (BsonBinaryWriter bsonWriter = new BsonBinaryWriter(ms, BsonBinaryWriterSettings.Defaults)) + { + BsonSerializationContext context = BsonSerializationContext.CreateRoot(bsonWriter); + BsonSerializationArgs args = default; + args.NominalType = typeof(object); + IBsonSerializer serializer = BsonSerializer.LookupSerializer(args.NominalType); + serializer.Serialize(context, args, points); + bs2 = ms.ToArray(); + } + } + + sw.Stop(); + EndSample(); + + Logger.D("Serialization Test", $"MongoDB.Bson: {bs2.Length} bytes in {sw.ElapsedMilliseconds}ms"); + //Logger.D("Serialization Test",string.Join(",", bs)); + + Logger.D("Serialization Test", "======================================"); + Logger.D("Serialization Test", $"size diff (nino - MongoDB.Bson): {len - bs2.Length} bytes"); + Logger.D("Serialization Test", + $"size diff pct => diff/MongoDB.Bson : {((len - bs2.Length) * 100f / bs2.Length):F2}%"); + + Logger.D("Serialization Test", "======================================"); + Logger.D("Serialization Test", $"time diff (nino - MongoDB.Bson): {tm - sw.ElapsedMilliseconds} ms"); + Logger.D("Serialization Test", + $"time diff pct => time/MongoDB.Bson : {((tm - sw.ElapsedMilliseconds) * 100f / sw.ElapsedMilliseconds):F2}%"); + + BeginSample("Nino - Deserialize"); + sw.Restart(); + Deserializer.Deserialize(ret, out NestedData d); + sw.Stop(); + EndSample(); + Logger.D("Deserialization Test", d); + Logger.D("Deserialization Test", + $"Nino: extracted {ret.Length} bytes and deserialized {points.ps.Length} entries in {sw.ElapsedMilliseconds}ms"); + tm = sw.ElapsedMilliseconds; + + //MongoDB.Bson + BeginSample("MongoDB.Bson - Deserialize"); + sw.Restart(); + d = (NestedData)BsonSerializer.Deserialize(bs2, typeof(NestedData)); + sw.Stop(); + EndSample(); + Logger.D("Deserialization Test", d); + Logger.D("Deserialization Test", + $"MongoDB.Bson: extracted {bs2.Length} bytes and deserialized {points.ps.Length} entries in {sw.ElapsedMilliseconds}ms"); + + Logger.D("Deserialization Test", "======================================"); + Logger.D("Deserialization Test", $"time diff (nino - MongoDB.Bson): {tm - sw.ElapsedMilliseconds} ms"); + Logger.D("Deserialization Test", + $"time diff pct => time/MongoDB.Bson : {((tm - sw.ElapsedMilliseconds) * 100f / sw.ElapsedMilliseconds):F2}%"); + + #endregion + } + } +} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test6.cs b/Nino_Unity/Assets/Test/Editor/Serialization/Test6.cs similarity index 64% rename from Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test6.cs rename to Nino_Unity/Assets/Test/Editor/Serialization/Test6.cs index ee5da79..99f52ff 100644 --- a/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test6.cs +++ b/Nino_Unity/Assets/Test/Editor/Serialization/Test6.cs @@ -1,8 +1,8 @@ using System; using MessagePack; using System.Text; -using Nino.Shared.Util; using System.Diagnostics; +using Test_Nino; using MessagePack.Resolvers; // ReSharper disable RedundantJumpStatement @@ -120,74 +120,12 @@ private static void DoTest(int max) var sw = new Stopwatch(); BeginSample("Nino - Serialize"); sw.Restart(); - int size = Nino.Serialization.Serializer.GetSize(points); - long len; - byte[] bs; - if (size <= 1024) - { - Span ret = stackalloc byte[size]; - Nino.Serialization.Serializer.Serialize(ret, points); - sw.Stop(); - EndSample(); - Logger.D("Serialization Test", $"Nino: {ret.Length} bytes in {sw.ElapsedMilliseconds}ms"); - len = ret.Length; - var tm = sw.ElapsedMilliseconds; - - //MsgPack - BeginSample("MsgPack - Serialize"); - byte[] bs2; - sw.Restart(); - var lz4Options = MessagePackSerializerOptions.Standard.WithCompression(MessagePackCompression.None); - bs2 = MessagePackSerializer.Serialize(points, lz4Options); - sw.Stop(); - EndSample(); - - Logger.D("Serialization Test", $"MsgPack: {bs2.Length} bytes in {sw.ElapsedMilliseconds}ms"); - //Logger.D("Serialization Test",string.Join(",", bs)); - - Logger.D("Serialization Test", "======================================"); - Logger.D("Serialization Test", $"size diff (nino - MsgPack): {len - bs2.Length} bytes"); - Logger.D("Serialization Test", - $"size diff pct => diff/MsgPack : {((len - bs2.Length) * 100f / bs2.Length):F2}%"); - - Logger.D("Serialization Test", "======================================"); - Logger.D("Serialization Test", $"time diff (nino - MsgPack): {tm - sw.ElapsedMilliseconds} ms"); - Logger.D("Serialization Test", - $"time diff pct => time/MsgPack : {((tm - sw.ElapsedMilliseconds) * 100f / sw.ElapsedMilliseconds):F2}%"); - - BeginSample("Nino - Deserialize"); - sw.Restart(); - var d = Nino.Serialization.Deserializer.Deserialize(ret); - sw.Stop(); - EndSample(); - Logger.D("Deserialization Test", d); - Logger.D("Deserialization Test", - $"Nino: extracted {len} bytes and deserialized {points.ps.Length} entries in {sw.ElapsedMilliseconds}ms"); - tm = sw.ElapsedMilliseconds; - - //MsgPack - BeginSample("MsgPack - Deserialize"); - sw.Restart(); - d = MessagePackSerializer.Deserialize(bs2); - sw.Stop(); - EndSample(); - Logger.D("Deserialization Test", d); - Logger.D("Deserialization Test", - $"MsgPack: extracted {bs2.Length} bytes and deserialized {points.ps.Length} entries in {sw.ElapsedMilliseconds}ms"); - - Logger.D("Deserialization Test", "======================================"); - Logger.D("Deserialization Test", $"time diff (nino - MsgPack): {tm - sw.ElapsedMilliseconds} ms"); - Logger.D("Deserialization Test", - $"time diff pct => time/MsgPack : {((tm - sw.ElapsedMilliseconds) * 100f / sw.ElapsedMilliseconds):F2}%"); - } - else - { - byte[] ret = new byte[size]; - Nino.Serialization.Serializer.Serialize(ret, points); + + byte[] ret = points.Serialize(); sw.Stop(); EndSample(); Logger.D("Serialization Test", $"Nino: {ret.Length} bytes in {sw.ElapsedMilliseconds}ms"); - len = ret.Length; + var len = ret.Length; var tm = sw.ElapsedMilliseconds; //MsgPack @@ -214,7 +152,7 @@ private static void DoTest(int max) BeginSample("Nino - Deserialize"); sw.Restart(); - var d = Nino.Serialization.Deserializer.Deserialize(ret); + Deserializer.Deserialize(ret, out NestedData d); sw.Stop(); EndSample(); Logger.D("Deserialization Test", d); @@ -236,7 +174,6 @@ private static void DoTest(int max) Logger.D("Deserialization Test", $"time diff (nino - MsgPack): {tm - sw.ElapsedMilliseconds} ms"); Logger.D("Deserialization Test", $"time diff pct => time/MsgPack : {((tm - sw.ElapsedMilliseconds) * 100f / sw.ElapsedMilliseconds):F2}%"); - } //Logger.D("Serialization Test",string.Join(",", bs)); diff --git a/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test7.cs b/Nino_Unity/Assets/Test/Editor/Serialization/Test7.cs similarity index 50% rename from Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test7.cs rename to Nino_Unity/Assets/Test/Editor/Serialization/Test7.cs index 910998f..ca48aa1 100644 --- a/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test7.cs +++ b/Nino_Unity/Assets/Test/Editor/Serialization/Test7.cs @@ -1,61 +1,21 @@ -using Nino.Serialization; using System.Collections.Generic; +using Test_Nino; using UnityEngine; -using Logger = Nino.Shared.Util.Logger; // ReSharper disable RedundantTypeArgumentsOfMethod namespace Nino.Test.Editor.Serialization { - public class CustomTypeTestWrapper : NinoWrapperBase - { - public override void Serialize(CustomTypeTest val, ref Writer writer) - { - writer.Write(ref val.v3, sizeof(float) * 3); - writer.Write(ref val.m, sizeof(float) * 16); - writer.Write(val.ni); - writer.Write(val.qs); - writer.Write(val.dict); - writer.Write(val.dict2); - } - - public override CustomTypeTest Deserialize(Reader reader) - { - var ret = new CustomTypeTest(); - reader.Read(ref ret.v3, sizeof(float) * 3); - reader.Read(ref ret.m, sizeof(float) * 16); - ret.ni = reader.ReadNullable(); - ret.qs = reader.ReadList(); - ret.dict = reader.ReadDictionary(); - ret.dict2 = reader.ReadDictionary(); - return ret; - } - - public override int GetSize(CustomTypeTest val) - { - int ret = 1; - ret += sizeof(float) * 3; - ret += sizeof(float) * 16; - ret += Serializer.GetSize(val.ni); - ret += Serializer.GetSize(val.qs); - ret += Serializer.GetSize(val.dict); - ret += Serializer.GetSize(val.dict2); - return ret; - } - } - public class Test7 { - private const string SerializationTest7 = "Nino/Test/Serialization/Test7 - Custom Type Importer Exporter"; + private const string SerializationTest7 = "Nino/Test/Serialization/Test7 - Primitive Type Serialization"; #if UNITY_2017_1_OR_NEWER [UnityEditor.MenuItem(SerializationTest7, priority = 7)] #endif public static void Main() { - //register wrappers - WrapperManifest.AddWrapper(typeof(CustomTypeTest), new CustomTypeTestWrapper()); //custom type - CustomTypeTest c = new CustomTypeTest() + PrimitiveTypeTest c = new PrimitiveTypeTest() { ni = null, v3 = UnityEngine.Vector3.one, @@ -85,7 +45,7 @@ public static void Main() var bs = Serializer.Serialize(c); Logger.D($"serialized to {bs.Length} bytes: {string.Join(",", bs)}"); Logger.D("will deserialize"); - var cc = Deserializer.Deserialize(bs); + Deserializer.Deserialize(bs, out PrimitiveTypeTest cc); Logger.D($"deserialized as cc: {cc}"); } } diff --git a/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test8.cs b/Nino_Unity/Assets/Test/Editor/Serialization/Test8.cs similarity index 63% rename from Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test8.cs rename to Nino_Unity/Assets/Test/Editor/Serialization/Test8.cs index d8f156c..dde383c 100644 --- a/Nino_Unity/Assets/Nino/Test/Editor/Serialization/Test8.cs +++ b/Nino_Unity/Assets/Test/Editor/Serialization/Test8.cs @@ -1,6 +1,6 @@ -using Nino.Shared.Util; -using Nino.Serialization; using System.Diagnostics; +using Test_Nino; + // ReSharper disable RedundantTypeArgumentsOfMethod namespace Nino.Test.Editor.Serialization @@ -16,31 +16,6 @@ public static void Main() { Stopwatch sw = new Stopwatch(); - IncludeAllClass c = new IncludeAllClass() - { - a = 100, - b = 199, - c = 5.5f, - d = 1.23456 - }; - Logger.D( - "serialize an 'include all' class will make serialization " + - "and deserialization result larger and slower, it is recommended to use NinoMember Attributes"); - Logger.D($"will serialize c: {c}"); - sw.Reset(); - sw.Start(); - var bs = Serializer.Serialize(c); - sw.Stop(); - Logger.D( - $"serialized to {bs.Length} bytes in {((float)sw.ElapsedTicks / Stopwatch.Frequency) * 1000} ms: {string.Join(",", bs)}"); - - Logger.D("will deserialize"); - sw.Reset(); - sw.Start(); - var cc = Deserializer.Deserialize(bs); - sw.Stop(); - Logger.D($"deserialized as cc in {((float)sw.ElapsedTicks / Stopwatch.Frequency) * 1000} ms: {cc}"); - IncludeAllClassCodeGen codeGen = new IncludeAllClassCodeGen() { a = 100, @@ -53,14 +28,14 @@ public static void Main() Logger.D($"will serialize codeGen: {codeGen}"); sw.Reset(); sw.Start(); - bs = Serializer.Serialize(codeGen); + var bs = codeGen.Serialize(); sw.Stop(); Logger.D($"serialized to {bs.Length} bytes in {((float)sw.ElapsedTicks / Stopwatch.Frequency) * 1000} ms: {string.Join(",", bs)}"); Logger.D("will deserialize"); sw.Reset(); sw.Start(); - var codeGenR = Deserializer.Deserialize(bs); + Deserializer.Deserialize(bs,out IncludeAllClassCodeGen codeGenR); sw.Stop(); Logger.D($"deserialized as codeGenR in {((float)sw.ElapsedTicks / Stopwatch.Frequency) * 1000} ms: {codeGenR}"); @@ -76,14 +51,14 @@ public static void Main() Logger.D($"will serialize d in {((float)sw.ElapsedTicks / Stopwatch.Frequency) * 1000} ms: {d}"); sw.Reset(); sw.Start(); - bs = Serializer.Serialize(d); + bs = d.Serialize(); sw.Stop(); Logger.D($"serialized to {bs.Length} bytes: {string.Join(",", bs)}"); Logger.D("will deserialize"); sw.Reset(); sw.Start(); - var dd = Deserializer.Deserialize(bs); + Deserializer.Deserialize(bs, out NotIncludeAllClass dd); sw.Stop(); Logger.D($"deserialized as dd in {((float)sw.ElapsedTicks / Stopwatch.Frequency) * 1000} ms: {dd}"); } diff --git a/Nino_Unity/Assets/Test/Editor/Serialization/Test9.cs b/Nino_Unity/Assets/Test/Editor/Serialization/Test9.cs new file mode 100644 index 0000000..2ea4ef7 --- /dev/null +++ b/Nino_Unity/Assets/Test/Editor/Serialization/Test9.cs @@ -0,0 +1,81 @@ +using System.Collections.Generic; +using System.Linq; +using Test_Nino; + + +// ReSharper disable RedundantTypeArgumentsOfMethod +namespace Nino.Test.Editor.Serialization +{ + public class Test9 + { + private const string SerializationTest9 = "Nino/Test/Serialization/Test9 - Basic Types"; + +#if UNITY_2017_1_OR_NEWER + [UnityEditor.MenuItem(SerializationTest9,priority=9)] +#endif + public static void Main() + { + int a = int.MaxValue; + uint b = uint.MaxValue; + long c = long.MaxValue; + ulong d = ulong.MaxValue; + float e = float.MaxValue; + double f = double.MaxValue; + decimal g = decimal.MaxValue; + string h = "Hello World"; + bool i = true; + char j = 'a'; + byte k = byte.MaxValue; + sbyte l = sbyte.MaxValue; + ushort m = ushort.MaxValue; + short n = short.MaxValue; + int[] o = new int[]{ 1, 2, 3, 4, 5 }; + List p = new List() { 1, 2, 3, 4, 5 }; + Dictionary q = new Dictionary() + { { "a", 1 }, { "b", 2 }, { "c", 3 }, { "d", 4 }, { "e", 5 } }; + + T Deserialize(byte[] bytes) where T : unmanaged + { + Deserializer.Deserialize(bytes, out T value); + return value; + } + T[] DeserializeArray(byte[] bytes) where T : unmanaged + { + Deserializer.Deserialize(bytes, out T[] value); + return value; + } + List DeserializeList(byte[] bytes) where T : unmanaged + { + Deserializer.Deserialize(bytes, out List value); + return value; + } + string DeserializeString(byte[] bytes) + { + Deserializer.Deserialize(bytes, out string value); + return value; + } + + Logger.D($"Serialized a as: {(((a)).Serialize().Length)} bytes: {(string.Join(",",((a)).Serialize()))}, deserialized as:{Deserialize(a.Serialize())}"); + Logger.D($"Serialized b as: {(((b)).Serialize().Length)} bytes: {(string.Join(",",((b)).Serialize()))}, deserialized as:{Deserialize(b.Serialize())}"); + Logger.D($"Serialized c as: {(((c)).Serialize().Length)} bytes: {(string.Join(",",((c)).Serialize()))}, deserialized as:{Deserialize(c.Serialize())}"); + Logger.D($"Serialized d as: {(((d)).Serialize().Length)} bytes: {(string.Join(",",((d)).Serialize()))}, deserialized as:{Deserialize(d.Serialize())}"); + Logger.D($"Serialized e as: {(((e)).Serialize().Length)} bytes: {(string.Join(",",((e)).Serialize()))}, deserialized as:{Deserialize(e.Serialize())}"); + Logger.D($"Serialized f as: {(((f)).Serialize().Length)} bytes: {(string.Join(",",((f)).Serialize()))}, deserialized as:{Deserialize(f.Serialize())}"); + Logger.D($"Serialized g as: {(((g)).Serialize().Length)} bytes: {(string.Join(",",((g)).Serialize()))}, deserialized as:{Deserialize(g.Serialize())}"); + Logger.D($"Serialized h as: {(((h)).Serialize().Length)} bytes: {(string.Join(",",((h)).Serialize()))}, deserialized as:{DeserializeString(h.Serialize())}"); + Logger.D($"Serialized i as: {(((i)).Serialize().Length)} bytes: {(string.Join(",",((i)).Serialize()))}, deserialized as:{Deserialize(i.Serialize())}"); + Logger.D($"Serialized j as: {(((j)).Serialize().Length)} bytes: {(string.Join(",",((j)).Serialize()))}, deserialized as:{Deserialize(j.Serialize())}"); + Logger.D($"Serialized k as: {(((k)).Serialize().Length)} bytes: {(string.Join(",",((k)).Serialize()))}, deserialized as:{Deserialize(k.Serialize())}"); + Logger.D($"Serialized l as: {(((l)).Serialize().Length)} bytes: {(string.Join(",",((l)).Serialize()))}, deserialized as:{Deserialize(l.Serialize())}"); + Logger.D($"Serialized m as: {(((m)).Serialize().Length)} bytes: {(string.Join(",",((m)).Serialize()))}, deserialized as:{Deserialize(m.Serialize())}"); + Logger.D($"Serialized n as: {(((n)).Serialize().Length)} bytes: {(string.Join(",",((n)).Serialize()))}, deserialized as:{Deserialize(n.Serialize())}"); + Logger.D($"Serialized o as: {(((o)).Serialize().Length)} bytes: {(string.Join(",",((o)).Serialize()))}, deserialized as:{DeserializeArray(o.Serialize())}"); + Logger.D($"Serialized p as: {(((p)).Serialize().Length)} bytes: {(string.Join(",",((p)).Serialize()))}, deserialized as:{string.Join(",",DeserializeList(p.Serialize()))}"); + Deserializer.Deserialize(q.Serialize(), out Dictionary dict); + Logger.D( + $"Serialized q as: {(((q)).Serialize().Length)} bytes: {(string.Join(",", ((q)).Serialize()))}, " + + $"deserialized as:{string.Join(",", dict.ToList().SelectMany(kvp => $"{kvp.Key}-{kvp.Value}"))}"); + } + } +} +// ReSharper restore RedundantTypeArgumentsOfMethod \ No newline at end of file diff --git a/Nino_Unity/Assets/Test/Editor/Test.Editor.asmdef b/Nino_Unity/Assets/Test/Editor/Test.Editor.asmdef new file mode 100644 index 0000000..6a35c79 --- /dev/null +++ b/Nino_Unity/Assets/Test/Editor/Test.Editor.asmdef @@ -0,0 +1,16 @@ +{ + "name": "Test.Editor", + "rootNamespace": "", + "references": ["GUID:0371820e3c81945b3853517b36266c3a","GUID:8cb834c2cb7b04c2391ea9063c36e935","GUID:b4ba1c6530914478f9c4dc9b75d56ac4","GUID:0062188b04f3b485c8cd32a3cac02b12","GUID:bbde805d927e795439d7a746d1749cab","GUID:5a46ad82eac024e4fbb6a0516a5def17"], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Nino_Unity/Assets/Nino/Test/MessagePackGenerated.cs b/Nino_Unity/Assets/Test/MessagePackGenerated.cs similarity index 74% rename from Nino_Unity/Assets/Nino/Test/MessagePackGenerated.cs rename to Nino_Unity/Assets/Test/MessagePackGenerated.cs index 89ec334..3972988 100644 --- a/Nino_Unity/Assets/Nino/Test/MessagePackGenerated.cs +++ b/Nino_Unity/Assets/Test/MessagePackGenerated.cs @@ -50,7 +50,7 @@ internal static class GeneratedResolverGetFormatterHelper static GeneratedResolverGetFormatterHelper() { - lookup = new global::System.Collections.Generic.Dictionary(14) + lookup = new global::System.Collections.Generic.Dictionary(13) { { typeof(global::Nino.Test.Data[]), 0 }, { typeof(global::Nino.Test.NotIncludeAllClass[]), 1 }, @@ -62,10 +62,9 @@ static GeneratedResolverGetFormatterHelper() { typeof(global::System.Collections.Generic.List), 7 }, { typeof(global::Nino.Test.TestEnum), 8 }, { typeof(global::Nino.Test.BuildTestDataCodeGen), 9 }, - { typeof(global::Nino.Test.BuildTestDataNoCodeGen), 10 }, - { typeof(global::Nino.Test.Data), 11 }, - { typeof(global::Nino.Test.NestedData), 12 }, - { typeof(global::Nino.Test.NotIncludeAllClass), 13 }, + { typeof(global::Nino.Test.Data), 10 }, + { typeof(global::Nino.Test.NestedData), 11 }, + { typeof(global::Nino.Test.NotIncludeAllClass), 12 }, }; } @@ -89,10 +88,9 @@ internal static object GetFormatter(Type t) case 7: return new global::MessagePack.Formatters.ListFormatter(); case 8: return new MessagePack.Formatters.Nino.Test.TestEnumFormatter(); case 9: return new MessagePack.Formatters.Nino.Test.BuildTestDataCodeGenFormatter(); - case 10: return new MessagePack.Formatters.Nino.Test.BuildTestDataNoCodeGenFormatter(); - case 11: return new MessagePack.Formatters.Nino.Test.DataFormatter(); - case 12: return new MessagePack.Formatters.Nino.Test.NestedDataFormatter(); - case 13: return new MessagePack.Formatters.Nino.Test.NotIncludeAllClassFormatter(); + case 10: return new MessagePack.Formatters.Nino.Test.DataFormatter(); + case 11: return new MessagePack.Formatters.Nino.Test.NestedDataFormatter(); + case 12: return new MessagePack.Formatters.Nino.Test.NotIncludeAllClassFormatter(); default: return null; } } @@ -306,136 +304,6 @@ public void Serialize(ref global::MessagePack.MessagePackWriter writer, global:: } } - public sealed class BuildTestDataNoCodeGenFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - public void Serialize(ref global::MessagePack.MessagePackWriter writer, global::Nino.Test.BuildTestDataNoCodeGen value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - global::MessagePack.IFormatterResolver formatterResolver = options.Resolver; - writer.WriteArrayHeader(22); - writer.Write(value.a); - writer.Write(value.b); - writer.Write(value.c); - writer.Write(value.d); - writer.Write(value.e); - writer.Write(value.f); - writer.Write(value.g); - writer.Write(value.h); - writer.Write(value.i); - writer.Write(value.j); - formatterResolver.GetFormatterWithVerify().Serialize(ref writer, value.k, options); - writer.Write(value.l); - writer.Write(value.m); - formatterResolver.GetFormatterWithVerify().Serialize(ref writer, value.n, options); - formatterResolver.GetFormatterWithVerify>().Serialize(ref writer, value.o, options); - formatterResolver.GetFormatterWithVerify>().Serialize(ref writer, value.p, options); - writer.Write(value.q); - formatterResolver.GetFormatterWithVerify().Serialize(ref writer, value.r, options); - formatterResolver.GetFormatterWithVerify>().Serialize(ref writer, value.s, options); - formatterResolver.GetFormatterWithVerify>().Serialize(ref writer, value.t, options); - formatterResolver.GetFormatterWithVerify>().Serialize(ref writer, value.u, options); - formatterResolver.GetFormatterWithVerify>().Serialize(ref writer, value.v, options); - } - - public global::Nino.Test.BuildTestDataNoCodeGen Deserialize(ref global::MessagePack.MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - options.Security.DepthStep(ref reader); - global::MessagePack.IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadArrayHeader(); - var ____result = new global::Nino.Test.BuildTestDataNoCodeGen(); - - for (int i = 0; i < length; i++) - { - switch (i) - { - case 0: - ____result.a = reader.ReadByte(); - break; - case 1: - ____result.b = reader.ReadSByte(); - break; - case 2: - ____result.c = reader.ReadInt16(); - break; - case 3: - ____result.d = reader.ReadUInt16(); - break; - case 4: - ____result.e = reader.ReadInt32(); - break; - case 5: - ____result.f = reader.ReadUInt32(); - break; - case 6: - ____result.g = reader.ReadInt64(); - break; - case 7: - ____result.h = reader.ReadUInt64(); - break; - case 8: - ____result.i = reader.ReadSingle(); - break; - case 9: - ____result.j = reader.ReadDouble(); - break; - case 10: - ____result.k = formatterResolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 11: - ____result.l = reader.ReadBoolean(); - break; - case 12: - ____result.m = reader.ReadChar(); - break; - case 13: - ____result.n = formatterResolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 14: - ____result.o = formatterResolver.GetFormatterWithVerify>().Deserialize(ref reader, options); - break; - case 15: - ____result.p = formatterResolver.GetFormatterWithVerify>().Deserialize(ref reader, options); - break; - case 16: - ____result.q = reader.ReadBytes()?.ToArray(); - break; - case 17: - ____result.r = formatterResolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 18: - ____result.s = formatterResolver.GetFormatterWithVerify>().Deserialize(ref reader, options); - break; - case 19: - ____result.t = formatterResolver.GetFormatterWithVerify>().Deserialize(ref reader, options); - break; - case 20: - ____result.u = formatterResolver.GetFormatterWithVerify>().Deserialize(ref reader, options); - break; - case 21: - ____result.v = formatterResolver.GetFormatterWithVerify>().Deserialize(ref reader, options); - break; - default: - reader.Skip(); - break; - } - } - - reader.Depth--; - return ____result; - } - } - public sealed class DataFormatter : global::MessagePack.Formatters.IMessagePackFormatter { diff --git a/Nino_Unity/Assets/Test/Nino/Nino.Core.dll b/Nino_Unity/Assets/Test/Nino/Nino.Core.dll new file mode 100644 index 0000000..20d3ca4 Binary files /dev/null and b/Nino_Unity/Assets/Test/Nino/Nino.Core.dll differ diff --git a/Nino_Unity/Assets/Test/Nino/Nino.Generator.dll b/Nino_Unity/Assets/Test/Nino/Nino.Generator.dll new file mode 100644 index 0000000..90b09c2 Binary files /dev/null and b/Nino_Unity/Assets/Test/Nino/Nino.Generator.dll differ diff --git a/Nino_Unity/Assets/Nino/Shared/ThirdParty/System.Buffers.dll b/Nino_Unity/Assets/Test/Nino/ThirdParty/System.Buffers.dll similarity index 100% rename from Nino_Unity/Assets/Nino/Shared/ThirdParty/System.Buffers.dll rename to Nino_Unity/Assets/Test/Nino/ThirdParty/System.Buffers.dll diff --git a/Nino_Unity/Assets/Nino/Shared/ThirdParty/System.Memory.dll b/Nino_Unity/Assets/Test/Nino/ThirdParty/System.Memory.dll similarity index 100% rename from Nino_Unity/Assets/Nino/Shared/ThirdParty/System.Memory.dll rename to Nino_Unity/Assets/Test/Nino/ThirdParty/System.Memory.dll diff --git a/Nino_Unity/Assets/Nino/Shared/ThirdParty/System.Runtime.CompilerServices.Unsafe.dll b/Nino_Unity/Assets/Test/Nino/ThirdParty/System.Runtime.CompilerServices.Unsafe.dll similarity index 100% rename from Nino_Unity/Assets/Nino/Shared/ThirdParty/System.Runtime.CompilerServices.Unsafe.dll rename to Nino_Unity/Assets/Test/Nino/ThirdParty/System.Runtime.CompilerServices.Unsafe.dll diff --git a/Nino_Unity/Assets/Nino/Editor/Nino.Editor.asmdef b/Nino_Unity/Assets/Test/Test.asmdef similarity index 59% rename from Nino_Unity/Assets/Nino/Editor/Nino.Editor.asmdef rename to Nino_Unity/Assets/Test/Test.asmdef index d7c3961..6a9304f 100644 --- a/Nino_Unity/Assets/Nino/Editor/Nino.Editor.asmdef +++ b/Nino_Unity/Assets/Test/Test.asmdef @@ -1,11 +1,14 @@ { - "name": "Nino.Editor", + "name": "Test", + "rootNamespace": "", "references": [ - "Nino.Serialization" - ], - "includePlatforms": [ - "Editor" + "Nino", + "Mongo", + "Protobuf", + "MessagePack", + "MessagePack.Annotations" ], + "includePlatforms": [], "excludePlatforms": [], "allowUnsafeCode": false, "overrideReferences": false, diff --git a/Nino_Unity/ProjectSettings/BurstAotSettings_Android.json b/Nino_Unity/ProjectSettings/BurstAotSettings_Android.json new file mode 100644 index 0000000..ce2d8aa --- /dev/null +++ b/Nino_Unity/ProjectSettings/BurstAotSettings_Android.json @@ -0,0 +1,17 @@ +{ + "MonoBehaviour": { + "Version": 4, + "EnableBurstCompilation": true, + "EnableOptimisations": true, + "EnableSafetyChecks": false, + "EnableDebugInAllBuilds": false, + "DebugDataKind": 1, + "EnableArmv9SecurityFeatures": false, + "CpuMinTargetX32": 0, + "CpuMaxTargetX32": 0, + "CpuMinTargetX64": 0, + "CpuMaxTargetX64": 0, + "CpuTargetsArm64": 512, + "OptimizeFor": 0 + } +} diff --git a/Nino_Unity/ProjectSettings/CommonBurstAotSettings.json b/Nino_Unity/ProjectSettings/CommonBurstAotSettings.json new file mode 100644 index 0000000..0293daf --- /dev/null +++ b/Nino_Unity/ProjectSettings/CommonBurstAotSettings.json @@ -0,0 +1,6 @@ +{ + "MonoBehaviour": { + "Version": 4, + "DisabledWarnings": "" + } +} diff --git a/Nino_Unity/ProjectSettings/MemorySettings.asset b/Nino_Unity/ProjectSettings/MemorySettings.asset new file mode 100644 index 0000000..5b5face --- /dev/null +++ b/Nino_Unity/ProjectSettings/MemorySettings.asset @@ -0,0 +1,35 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!387306366 &1 +MemorySettings: + m_ObjectHideFlags: 0 + m_EditorMemorySettings: + m_MainAllocatorBlockSize: -1 + m_ThreadAllocatorBlockSize: -1 + m_MainGfxBlockSize: -1 + m_ThreadGfxBlockSize: -1 + m_CacheBlockSize: -1 + m_TypetreeBlockSize: -1 + m_ProfilerBlockSize: -1 + m_ProfilerEditorBlockSize: -1 + m_BucketAllocatorGranularity: -1 + m_BucketAllocatorBucketsCount: -1 + m_BucketAllocatorBlockSize: -1 + m_BucketAllocatorBlockCount: -1 + m_ProfilerBucketAllocatorGranularity: -1 + m_ProfilerBucketAllocatorBucketsCount: -1 + m_ProfilerBucketAllocatorBlockSize: -1 + m_ProfilerBucketAllocatorBlockCount: -1 + m_TempAllocatorSizeMain: -1 + m_JobTempAllocatorBlockSize: -1 + m_BackgroundJobTempAllocatorBlockSize: -1 + m_JobTempAllocatorReducedBlockSize: -1 + m_TempAllocatorSizeGIBakingWorker: -1 + m_TempAllocatorSizeNavMeshWorker: -1 + m_TempAllocatorSizeAudioWorker: -1 + m_TempAllocatorSizeCloudWorker: -1 + m_TempAllocatorSizeGfx: -1 + m_TempAllocatorSizeJobWorker: -1 + m_TempAllocatorSizeBackgroundWorker: -1 + m_TempAllocatorSizePreloadManager: -1 + m_PlatformMemorySettings: {} diff --git a/Nino_Unity/ProjectSettings/ProjectSettings.asset b/Nino_Unity/ProjectSettings/ProjectSettings.asset index 7440861..6e77f88 100644 --- a/Nino_Unity/ProjectSettings/ProjectSettings.asset +++ b/Nino_Unity/ProjectSettings/ProjectSettings.asset @@ -3,7 +3,7 @@ --- !u!129 &1 PlayerSettings: m_ObjectHideFlags: 0 - serializedVersion: 23 + serializedVersion: 26 productGUID: 68b1aad519424499bae0af33f13e893b AndroidProfiler: 0 AndroidFilterTouchesWhenObscured: 0 @@ -48,14 +48,16 @@ PlayerSettings: defaultScreenHeightWeb: 600 m_StereoRenderingPath: 0 m_ActiveColorSpace: 0 + unsupportedMSAAFallback: 0 + m_SpriteBatchVertexThreshold: 300 m_MTRendering: 1 mipStripping: 0 numberOfMipsStripped: 0 + numberOfMipsStrippedPerMipmapLimitGroup: {} m_StackTraceTypes: 010000000100000001000000010000000100000001000000 iosShowActivityIndicatorOnLoading: -1 androidShowActivityIndicatorOnLoading: -1 iosUseCustomAppBackgroundBehavior: 0 - iosAllowHTTPDownload: 1 allowedAutorotateToPortrait: 1 allowedAutorotateToPortraitUpsideDown: 1 allowedAutorotateToLandscapeRight: 1 @@ -74,6 +76,7 @@ PlayerSettings: androidMinimumWindowWidth: 400 androidMinimumWindowHeight: 300 androidFullscreenMode: 1 + androidAutoRotationBehavior: 1 defaultIsNativeResolution: 1 macRetinaSupport: 1 runInBackground: 1 @@ -85,6 +88,7 @@ PlayerSettings: hideHomeButton: 0 submitAnalytics: 1 usePlayerLog: 1 + dedicatedServerOptimizations: 0 bakeCollisionMeshes: 0 forceSingleInstance: 0 useFlipModelSwapchain: 1 @@ -119,8 +123,12 @@ PlayerSettings: switchNVNShaderPoolsGranularity: 33554432 switchNVNDefaultPoolsGranularity: 16777216 switchNVNOtherPoolsGranularity: 16777216 + switchGpuScratchPoolGranularity: 2097152 + switchAllowGpuScratchShrinking: 0 switchNVNMaxPublicTextureIDCount: 0 switchNVNMaxPublicSamplerIDCount: 0 + switchNVNGraphicsFirmwareMemory: 32 + switchMaxWorkerMultiple: 8 stadiaPresentMode: 0 stadiaTargetFramerate: 0 vulkanNumSwapchainBuffers: 3 @@ -128,12 +136,9 @@ PlayerSettings: vulkanEnablePreTransform: 0 vulkanEnableLateAcquireNextImage: 0 vulkanEnableCommandBufferRecycling: 1 - m_SupportedAspectRatios: - 4:3: 1 - 5:4: 1 - 16:10: 1 - 16:9: 1 - Others: 1 + loadStoreDebugModeEnabled: 0 + visionOSBundleVersion: 1.0 + tvOSBundleVersion: 1.0 bundleVersion: 0.1 preloadedAssets: [] metroInputSource: 0 @@ -145,8 +150,10 @@ PlayerSettings: enable360StereoCapture: 0 isWsaHolographicRemotingEnabled: 0 enableFrameTimingStats: 0 + enableOpenGLProfilerGPURecorders: 1 + allowHDRDisplaySupport: 0 useHDRDisplay: 0 - D3DHDRBitDepth: 0 + hdrBitDepth: 0 m_ColorGamuts: 00000000 targetPixelDensity: 30 resolutionScalingMode: 0 @@ -155,13 +162,15 @@ PlayerSettings: androidMaxAspectRatio: 2.1 applicationIdentifier: Android: com.DefaultCompany.Nino + iPhone: com.DefaultCompany.Nino buildNumber: Standalone: 0 + VisionOS: 0 iPhone: 0 tvOS: 0 overrideDefaultApplicationIdentifier: 0 AndroidBundleVersionCode: 1 - AndroidMinSdkVersion: 19 + AndroidMinSdkVersion: 22 AndroidTargetSdkVersion: 0 AndroidPreferredInstallLocation: 1 aotOptions: @@ -174,12 +183,15 @@ PlayerSettings: APKExpansionFiles: 0 keepLoadedShadersAlive: 0 StripUnusedMeshComponents: 1 + strictShaderVariantMatching: 0 VertexChannelCompressionMask: 4054 iPhoneSdkVersion: 988 - iOSTargetOSVersionString: 11.0 + iOSTargetOSVersionString: 12.0 tvOSSdkVersion: 0 tvOSRequireExtendedGameController: 0 - tvOSTargetOSVersionString: 11.0 + tvOSTargetOSVersionString: 12.0 + VisionOSSdkVersion: 0 + VisionOSTargetOSVersionString: 1.0 uIPrerenderedIcon: 0 uIRequiresPersistentWiFi: 0 uIRequiresFullScreen: 1 @@ -217,6 +229,7 @@ PlayerSettings: iOSLaunchScreeniPadCustomStoryboardPath: iOSDeviceRequirements: [] iOSURLSchemes: [] + macOSURLSchemes: [] iOSBackgroundModes: 0 iOSMetalForceHardShadows: 0 metalEditorSupport: 1 @@ -226,8 +239,10 @@ PlayerSettings: appleDeveloperTeamID: iOSManualSigningProvisioningProfileID: tvOSManualSigningProvisioningProfileID: + VisionOSManualSigningProvisioningProfileID: iOSManualSigningProvisioningProfileType: 0 tvOSManualSigningProvisioningProfileType: 0 + VisionOSManualSigningProvisioningProfileType: 0 appleEnableAutomaticSigning: 0 iOSRequireARKit: 0 iOSAutomaticallyDetectAndAddCapabilities: 1 @@ -242,6 +257,7 @@ PlayerSettings: useCustomLauncherGradleManifest: 0 useCustomBaseGradleTemplate: 0 useCustomGradlePropertiesTemplate: 0 + useCustomGradleSettingsTemplate: 0 useCustomProguardFile: 0 AndroidTargetArchitectures: 1 AndroidTargetDevices: 0 @@ -249,6 +265,7 @@ PlayerSettings: androidSplashScreen: {fileID: 0} AndroidKeystoreName: AndroidKeyaliasName: + AndroidEnableArmv9SecurityFeatures: 0 AndroidBuildApkPerCpuArchitecture: 0 AndroidTVCompatibility: 0 AndroidIsGame: 1 @@ -262,7 +279,6 @@ PlayerSettings: banner: {fileID: 0} androidGamepadSupportLevel: 0 chromeosInputEmulation: 1 - AndroidMinifyWithR8: 0 AndroidMinifyRelease: 0 AndroidMinifyDebug: 0 AndroidValidateAppBundleSize: 1 @@ -361,7 +377,105 @@ PlayerSettings: m_Height: 36 m_Kind: 1 m_SubKind: + - m_BuildTarget: iPhone + m_Icons: + - m_Textures: [] + m_Width: 180 + m_Height: 180 + m_Kind: 0 + m_SubKind: iPhone + - m_Textures: [] + m_Width: 120 + m_Height: 120 + m_Kind: 0 + m_SubKind: iPhone + - m_Textures: [] + m_Width: 167 + m_Height: 167 + m_Kind: 0 + m_SubKind: iPad + - m_Textures: [] + m_Width: 152 + m_Height: 152 + m_Kind: 0 + m_SubKind: iPad + - m_Textures: [] + m_Width: 76 + m_Height: 76 + m_Kind: 0 + m_SubKind: iPad + - m_Textures: [] + m_Width: 120 + m_Height: 120 + m_Kind: 3 + m_SubKind: iPhone + - m_Textures: [] + m_Width: 80 + m_Height: 80 + m_Kind: 3 + m_SubKind: iPhone + - m_Textures: [] + m_Width: 80 + m_Height: 80 + m_Kind: 3 + m_SubKind: iPad + - m_Textures: [] + m_Width: 40 + m_Height: 40 + m_Kind: 3 + m_SubKind: iPad + - m_Textures: [] + m_Width: 87 + m_Height: 87 + m_Kind: 1 + m_SubKind: iPhone + - m_Textures: [] + m_Width: 58 + m_Height: 58 + m_Kind: 1 + m_SubKind: iPhone + - m_Textures: [] + m_Width: 29 + m_Height: 29 + m_Kind: 1 + m_SubKind: iPhone + - m_Textures: [] + m_Width: 58 + m_Height: 58 + m_Kind: 1 + m_SubKind: iPad + - m_Textures: [] + m_Width: 29 + m_Height: 29 + m_Kind: 1 + m_SubKind: iPad + - m_Textures: [] + m_Width: 60 + m_Height: 60 + m_Kind: 2 + m_SubKind: iPhone + - m_Textures: [] + m_Width: 40 + m_Height: 40 + m_Kind: 2 + m_SubKind: iPhone + - m_Textures: [] + m_Width: 40 + m_Height: 40 + m_Kind: 2 + m_SubKind: iPad + - m_Textures: [] + m_Width: 20 + m_Height: 20 + m_Kind: 2 + m_SubKind: iPad + - m_Textures: [] + m_Width: 1024 + m_Height: 1024 + m_Kind: 4 + m_SubKind: App Store m_BuildTargetBatching: [] + m_BuildTargetShaderSettings: [] m_BuildTargetGraphicsJobs: - m_BuildTarget: MacStandaloneSupport m_GraphicsJobs: 0 @@ -402,6 +516,8 @@ PlayerSettings: m_APIs: 10000000 m_Automatic: 1 m_BuildTargetVRSettings: [] + m_DefaultShaderChunkSizeInMB: 16 + m_DefaultShaderChunkCount: 0 openGLRequireES31: 0 openGLRequireES31AEP: 0 openGLRequireES32: 0 @@ -411,8 +527,11 @@ PlayerSettings: iPhone: 1 tvOS: 1 m_BuildTargetGroupLightmapEncodingQuality: [] + m_BuildTargetGroupHDRCubemapEncodingQuality: [] m_BuildTargetGroupLightmapSettings: [] + m_BuildTargetGroupLoadStoreDebugModeSettings: [] m_BuildTargetNormalMapEncoding: [] + m_BuildTargetDefaultTextureCompressionFormat: [] playModeTestRunnerEnabled: 0 runPlayModeTestAsEditModeTest: 0 actionOnDotNetUnhandledException: 1 @@ -423,6 +542,7 @@ PlayerSettings: locationUsageDescription: microphoneUsageDescription: bluetoothUsageDescription: + macOSTargetOSVersion: 10.13.0 switchNMETAOverride: switchNetLibKey: switchSocketMemoryPoolSize: 6144 @@ -430,9 +550,11 @@ PlayerSettings: switchSocketConcurrencyLimit: 14 switchScreenResolutionBehavior: 2 switchUseCPUProfiler: 0 - switchUseGOLDLinker: 0 + switchEnableFileSystemTrace: 0 + switchLTOSetting: 0 switchApplicationID: 0x01004b9000490000 switchNSODependencies: + switchCompilerFlags: switchTitleNames_0: switchTitleNames_1: switchTitleNames_2: @@ -506,7 +628,6 @@ PlayerSettings: switchReleaseVersion: 0 switchDisplayVersion: 1.0.0 switchStartupUserAccount: 0 - switchTouchScreenUsage: 0 switchSupportedLanguagesMask: 0 switchLogoType: 0 switchApplicationErrorCodeCategory: @@ -548,6 +669,7 @@ PlayerSettings: switchNativeFsCacheSize: 32 switchIsHoldTypeHorizontal: 0 switchSupportedNpadCount: 8 + switchEnableTouchScreen: 1 switchSocketConfigEnabled: 0 switchTcpInitialSendBufferSize: 32 switchTcpInitialReceiveBufferSize: 64 @@ -558,9 +680,8 @@ PlayerSettings: switchSocketBufferEfficiency: 4 switchSocketInitializeEnabled: 1 switchNetworkInterfaceManagerInitializeEnabled: 1 - switchPlayerConnectionEnabled: 1 switchUseNewStyleFilepaths: 0 - switchUseLegacyFmodPriorities: 1 + switchUseLegacyFmodPriorities: 0 switchUseMicroSleepForYield: 1 switchEnableRamDiskSupport: 0 switchMicroSleepForYieldTime: 25 @@ -648,6 +769,7 @@ PlayerSettings: webGLMemorySize: 16 webGLExceptionSupport: 1 webGLNameFilesAsHashes: 0 + webGLShowDiagnostics: 0 webGLDataCaching: 1 webGLDebugSymbols: 0 webGLEmscriptenArgs: @@ -660,6 +782,13 @@ PlayerSettings: webGLLinkerTarget: 1 webGLThreadsSupport: 0 webGLDecompressionFallback: 0 + webGLInitialMemorySize: 32 + webGLMaximumMemorySize: 2048 + webGLMemoryGrowthMode: 2 + webGLMemoryLinearGrowthStep: 16 + webGLMemoryGeometricGrowthStep: 0.2 + webGLMemoryGeometricGrowthCap: 96 + webGLPowerPreference: 2 scriptingDefineSymbols: 7: IL2CPP additionalCompilerArguments: {} @@ -667,17 +796,30 @@ PlayerSettings: scriptingBackend: Android: 1 il2cppCompilerConfiguration: {} - managedStrippingLevel: {} + il2cppCodeGeneration: {} + managedStrippingLevel: + Android: 1 + EmbeddedLinux: 1 + GameCoreScarlett: 1 + GameCoreXboxOne: 1 + Nintendo Switch: 1 + PS4: 1 + PS5: 1 + QNX: 1 + Stadia: 1 + VisionOS: 1 + WebGL: 1 + Windows Store Apps: 1 + XboxOne: 1 + iPhone: 1 + tvOS: 1 incrementalIl2cppBuild: {} suppressCommonWarnings: 1 allowUnsafeCode: 1 useDeterministicCompilation: 1 - useReferenceAssemblies: 1 - enableRoslynAnalyzers: 1 additionalIl2CppArgs: scriptingRuntimeVersion: 1 gcIncremental: 0 - assemblyVersionValidation: 1 gcWBarrierValidation: 0 apiCompatibilityLevelPerPlatform: Android: 3 @@ -706,6 +848,7 @@ PlayerSettings: metroSplashScreenBackgroundColor: {r: 0.12941177, g: 0.17254902, b: 0.21568628, a: 1} metroSplashScreenUseBackgroundColor: 0 + syncCapabilities: 0 platformCapabilities: {} metroTargetDeviceFamilies: {} metroFTAName: @@ -753,6 +896,11 @@ PlayerSettings: luminVersion: m_VersionCode: 1 m_VersionName: + hmiPlayerDataPath: + hmiForceSRGBBlit: 1 + embeddedLinuxEnableGamepadInput: 1 + hmiLogStartupTiming: 0 + hmiCpuConfiguration: apiCompatibilityLevel: 6 activeInputHandler: 0 windowsGamepadBackendHint: 0 @@ -763,4 +911,7 @@ PlayerSettings: organizationId: cloudEnabled: 0 legacyClampBlendShapeWeights: 0 + hmiLoadingImage: {fileID: 0} + platformRequiresReadableAssets: 0 virtualTexturingSupportEnabled: 0 + insecureHttpOption: 0 diff --git a/Nino_Unity/ProjectSettings/ProjectVersion.txt b/Nino_Unity/ProjectSettings/ProjectVersion.txt index d58dcc0..bc915f1 100644 --- a/Nino_Unity/ProjectSettings/ProjectVersion.txt +++ b/Nino_Unity/ProjectSettings/ProjectVersion.txt @@ -1,2 +1,2 @@ -m_EditorVersion: 2020.3.47f1 -m_EditorVersionWithRevision: 2020.3.47f1 (5ef4f5b5e2d4) +m_EditorVersion: 2022.3.24f1 +m_EditorVersionWithRevision: 2022.3.24f1 (334eb2a0b267)