├── .editorconfig ├── .gitignore ├── .travis.yml ├── HEADER ├── License.md ├── README.md ├── ReleaseNotes.txt └── src ├── GameDevWare.Serialization.Tests ├── DataContractMetadataTest.cs ├── DefaultMessagePackExtensionTypeHandlerTests.cs ├── GameDevWare.Serialization.Tests.csproj ├── TestObject.cs ├── ValueContainer.cs ├── WriteReadTest.cs └── packages.config ├── GameDevWare.Serialization.Unity └── Assets │ ├── Plugins │ └── GameDevWare.Serialization │ │ ├── ArrayExtensions.cs │ │ ├── Documentation │ │ └── README.pdf │ │ ├── GenerateTypeSerializerAttribute.cs │ │ ├── IJsonReader.cs │ │ ├── IJsonWriter.cs │ │ ├── IValueInfo.cs │ │ ├── IndexedDictionary.cs │ │ ├── Json.cs │ │ ├── JsonMember.cs │ │ ├── JsonReader.cs │ │ ├── JsonReaderExtentions.cs │ │ ├── JsonSerializationException.cs │ │ ├── JsonStreamReader.cs │ │ ├── JsonStreamWriter.cs │ │ ├── JsonStringBuilderReader.cs │ │ ├── JsonStringBuilderWriter.cs │ │ ├── JsonStringReader.cs │ │ ├── JsonTextReader.cs │ │ ├── JsonTextWriter.cs │ │ ├── JsonToken.cs │ │ ├── JsonUtils.cs │ │ ├── JsonWriter.cs │ │ ├── JsonWriterExtentions.cs │ │ ├── MessagePack │ │ ├── BigEndianBitConverter.cs │ │ ├── DefaultMsgPackExtensionTypeHandler.cs │ │ ├── EndianBitConverter.cs │ │ ├── Endianness.cs │ │ ├── LittleEndianBitConverter.cs │ │ ├── MsgPackExtensionType.cs │ │ ├── MsgPackExtensionTypeHandler.cs │ │ ├── MsgPackReader.cs │ │ ├── MsgPackTimestamp.cs │ │ ├── MsgPackType.cs │ │ ├── MsgPackWriter.cs │ │ ├── UnknownMsgPackExtentionTypeException.cs │ │ └── UnknownMsgPackFormatException.cs │ │ ├── Metadata │ │ ├── DataMemberDescription.cs │ │ ├── FieldDescription.cs │ │ ├── MemberDescription.cs │ │ ├── MetadataReflection.cs │ │ ├── PropertyDescription.cs │ │ └── TypeDescription.cs │ │ ├── MsgPack.cs │ │ ├── PathSegment.cs │ │ ├── ReflectionExtentions.cs │ │ ├── SerializationContext.cs │ │ ├── SerializationOptions.cs │ │ ├── Serializers │ │ ├── ArraySerializer.cs │ │ ├── BinarySerializer.cs │ │ ├── BoundsSerializer.cs │ │ ├── DateTimeOffsetSerializer.cs │ │ ├── DateTimeSerializer.cs │ │ ├── DictionaryEntrySerializer.cs │ │ ├── DictionarySerializer.cs │ │ ├── EnumNumberSerializer.cs │ │ ├── EnumSerializer.cs │ │ ├── GuidSerializer.cs │ │ ├── Matrix4x4Serializer.cs │ │ ├── MsgPackExtensionTypeSerializer.cs │ │ ├── MsgPackTimestampSerializer.cs │ │ ├── ObjectSerializer.cs │ │ ├── PrimitiveTypeSerializer.cs │ │ ├── QuaternionSerializer.cs │ │ ├── RectSerializer.cs │ │ ├── StreamSerializer.cs │ │ ├── TimeSpanSerializer.cs │ │ ├── UriSerializer.cs │ │ ├── Vector2Serializer.cs │ │ ├── Vector3Serializer.cs │ │ ├── Vector4Serializer.cs │ │ └── VersionSerializer.cs │ │ ├── TypeSerializer.cs │ │ └── TypeSerializerAttribute.cs │ └── Scripts │ ├── Benchmark.meta │ ├── Benchmark │ ├── Benchmark.cs │ ├── Benchmark.cs.meta │ ├── Benchmark.unity │ ├── Benchmark.unity.meta │ ├── BigTestObject.cs │ ├── BigTestObject.cs.meta │ ├── ByteCountingStream.cs │ ├── ByteCountingStream.cs.meta │ ├── ITestObject.cs │ ├── ITestObject.cs.meta │ ├── MediumTestObject.cs │ ├── MediumTestObject.cs.meta │ ├── SmallTestObject.cs │ └── SmallTestObject.cs.meta │ ├── Example.meta │ └── Example │ ├── SerializeExample.cs │ └── SerializeExample.cs.meta ├── GameDevWare.Serialization.sln └── GameDevWare.Serialization ├── GameDevWare.Serialization.csproj ├── GameDevWare.Serialization.csproj.DotSettings ├── NonSerializedAttribute.cs └── SerializableAttribute.cs /.editorconfig: -------------------------------------------------------------------------------- 1 | # editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | charset = utf-8 7 | end_of_line = crlf 8 | indent_style = tab 9 | indent_size = 4 10 | trim_trailing_whitespace = true 11 | insert_final_newline = true 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.exp 2 | *.ipch 3 | *.metagen 4 | *.ncb 5 | *.nupkg 6 | *.obj 7 | *.opensdf 8 | *.pdb 9 | *.ReSharper 10 | *.sdf 11 | *.meta 12 | *.suo 13 | *.swp 14 | *.user 15 | *.log 16 | _ReSharper* 17 | *.csproj 18 | *.sln 19 | *.userprefs 20 | *.exe 21 | *.dll 22 | 23 | bin/ 24 | obj/ 25 | .vs 26 | media/ 27 | packages/ 28 | 29 | src/GameDevWare.Serialization.Unity/Assembly* 30 | src/GameDevWare.Serialization.Unity/obj/ 31 | src/GameDevWare.Serialization.Unity/Library/ 32 | src/GameDevWare.Serialization.Unity/Temp/ 33 | src/GameDevWare.Serialization.Unity/Assets/StreamingAssets/ 34 | src/GameDevWare.Serialization.Unity/Assets/Bundles/ 35 | src/GameDevWare.Serialization.Unity/ProjectSettings/ 36 | src/GameDevWare.Serialization.Unity/Assets/AssetStoreTools/ 37 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: csharp 2 | mono: none 3 | dotnet: 2.0.3 4 | dist: trusty 5 | install: 6 | - cd src 7 | - dotnet restore 8 | script: 9 | - dotnet build -f netcoreapp2.0 10 | - cd GameDevWare.Serialization.Tests 11 | - dotnet test -f netcoreapp2.0 12 | -------------------------------------------------------------------------------- /HEADER: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ -------------------------------------------------------------------------------- /License.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /ReleaseNotes.txt: -------------------------------------------------------------------------------- 1 | add check for DynamicMethod support in MetadataReflection (for some environments where Expression.Compile is supported but DynamicMethod is not) 2 | added better error messages in case of missing empty constructor and EOS during deserialization. 3 | added byte[] deserialization options in MsgPack and Json helper classes. 4 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Tests/DataContractMetadataTest.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Runtime.Serialization; 3 | using NUnit.Framework; 4 | 5 | namespace GameDevWare.Serialization.Tests 6 | { 7 | [TestFixture, Category("DataContractMetadataTest")] 8 | public class DataContractMetadataTest 9 | { 10 | [DataContract] 11 | public class ClassWithPrivateMembers 12 | { 13 | [DataMember] 14 | private int field1 { get; set; } 15 | [DataMember] 16 | public int field2; 17 | private int field3; 18 | public int field4 { get; set; } 19 | 20 | private ClassWithPrivateMembers() 21 | { 22 | 23 | } 24 | 25 | public static ClassWithPrivateMembers Create() 26 | { 27 | return new ClassWithPrivateMembers(); 28 | } 29 | 30 | public void Init() 31 | { 32 | this.field1 = 1; 33 | this.field2 = 2; 34 | this.field3 = 3; 35 | this.field4 = 4; 36 | } 37 | 38 | public bool Test(object obj) 39 | { 40 | var other = obj as ClassWithPrivateMembers; 41 | if (other == null) return false; 42 | return this.field1 == other.field1 && this.field2 == other.field2 && this.field3 == 0 && this.field4 == 0; 43 | } 44 | 45 | public override string ToString() 46 | { 47 | return "{" + this.field1 + ", " + this.field2 + ", " + this.field3 + ", " + this.field4 + "}"; 48 | } 49 | } 50 | public class ClassWithSerializablePublicMembers 51 | { 52 | private int field1 { get; set; } 53 | public int field2; 54 | private int field3; 55 | public virtual int field4 { get; set; } 56 | 57 | public virtual void Init() 58 | { 59 | this.field1 = 1; 60 | this.field2 = 2; 61 | this.field3 = 3; 62 | this.field4 = 4; 63 | } 64 | 65 | public virtual bool Test(object obj) 66 | { 67 | var other = obj as ClassWithSerializablePublicMembers; 68 | if (other == null) return false; 69 | return this.field1 == 0 && this.field2 == other.field2 && this.field3 == 0 && this.field4 == other.field4; 70 | } 71 | 72 | public override string ToString() 73 | { 74 | return "{" + this.field1 + ", " + this.field2 + ", " + this.field3 + ", " + this.field4 + "}"; 75 | } 76 | } 77 | [DataContract] 78 | public class ClassWithDerivedMixedContract : ClassWithSerializablePublicMembers 79 | { 80 | [DataMember] 81 | private int field5; 82 | public int field6; 83 | 84 | public override void Init() 85 | { 86 | base.Init(); 87 | 88 | this.field5 = 5; 89 | this.field6 = 6; 90 | } 91 | 92 | public override bool Test(object obj) 93 | { 94 | var other = obj as ClassWithDerivedMixedContract; 95 | if (other == null) return false; 96 | return base.Test(obj) && this.field5 == other.field5 && this.field6 == 0; 97 | } 98 | 99 | public override string ToString() 100 | { 101 | return base.ToString() + " {" + this.field5 + ", " + this.field6 + "}"; 102 | } 103 | } 104 | [DataContract] 105 | public class ClassWithDerivedContractAndOverriddenProperty : ClassWithSerializablePublicMembers 106 | { 107 | [DataMember] 108 | public int field5; 109 | [DataMember] 110 | public override int field4 { get; set; } 111 | 112 | public override void Init() 113 | { 114 | base.Init(); 115 | this.field5 = 5; 116 | this.field4 = 6; 117 | } 118 | 119 | public override bool Test(object obj) 120 | { 121 | var other = obj as ClassWithDerivedContractAndOverriddenProperty; 122 | if (other == null) return false; 123 | return base.Test(obj) && this.field5 == other.field5; 124 | } 125 | 126 | public override string ToString() 127 | { 128 | return base.ToString() + " {" + this.field5 + "}"; 129 | } 130 | } 131 | 132 | [Test] 133 | public void PrivateMembersSerializationTest() 134 | { 135 | var expected = ClassWithPrivateMembers.Create(); 136 | expected.Init(); 137 | var stream = new MemoryStream(); 138 | 139 | MsgPack.Serialize(expected, stream); 140 | stream.Position = 0; 141 | 142 | var actual = MsgPack.Deserialize(stream); 143 | Assert.True(actual.Test(expected), "Actual object is not valid: " + actual + ", this one expected: " + expected); 144 | } 145 | 146 | [Test] 147 | public void PublicMembersSerializationTest() 148 | { 149 | var expected = new ClassWithSerializablePublicMembers(); 150 | expected.Init(); 151 | var stream = new MemoryStream(); 152 | 153 | MsgPack.Serialize(expected, stream); 154 | stream.Position = 0; 155 | 156 | var actual = MsgPack.Deserialize(stream); 157 | Assert.True(actual.Test(expected), "Actual object is not valid: " + actual + ", this one expected: " + expected); 158 | } 159 | 160 | [Test] 161 | public void MixedContractSerializationTest() 162 | { 163 | var expected = new ClassWithDerivedMixedContract(); 164 | expected.Init(); 165 | var stream = new MemoryStream(); 166 | 167 | MsgPack.Serialize(expected, stream); 168 | stream.Position = 0; 169 | 170 | var actual = MsgPack.Deserialize(stream); 171 | Assert.True(actual.Test(expected), "Actual object is not valid: " + actual + ", this one expected: " + expected); 172 | } 173 | 174 | [Test] 175 | public void OverriddenPropertySerializationTest() 176 | { 177 | var expected = new ClassWithDerivedContractAndOverriddenProperty(); 178 | expected.Init(); 179 | var stream = new MemoryStream(); 180 | 181 | MsgPack.Serialize(expected, stream); 182 | stream.Position = 0; 183 | 184 | var actual = MsgPack.Deserialize(stream); 185 | Assert.True(actual.Test(expected), "Actual object is not valid: " + actual + ", this one expected: " + expected); 186 | } 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Tests/DefaultMessagePackExtensionTypeHandlerTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using GameDevWare.Serialization.MessagePack; 3 | using NUnit.Framework; 4 | 5 | namespace GameDevWare.Serialization.Tests 6 | { 7 | [TestFixture, Category("DefaultMessagePackExtensionTypeHandlerTests")] 8 | public class DefaultMessagePackExtensionTypeHandlerTests 9 | { 10 | [Test] 11 | public void TryReadWriteDateTimeLocal() 12 | { 13 | var expectedValue = DateTime.Now; 14 | var writeBuffer = new ArraySegment(new byte[1024]); 15 | DefaultMessagePackExtensionTypeHandler.Instance.TryWrite(expectedValue, out var type, ref writeBuffer); 16 | DefaultMessagePackExtensionTypeHandler.Instance.TryRead(type, writeBuffer, out var actualValue); 17 | 18 | Assert.IsInstanceOf(actualValue); 19 | Assert.AreEqual(expectedValue, (DateTime)actualValue); 20 | Assert.AreEqual(expectedValue.Kind, ((DateTime)actualValue).Kind); 21 | } 22 | 23 | [Test] 24 | public void TryReadWriteDateTimeUtc() 25 | { 26 | var expectedValue = DateTime.UtcNow; 27 | var writeBuffer = new ArraySegment(new byte[1024]); 28 | DefaultMessagePackExtensionTypeHandler.Instance.TryWrite(expectedValue, out var type, ref writeBuffer); 29 | DefaultMessagePackExtensionTypeHandler.Instance.TryRead(type, writeBuffer, out var actualValue); 30 | 31 | Assert.IsInstanceOf(actualValue); 32 | Assert.AreEqual(expectedValue, (DateTime)actualValue); 33 | Assert.AreEqual(expectedValue.Kind, ((DateTime)actualValue).Kind); 34 | } 35 | 36 | [Test] 37 | public void TryReadWriteDateTimeUnspecified() 38 | { 39 | var expectedValue = new DateTime(DateTime.UtcNow.Ticks, DateTimeKind.Unspecified); 40 | var writeBuffer = new ArraySegment(new byte[1024]); 41 | DefaultMessagePackExtensionTypeHandler.Instance.TryWrite(expectedValue, out var type, ref writeBuffer); 42 | DefaultMessagePackExtensionTypeHandler.Instance.TryRead(type, writeBuffer, out var actualValue); 43 | 44 | Assert.AreEqual(expectedValue, (DateTime)actualValue); 45 | Assert.AreEqual(expectedValue.Kind, ((DateTime)actualValue).Kind); 46 | } 47 | 48 | [Test] 49 | public void TryReadWriteDateTimeMax() 50 | { 51 | var expectedValue = DateTime.MaxValue; 52 | var writeBuffer = new ArraySegment(new byte[1024]); 53 | DefaultMessagePackExtensionTypeHandler.Instance.TryWrite(expectedValue, out var type, ref writeBuffer); 54 | DefaultMessagePackExtensionTypeHandler.Instance.TryRead(type, writeBuffer, out var actualValue); 55 | 56 | Assert.IsInstanceOf(actualValue); 57 | Assert.AreEqual(expectedValue, (DateTime)actualValue); 58 | Assert.AreEqual(expectedValue.Kind, ((DateTime)actualValue).Kind); 59 | } 60 | 61 | 62 | [Test] 63 | public void TryReadWriteDateTimeMin() 64 | { 65 | var expectedValue = DateTime.MinValue; 66 | var writeBuffer = new ArraySegment(new byte[1024]); 67 | DefaultMessagePackExtensionTypeHandler.Instance.TryWrite(expectedValue, out var type, ref writeBuffer); 68 | DefaultMessagePackExtensionTypeHandler.Instance.TryRead(type, writeBuffer, out var actualValue); 69 | 70 | Assert.IsInstanceOf(actualValue); 71 | Assert.AreEqual(expectedValue, (DateTime)actualValue); 72 | Assert.AreEqual(expectedValue.Kind, ((DateTime)actualValue).Kind); 73 | } 74 | 75 | [Test] 76 | public void TryReadWriteDateTimeExact() 77 | { 78 | var expectedValue = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Local); 79 | var writeBuffer = new ArraySegment(); 80 | DefaultMessagePackExtensionTypeHandler.Instance.TryWrite(expectedValue, out var type, ref writeBuffer); 81 | DefaultMessagePackExtensionTypeHandler.Instance.TryRead(type, writeBuffer, out var now); 82 | 83 | Assert.IsInstanceOf(now); 84 | Assert.AreEqual(expectedValue, (DateTime)now); 85 | } 86 | 87 | [Test] 88 | public void TryReadWriteDateTimeOffset() 89 | { 90 | var expectedValue = DateTimeOffset.Now; 91 | var writeBuffer = new ArraySegment(new byte[1024]); 92 | DefaultMessagePackExtensionTypeHandler.Instance.TryWrite(expectedValue, out var type, ref writeBuffer); 93 | DefaultMessagePackExtensionTypeHandler.Instance.TryRead(type, writeBuffer, out var actualValue); 94 | 95 | Assert.IsInstanceOf(actualValue); 96 | Assert.AreEqual(expectedValue, (DateTimeOffset)actualValue); 97 | } 98 | 99 | [Test] 100 | public void TryReadWriteDecimalMax() 101 | { 102 | var expectedValue = decimal.MaxValue; 103 | var writeBuffer = new ArraySegment(new byte[1024]); 104 | DefaultMessagePackExtensionTypeHandler.Instance.TryWrite(expectedValue, out var type, ref writeBuffer); 105 | DefaultMessagePackExtensionTypeHandler.Instance.TryRead(type, writeBuffer, out var actualValue); 106 | 107 | Assert.IsInstanceOf(actualValue); 108 | Assert.AreEqual(expectedValue, (decimal)actualValue); 109 | } 110 | 111 | [Test] 112 | public void TryReadWriteDecimalMin() 113 | { 114 | var expectedValue = decimal.MinValue; 115 | var writeBuffer = new ArraySegment(new byte[1024]); 116 | DefaultMessagePackExtensionTypeHandler.Instance.TryWrite(expectedValue, out var type, ref writeBuffer); 117 | DefaultMessagePackExtensionTypeHandler.Instance.TryRead(type, writeBuffer, out var actualValue); 118 | 119 | Assert.IsInstanceOf(actualValue); 120 | Assert.AreEqual(expectedValue, (decimal)actualValue); 121 | } 122 | 123 | [Test] 124 | public void TryReadWriteGuid() 125 | { 126 | var expectedValue = Guid.NewGuid(); 127 | var writeBuffer = new ArraySegment(new byte[1024]); 128 | DefaultMessagePackExtensionTypeHandler.Instance.TryWrite(expectedValue, out var type, ref writeBuffer); 129 | DefaultMessagePackExtensionTypeHandler.Instance.TryRead(type, writeBuffer, out var actualValue); 130 | 131 | Assert.IsInstanceOf(actualValue); 132 | Assert.AreEqual(expectedValue, (Guid)actualValue); 133 | } 134 | 135 | [Test] 136 | public void TryReadWriteMessagePackTimestamp() 137 | { 138 | var expectedValue = new MessagePackTimestamp(1500, 1500); 139 | var writeBuffer = new ArraySegment(new byte[1024]); 140 | DefaultMessagePackExtensionTypeHandler.Instance.TryWrite(expectedValue, out var type, ref writeBuffer); 141 | DefaultMessagePackExtensionTypeHandler.Instance.TryRead(type, writeBuffer, out var actualValue); 142 | 143 | Assert.IsInstanceOf(actualValue); 144 | Assert.AreEqual(expectedValue, (MessagePackTimestamp)actualValue); 145 | } 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Tests/GameDevWare.Serialization.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net45;netcoreapp2.0 5 | 2.0.3 6 | 0.0.0 7 | True 8 | Library 9 | false 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Tests/TestObject.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.Globalization; 6 | using System.Linq; 7 | 8 | namespace GameDevWare.Serialization.Tests 9 | { 10 | public class TestObject 11 | { 12 | private sealed class Comparer : IEqualityComparer 13 | { 14 | public static readonly IEqualityComparer Default = new Comparer(); 15 | 16 | bool IEqualityComparer.Equals(object a, object b) 17 | { 18 | var areEquals = false; 19 | if (ReferenceEquals(a, b)) 20 | areEquals = true; 21 | else if (a == null || b == null) 22 | areEquals = false; 23 | else if (a is string && b is string) 24 | areEquals = a.Equals(b); 25 | else if (a.GetType() != b.GetType() && TryChangeType(b.GetType(), ref a)) 26 | areEquals = a.Equals(b); 27 | else if (a.GetType() != b.GetType() && TryChangeType(a.GetType(), ref b)) 28 | areEquals = a.Equals(b); 29 | else if (a is IEnumerable && b is IEnumerable) 30 | areEquals = ((IEnumerable)a).Cast().SequenceEqual(((IEnumerable)b).Cast(), Default); 31 | else if (a is DateTime && b is DateTime) 32 | { 33 | var aTicks = ((DateTime)a).ToUniversalTime().Ticks; 34 | var bTicks = ((DateTime)b).ToUniversalTime().Ticks; 35 | areEquals = aTicks - (aTicks % TimeSpan.TicksPerSecond) == bTicks - (bTicks % TimeSpan.TicksPerSecond); 36 | } 37 | else if (a is DateTimeOffset && b is DateTimeOffset) 38 | { 39 | var aTicks = ((DateTimeOffset)a).Ticks; 40 | var bTicks = ((DateTimeOffset)b).Ticks; 41 | areEquals = aTicks - (aTicks % TimeSpan.TicksPerSecond) == bTicks - (bTicks % TimeSpan.TicksPerSecond); 42 | } 43 | else if (a.GetType() == typeof(object) && b.GetType() == typeof(object)) 44 | return true; 45 | else 46 | areEquals = a.Equals(b); 47 | 48 | if (areEquals == false && Debugger.IsAttached) 49 | Debugger.Break(); 50 | 51 | return areEquals; 52 | } 53 | int IEqualityComparer.GetHashCode(object obj) 54 | { 55 | if (obj is IEnumerable) 56 | return ((IEnumerable)obj).Cast().Aggregate(0, (s, v) => unchecked(s + Default.GetHashCode(v))); 57 | return obj == null ? 0 : obj.GetHashCode(); 58 | } 59 | } 60 | 61 | public int IntField; 62 | public int IntProperty { get; set; } 63 | public short ShortField; 64 | public long LongField; 65 | public double DoubleField; 66 | public float SingleField; 67 | public decimal DecimalField; 68 | public int[] IntArrayProperty { get; set; } 69 | public TestObject ObjectProperty { get; set; } 70 | public TestObject[] ObjectArrayProperty { get; set; } 71 | public object[] MixedArrayProperty { get; set; } 72 | public string[] StringArrayProperty { get; set; } 73 | public string StringProperty { get; set; } 74 | public bool BoolProperty { get; set; } 75 | public DateTime DateProperty { get; set; } 76 | public DateTimeOffset DateOffsetProperty { get; set; } 77 | public long? NullableProperty { get; set; } 78 | public object AnyProperty { get; set; } 79 | 80 | public override bool Equals(object obj) 81 | { 82 | var other = obj as TestObject; 83 | if (other == null) 84 | return false; 85 | 86 | return this.IntField == other.IntField && 87 | this.IntProperty == other.IntProperty && 88 | this.LongField == other.LongField && 89 | Math.Abs(this.DoubleField - other.DoubleField) < double.Epsilon && 90 | Math.Abs(this.SingleField - other.SingleField) < float.Epsilon && 91 | this.ShortField == other.ShortField && 92 | this.DecimalField == other.DecimalField && 93 | this.StringProperty == other.StringProperty && 94 | Comparer.Default.Equals(this.DateProperty, other.DateProperty) && 95 | Comparer.Default.Equals(this.DateOffsetProperty, other.DateOffsetProperty) && 96 | this.BoolProperty == other.BoolProperty && 97 | this.NullableProperty == other.NullableProperty && 98 | Comparer.Default.Equals(this.AnyProperty, other.AnyProperty) && 99 | Comparer.Default.Equals(this.IntArrayProperty, other.IntArrayProperty) && 100 | Comparer.Default.Equals(this.MixedArrayProperty, other.MixedArrayProperty) && 101 | Comparer.Default.Equals(this.ObjectProperty, other.ObjectProperty) && 102 | Comparer.Default.Equals(this.ObjectArrayProperty, other.ObjectArrayProperty) && 103 | Comparer.Default.Equals(this.StringArrayProperty, other.StringArrayProperty); 104 | } 105 | public override int GetHashCode() 106 | { 107 | return unchecked(this.IntField + this.IntField + 108 | ShortField + LongField.GetHashCode() + 109 | DoubleField.GetHashCode() + 110 | SingleField.GetHashCode() + 111 | DecimalField.GetHashCode() + 112 | (this.StringProperty ?? "").GetHashCode() + 113 | DateProperty.GetHashCode() + 114 | DateOffsetProperty.GetHashCode() + 115 | (AnyProperty ?? string.Empty).GetHashCode() 116 | ); 117 | } 118 | 119 | private static bool TryChangeType(Type toType, ref object value) 120 | { 121 | try 122 | { 123 | if (toType.IsEnum) 124 | value = Enum.ToObject(toType, Convert.ChangeType(value, Enum.GetUnderlyingType(toType))); 125 | else if (toType == typeof(DateTime) && value is string) 126 | value = DateTime.Parse((string)value, CultureInfo.InvariantCulture); 127 | else if (toType == typeof(DateTimeOffset) && value is string) 128 | value = DateTimeOffset.Parse((string)value, CultureInfo.InvariantCulture); 129 | else 130 | value = Convert.ChangeType(value, toType); 131 | return true; 132 | } 133 | catch 134 | { 135 | return false; 136 | } 137 | } 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Tests/ValueContainer.cs: -------------------------------------------------------------------------------- 1 | namespace GameDevWare.Serialization.Tests 2 | { 3 | public class ValueContainer 4 | { 5 | public T Value; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Tests/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/ArrayExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace GameDevWare.Serialization 3 | { 4 | internal static class ArrayExtensions 5 | { 6 | public static OutputT[] ConvertAll(this T[] array, Func converter) 7 | { 8 | if (array == null) throw new ArgumentNullException("array"); 9 | if (converter == null) throw new ArgumentNullException("converter"); 10 | 11 | var newList = new OutputT[array.Length]; 12 | var i = 0; 13 | foreach (var item in array) 14 | { 15 | newList[i++] = converter(item); 16 | } 17 | return newList; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Documentation/README.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deniszykov/msgpack-unity3d/fad13635c50d3820e478009b5f08a3ef765ccf36/src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Documentation/README.pdf -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/GenerateTypeSerializerAttribute.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | 18 | // ReSharper disable once CheckNamespace 19 | namespace GameDevWare.Serialization 20 | { 21 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)] 22 | public class GenerateTypeSerializerAttribute : Attribute 23 | { 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/IJsonReader.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | 17 | // ReSharper disable once CheckNamespace 18 | namespace GameDevWare.Serialization 19 | { 20 | public interface IJsonReader 21 | { 22 | SerializationContext Context { get; } 23 | 24 | JsonToken Token { get; } 25 | object RawValue { get; } 26 | IValueInfo Value { get; } 27 | 28 | bool NextToken(); 29 | 30 | bool IsEndOfStream(); 31 | 32 | /// 33 | /// Resets Line/Column numbers, CharactersRead and Token information of reader 34 | /// 35 | void Reset(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/IJsonWriter.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | 18 | // ReSharper disable once CheckNamespace 19 | namespace GameDevWare.Serialization 20 | { 21 | public interface IJsonWriter 22 | { 23 | SerializationContext Context { get; } 24 | 25 | void Flush(); 26 | 27 | void Write(string value); 28 | void Write(JsonMember value); 29 | void Write(int number); 30 | void Write(uint number); 31 | void Write(long number); 32 | void Write(ulong number); 33 | void Write(float number); 34 | void Write(double number); 35 | void Write(decimal number); 36 | void Write(bool value); 37 | void Write(DateTime dateTime); 38 | void Write(DateTimeOffset dateTimeOffset); 39 | void WriteObjectBegin(int numberOfMembers); 40 | void WriteObjectEnd(); 41 | void WriteArrayBegin(int numberOfMembers); 42 | void WriteArrayEnd(); 43 | void WriteNull(); 44 | 45 | void WriteJson(string jsonString); 46 | void WriteJson(char[] jsonString, int index, int charCount); 47 | 48 | void Reset(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/IValueInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | // ReSharper disable once CheckNamespace 4 | namespace GameDevWare.Serialization 5 | { 6 | public interface IValueInfo 7 | { 8 | bool HasValue { get; } 9 | object Raw { get; } 10 | Type Type { get; } 11 | bool AsBoolean { get; } 12 | byte AsByte { get; } 13 | short AsInt16 { get; } 14 | int AsInt32 { get; } 15 | long AsInt64 { get; } 16 | sbyte AsSByte { get; } 17 | ushort AsUInt16 { get; } 18 | uint AsUInt32 { get; } 19 | ulong AsUInt64 { get; } 20 | float AsSingle { get; } 21 | double AsDouble { get; } 22 | decimal AsDecimal { get; } 23 | string AsString { get; } 24 | DateTime AsDateTime { get; } 25 | 26 | int LineNumber { get; } 27 | int ColumnNumber { get; } 28 | } 29 | } -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/JsonMember.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Linq; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization 21 | { 22 | public struct JsonMember : IEquatable, IEquatable 23 | { 24 | internal string NameString; 25 | internal char[] NameChars; 26 | internal bool IsEscapedAndQuoted; 27 | 28 | public int Length 29 | { 30 | get { return this.NameString != null ? this.NameString.Length : this.NameChars.Length; } 31 | } 32 | 33 | public JsonMember(string name) 34 | : this(name, false) 35 | { 36 | } 37 | 38 | public JsonMember(string name, bool escapedAndQuoted) 39 | { 40 | if (name == null) 41 | throw new ArgumentNullException("name"); 42 | 43 | this.NameString = name; 44 | this.IsEscapedAndQuoted = escapedAndQuoted; 45 | this.NameChars = null; 46 | } 47 | 48 | public JsonMember(char[] name) 49 | : this(name, false) 50 | { 51 | } 52 | 53 | public JsonMember(char[] name, bool escapedAndQuoted) 54 | { 55 | if (name == null) 56 | throw new ArgumentNullException("name"); 57 | 58 | this.NameChars = name; 59 | this.IsEscapedAndQuoted = escapedAndQuoted; 60 | this.NameString = null; 61 | } 62 | 63 | public override int GetHashCode() 64 | { 65 | return this.NameString != null ? this.NameString.GetHashCode() : this.NameChars.Aggregate(0, (a, c) => a ^ (int) c); 66 | } 67 | 68 | public override bool Equals(object obj) 69 | { 70 | if (obj is JsonMember) 71 | return this.Equals((JsonMember) obj); 72 | else if (obj is string) 73 | return this.Equals((string) obj); 74 | else 75 | return false; 76 | } 77 | 78 | public bool Equals(JsonMember other) 79 | { 80 | return this.ToString().Equals(other.ToString(), StringComparison.Ordinal); 81 | } 82 | 83 | public bool Equals(string other) 84 | { 85 | return this.ToString().Equals(other, StringComparison.Ordinal); 86 | } 87 | 88 | public static explicit operator string(JsonMember member) 89 | { 90 | return member.ToString(); 91 | } 92 | 93 | public static explicit operator JsonMember(string memberName) 94 | { 95 | return new JsonMember(memberName); 96 | } 97 | 98 | public override string ToString() 99 | { 100 | var name = NameString; 101 | if (this.NameChars != null) 102 | name = new string(NameChars, 0, NameChars.Length); 103 | 104 | // this is used in tests, so perf is not primary 105 | if (this.IsEscapedAndQuoted) 106 | { 107 | if (name.EndsWith(":")) 108 | name = name.Substring(0, name.Length - 1); 109 | 110 | name = JsonUtils.UnescapeAndUnquote(name); 111 | } 112 | 113 | return name; 114 | } 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/JsonStreamReader.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.IO; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization 21 | { 22 | public sealed class JsonStreamReader : JsonReader 23 | { 24 | private readonly StreamReader reader; 25 | 26 | public JsonStreamReader(Stream stream, SerializationContext context, char[] buffer = null) 27 | : base(context, buffer) 28 | { 29 | if (stream == null) throw new ArgumentNullException("stream"); 30 | if (!stream.CanRead) throw JsonSerializationException.StreamIsNotReadable(); 31 | 32 | this.reader = new StreamReader(stream, context.Encoding); 33 | } 34 | 35 | protected override int FillBuffer(char[] buffer, int index) 36 | { 37 | if (buffer == null) 38 | throw new ArgumentNullException("buffer"); 39 | if (index < 0 || index >= buffer.Length) 40 | throw new ArgumentOutOfRangeException("index"); 41 | 42 | 43 | var count = buffer.Length - index; 44 | if (count <= 0) 45 | return index; 46 | 47 | var read = this.reader.Read(buffer, index, count); 48 | return index + read; 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/JsonStreamWriter.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.IO; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization 21 | { 22 | public sealed class JsonStreamWriter : JsonWriter 23 | { 24 | private readonly StreamWriter writer; 25 | 26 | public Stream Stream { get { return writer.BaseStream; } } 27 | 28 | public JsonStreamWriter(Stream stream, SerializationContext context, char[] buffer = null) 29 | : base(context, buffer) 30 | { 31 | if (stream == null) throw new ArgumentNullException("stream"); 32 | if (!stream.CanWrite) throw JsonSerializationException.StreamIsNotWriteable(); 33 | 34 | 35 | writer = new StreamWriter(stream, context.Encoding); 36 | } 37 | 38 | public override void Flush() 39 | { 40 | writer.Flush(); 41 | } 42 | 43 | public override void WriteJson(string jsonString) 44 | { 45 | if (jsonString == null) 46 | throw new ArgumentNullException("jsonString"); 47 | 48 | 49 | writer.Write(jsonString); 50 | this.CharactersWritten += jsonString.Length; 51 | } 52 | 53 | public override void WriteJson(char[] jsonString, int index, int charactersToWrite) 54 | { 55 | if (jsonString == null) 56 | throw new ArgumentNullException("jsonString"); 57 | if (index < 0 || index >= jsonString.Length) 58 | throw new ArgumentOutOfRangeException("index"); 59 | if (charactersToWrite < 0 || index + charactersToWrite > jsonString.Length) 60 | throw new ArgumentOutOfRangeException("charactersToWrite"); 61 | 62 | 63 | if (charactersToWrite == 0) 64 | return; 65 | 66 | writer.Write(jsonString, index, charactersToWrite); 67 | this.CharactersWritten += charactersToWrite; 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/JsonStringBuilderReader.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Text; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization 21 | { 22 | public sealed class JsonStringBuilderReader : JsonReader 23 | { 24 | private readonly StringBuilder jsonString; 25 | private int position; 26 | 27 | public JsonStringBuilderReader(StringBuilder stringBuilder, SerializationContext context, char[] buffer = null) 28 | : base(context, buffer) 29 | { 30 | if (stringBuilder == null) 31 | throw new ArgumentNullException("str"); 32 | 33 | 34 | this.jsonString = stringBuilder; 35 | this.position = 0; 36 | } 37 | 38 | protected override int FillBuffer(char[] buffer, int index) 39 | { 40 | if (buffer == null) 41 | throw new ArgumentNullException("buffer"); 42 | if (index < 0 || index >= buffer.Length) 43 | throw new ArgumentOutOfRangeException("index"); 44 | 45 | 46 | var block = Math.Min(this.jsonString.Length - position, buffer.Length - index); 47 | if (block <= 0) 48 | return index; 49 | 50 | jsonString.CopyTo(position, buffer, index, block); 51 | 52 | position += block; 53 | 54 | return index + block; 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/JsonStringBuilderWriter.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Text; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization 21 | { 22 | public sealed class JsonStringBuilderWriter : JsonWriter 23 | { 24 | private readonly StringBuilder stringBuilder; 25 | 26 | public StringBuilder Builder 27 | { 28 | get { return stringBuilder; } 29 | } 30 | 31 | public JsonStringBuilderWriter(StringBuilder stringBuilder, SerializationContext context, char[] buffer = null) 32 | : base(context, buffer) 33 | { 34 | if (stringBuilder == null) 35 | throw new ArgumentNullException("builder"); 36 | 37 | 38 | this.stringBuilder = stringBuilder; 39 | } 40 | 41 | 42 | public override void Flush() 43 | { 44 | } 45 | 46 | public override void WriteJson(string jsonString) 47 | { 48 | if (jsonString == null) 49 | throw new ArgumentNullException("jsonString"); 50 | 51 | 52 | stringBuilder.Append(jsonString); 53 | this.CharactersWritten += jsonString.Length; 54 | } 55 | 56 | public override void WriteJson(char[] jsonString, int offset, int charactersToWrite) 57 | { 58 | if (jsonString == null) 59 | throw new ArgumentNullException("jsonString"); 60 | if (offset < 0 || offset >= jsonString.Length) 61 | throw new ArgumentOutOfRangeException("offset"); 62 | if (charactersToWrite < 0 || offset + charactersToWrite > jsonString.Length) 63 | throw new ArgumentOutOfRangeException("charactersToWrite"); 64 | 65 | 66 | if (charactersToWrite == 0) 67 | return; 68 | 69 | stringBuilder.Append(jsonString, offset, charactersToWrite); 70 | this.CharactersWritten += charactersToWrite; 71 | } 72 | 73 | public override string ToString() 74 | { 75 | return stringBuilder.ToString(); 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/JsonStringReader.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | 18 | // ReSharper disable once CheckNamespace 19 | namespace GameDevWare.Serialization 20 | { 21 | public sealed class JsonStringReader : JsonReader 22 | { 23 | private readonly string jsonString; 24 | private int position; 25 | 26 | public JsonStringReader(string jsonString, SerializationContext context, char[] buffer = null) 27 | : base(context, buffer) 28 | { 29 | if (jsonString == null) 30 | throw new ArgumentNullException("jsonString"); 31 | 32 | 33 | this.jsonString = jsonString; 34 | this.position = 0; 35 | } 36 | 37 | protected override int FillBuffer(char[] buffer, int index) 38 | { 39 | if (buffer == null) 40 | throw new ArgumentNullException("buffer"); 41 | if (index < 0 || index >= buffer.Length) 42 | throw new ArgumentOutOfRangeException("index"); 43 | 44 | 45 | var block = Math.Min(this.jsonString.Length - this.position, buffer.Length - index); 46 | if (block <= 0) 47 | return index; 48 | 49 | this.jsonString.CopyTo(this.position, buffer, index, block); 50 | 51 | this.position += block; 52 | 53 | return index + block; 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/JsonTextReader.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.IO; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization 21 | { 22 | public sealed class JsonTextReader : JsonReader 23 | { 24 | private readonly TextReader reader; 25 | 26 | public JsonTextReader(TextReader reader, SerializationContext context, char[] buffer = null) 27 | : base(context, buffer) 28 | { 29 | if (reader == null) 30 | throw new ArgumentNullException("reader"); 31 | 32 | 33 | this.reader = reader; 34 | } 35 | 36 | protected override int FillBuffer(char[] buffer, int index) 37 | { 38 | if (buffer == null) 39 | throw new ArgumentNullException("buffer"); 40 | if (index < 0 || index >= buffer.Length) 41 | throw new ArgumentOutOfRangeException("index"); 42 | 43 | 44 | var count = buffer.Length - index; 45 | if (count <= 0) 46 | return index; 47 | 48 | var read = this.reader.Read(buffer, index, count); 49 | return index + read; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/JsonTextWriter.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.IO; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization 21 | { 22 | public sealed class JsonTextWriter : JsonWriter 23 | { 24 | private readonly TextWriter writer; 25 | 26 | private TextWriter Writer 27 | { 28 | get { return writer; } 29 | } 30 | 31 | public JsonTextWriter(TextWriter writer, SerializationContext context, char[] buffer = null) 32 | : base(context, buffer) 33 | { 34 | if (writer == null) 35 | throw new ArgumentNullException("writer"); 36 | 37 | 38 | this.writer = writer; 39 | } 40 | 41 | public override void Flush() 42 | { 43 | writer.Flush(); 44 | } 45 | 46 | public override void WriteJson(string jsonString) 47 | { 48 | if (jsonString == null) 49 | throw new ArgumentNullException("jsonString"); 50 | 51 | 52 | writer.Write(jsonString); 53 | this.CharactersWritten += jsonString.Length; 54 | } 55 | 56 | public override void WriteJson(char[] jsonString, int offset, int charactersToWrite) 57 | { 58 | if (jsonString == null) 59 | throw new ArgumentNullException("jsonString"); 60 | if (offset < 0 || offset >= jsonString.Length) 61 | throw new ArgumentOutOfRangeException("offset"); 62 | if (charactersToWrite < 0 || offset + charactersToWrite > jsonString.Length) 63 | throw new ArgumentOutOfRangeException("charactersToWrite"); 64 | 65 | 66 | if (charactersToWrite == 0) 67 | return; 68 | 69 | writer.Write(jsonString, offset, charactersToWrite); 70 | this.CharactersWritten += charactersToWrite; 71 | } 72 | 73 | public override string ToString() 74 | { 75 | return writer.ToString(); 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/JsonToken.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | 17 | // ReSharper disable once CheckNamespace 18 | namespace GameDevWare.Serialization 19 | { 20 | public enum JsonToken 21 | { 22 | None = 0, 23 | BeginArray, 24 | EndOfArray, 25 | BeginObject, 26 | EndOfObject, 27 | Member, 28 | Number, 29 | StringLiteral, 30 | DateTime, 31 | Null, 32 | Boolean, 33 | EndOfStream 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/MessagePack/BigEndianBitConverter.cs: -------------------------------------------------------------------------------- 1 | // 2 | /* 3 | "Miscellaneous Utility Library" Software Licence 4 | 5 | Version 1.0 6 | 7 | Copyright (c) 2004-2008 Jon Skeet and Marc Gravell. 8 | All rights reserved. 9 | 10 | Redistribution and use in source and binary forms, with or without 11 | modification, are permitted provided that the following conditions 12 | are met: 13 | 14 | 1. Redistributions of source code must retain the above copyright 15 | notice, this list of conditions and the following disclaimer. 16 | 17 | 2. Redistributions in binary form must reproduce the above copyright 18 | notice, this list of conditions and the following disclaimer in the 19 | documentation and/or other materials provided with the distribution. 20 | 21 | 3. The end-user documentation included with the redistribution, if 22 | any, must include the following acknowledgment: 23 | 24 | "This product includes software developed by Jon Skeet 25 | and Marc Gravell. Contact skeet@pobox.com, or see 26 | http://www.pobox.com/~skeet/)." 27 | 28 | Alternately, this acknowledgment may appear in the software itself, 29 | if and wherever such third-party acknowledgments normally appear. 30 | 31 | 4. The name "Miscellaneous Utility Library" must not be used to endorse 32 | or promote products derived from this software without prior written 33 | permission. For written permission, please contact skeet@pobox.com. 34 | 35 | 5. Products derived from this software may not be called 36 | "Miscellaneous Utility Library", nor may "Miscellaneous Utility Library" 37 | appear in their name, without prior written permission of Jon Skeet. 38 | 39 | THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED 40 | WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 41 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 42 | IN NO EVENT SHALL JON SKEET BE LIABLE FOR ANY DIRECT, INDIRECT, 43 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 44 | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 45 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 46 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 47 | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 48 | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 49 | POSSIBILITY OF SUCH DAMAGE. 50 | */ 51 | 52 | // ReSharper disable once CheckNamespace 53 | namespace GameDevWare.Serialization.MessagePack 54 | { 55 | /// 56 | /// Implementation of EndianBitConverter which converts to/from big-endian 57 | /// byte arrays. 58 | /// 59 | internal sealed class BigEndianBitConverter : EndianBitConverter 60 | { 61 | /// 62 | /// Indicates the byte order ("endianess") in which data is converted using this class. 63 | /// 64 | /// 65 | /// Different computer architectures store data using different byte orders. "Big-endian" 66 | /// means the most significant byte is on the left end of a word. "Little-endian" means the 67 | /// most significant byte is on the right end of a word. 68 | /// 69 | /// true if this converter is little-endian, false otherwise. 70 | public override sealed bool IsLittleEndian() 71 | { 72 | return false; 73 | } 74 | 75 | /// 76 | /// Indicates the byte order ("endianess") in which data is converted using this class. 77 | /// 78 | public override sealed Endianness Endianness 79 | { 80 | get { return Endianness.BigEndian; } 81 | } 82 | 83 | /// 84 | /// Copies the specified number of bytes from value to buffer, starting at index. 85 | /// 86 | /// The value to copy 87 | /// The number of bytes to copy 88 | /// The buffer to copy the bytes into 89 | /// The index to start at 90 | protected override void CopyBytesImpl(long value, int bytes, byte[] buffer, int index) 91 | { 92 | var endOffset = index + bytes - 1; 93 | for (var i = 0; i < bytes; i++) 94 | { 95 | buffer[endOffset - i] = unchecked((byte) (value & 0xff)); 96 | value = value >> 8; 97 | } 98 | } 99 | 100 | /// 101 | /// Returns a value built from the specified number of bytes from the given buffer, 102 | /// starting at index. 103 | /// 104 | /// The data in byte array format 105 | /// The first index to use 106 | /// The number of bytes to use 107 | /// The value built from the given bytes 108 | protected override long FromBytes(byte[] buffer, int startIndex, int bytesToConvert) 109 | { 110 | long ret = 0; 111 | for (var i = 0; i < bytesToConvert; i++) 112 | { 113 | ret = unchecked((ret << 8) | buffer[startIndex + i]); 114 | } 115 | return ret; 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/MessagePack/Endianness.cs: -------------------------------------------------------------------------------- 1 | // 2 | /* 3 | "Miscellaneous Utility Library" Software Licence 4 | 5 | Version 1.0 6 | 7 | Copyright (c) 2004-2008 Jon Skeet and Marc Gravell. 8 | All rights reserved. 9 | 10 | Redistribution and use in source and binary forms, with or without 11 | modification, are permitted provided that the following conditions 12 | are met: 13 | 14 | 1. Redistributions of source code must retain the above copyright 15 | notice, this list of conditions and the following disclaimer. 16 | 17 | 2. Redistributions in binary form must reproduce the above copyright 18 | notice, this list of conditions and the following disclaimer in the 19 | documentation and/or other materials provided with the distribution. 20 | 21 | 3. The end-user documentation included with the redistribution, if 22 | any, must include the following acknowledgment: 23 | 24 | "This product includes software developed by Jon Skeet 25 | and Marc Gravell. Contact skeet@pobox.com, or see 26 | http://www.pobox.com/~skeet/)." 27 | 28 | Alternately, this acknowledgment may appear in the software itself, 29 | if and wherever such third-party acknowledgments normally appear. 30 | 31 | 4. The name "Miscellaneous Utility Library" must not be used to endorse 32 | or promote products derived from this software without prior written 33 | permission. For written permission, please contact skeet@pobox.com. 34 | 35 | 5. Products derived from this software may not be called 36 | "Miscellaneous Utility Library", nor may "Miscellaneous Utility Library" 37 | appear in their name, without prior written permission of Jon Skeet. 38 | 39 | THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED 40 | WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 41 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 42 | IN NO EVENT SHALL JON SKEET BE LIABLE FOR ANY DIRECT, INDIRECT, 43 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 44 | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 45 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 46 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 47 | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 48 | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 49 | POSSIBILITY OF SUCH DAMAGE. 50 | */ 51 | 52 | // ReSharper disable once CheckNamespace 53 | namespace GameDevWare.Serialization.MessagePack 54 | { 55 | /// 56 | /// Endianness of a converter 57 | /// 58 | public enum Endianness 59 | { 60 | /// 61 | /// Little endian - least significant byte first 62 | /// 63 | LittleEndian, 64 | 65 | /// 66 | /// Big endian - most significant byte first 67 | /// 68 | BigEndian 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/MessagePack/LittleEndianBitConverter.cs: -------------------------------------------------------------------------------- 1 | // 2 | /* 3 | "Miscellaneous Utility Library" Software Licence 4 | 5 | Version 1.0 6 | 7 | Copyright (c) 2004-2008 Jon Skeet and Marc Gravell. 8 | All rights reserved. 9 | 10 | Redistribution and use in source and binary forms, with or without 11 | modification, are permitted provided that the following conditions 12 | are met: 13 | 14 | 1. Redistributions of source code must retain the above copyright 15 | notice, this list of conditions and the following disclaimer. 16 | 17 | 2. Redistributions in binary form must reproduce the above copyright 18 | notice, this list of conditions and the following disclaimer in the 19 | documentation and/or other materials provided with the distribution. 20 | 21 | 3. The end-user documentation included with the redistribution, if 22 | any, must include the following acknowledgment: 23 | 24 | "This product includes software developed by Jon Skeet 25 | and Marc Gravell. Contact skeet@pobox.com, or see 26 | http://www.pobox.com/~skeet/)." 27 | 28 | Alternately, this acknowledgment may appear in the software itself, 29 | if and wherever such third-party acknowledgments normally appear. 30 | 31 | 4. The name "Miscellaneous Utility Library" must not be used to endorse 32 | or promote products derived from this software without prior written 33 | permission. For written permission, please contact skeet@pobox.com. 34 | 35 | 5. Products derived from this software may not be called 36 | "Miscellaneous Utility Library", nor may "Miscellaneous Utility Library" 37 | appear in their name, without prior written permission of Jon Skeet. 38 | 39 | THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED 40 | WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 41 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 42 | IN NO EVENT SHALL JON SKEET BE LIABLE FOR ANY DIRECT, INDIRECT, 43 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 44 | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 45 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 46 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 47 | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 48 | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 49 | POSSIBILITY OF SUCH DAMAGE. 50 | */ 51 | 52 | // ReSharper disable once CheckNamespace 53 | namespace GameDevWare.Serialization.MessagePack 54 | { 55 | /// 56 | /// Implementation of EndianBitConverter which converts to/from little-endian 57 | /// byte arrays. 58 | /// 59 | internal sealed class LittleEndianBitConverter : EndianBitConverter 60 | { 61 | /// 62 | /// Indicates the byte order ("endianess") in which data is converted using this class. 63 | /// 64 | /// 65 | /// Different computer architectures store data using different byte orders. "Big-endian" 66 | /// means the most significant byte is on the left end of a word. "Little-endian" means the 67 | /// most significant byte is on the right end of a word. 68 | /// 69 | /// true if this converter is little-endian, false otherwise. 70 | public override sealed bool IsLittleEndian() 71 | { 72 | return true; 73 | } 74 | 75 | /// 76 | /// Indicates the byte order ("endianess") in which data is converted using this class. 77 | /// 78 | public override sealed Endianness Endianness 79 | { 80 | get { return Endianness.LittleEndian; } 81 | } 82 | 83 | /// 84 | /// Copies the specified number of bytes from value to buffer, starting at index. 85 | /// 86 | /// The value to copy 87 | /// The number of bytes to copy 88 | /// The buffer to copy the bytes into 89 | /// The index to start at 90 | protected override void CopyBytesImpl(long value, int bytes, byte[] buffer, int index) 91 | { 92 | for (var i = 0; i < bytes; i++) 93 | { 94 | buffer[i + index] = unchecked((byte) (value & 0xff)); 95 | value = value >> 8; 96 | } 97 | } 98 | 99 | /// 100 | /// Returns a value built from the specified number of bytes from the given buffer, 101 | /// starting at index. 102 | /// 103 | /// The data in byte array format 104 | /// The first index to use 105 | /// The number of bytes to use 106 | /// The value built from the given bytes 107 | protected override long FromBytes(byte[] buffer, int startIndex, int bytesToConvert) 108 | { 109 | long ret = 0; 110 | for (var i = 0; i < bytesToConvert; i++) 111 | { 112 | ret = unchecked((ret << 8) | buffer[startIndex + bytesToConvert - 1 - i]); 113 | } 114 | return ret; 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/MessagePack/MsgPackExtensionType.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using GameDevWare.Serialization.Serializers; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization.MessagePack 21 | { 22 | /// 23 | /// Representation of extension types in Message Pack. This type is immutable by design 24 | /// 25 | [TypeSerializer(typeof(MsgPackExtensionTypeSerializer))] 26 | public sealed class MessagePackExtensionType : IEquatable, IComparable, IComparable 27 | { 28 | private static readonly byte[] EmptyBytes = new byte[0]; 29 | 30 | private readonly ArraySegment data; 31 | private readonly int hashCode; 32 | 33 | public int Length 34 | { 35 | get { return this.data.Count; } 36 | } 37 | public sbyte Type { get; private set; } 38 | 39 | // ReSharper disable PossibleNullReferenceException 40 | public byte this[int index] 41 | { 42 | get { return this.data.Array[this.data.Offset + index]; } 43 | } 44 | 45 | // ReSharper restore PossibleNullReferenceException 46 | 47 | public MessagePackExtensionType() 48 | { 49 | this.Type = 0; // generic binary 50 | this.data = new ArraySegment(EmptyBytes, 0, 0); 51 | } 52 | public MessagePackExtensionType(byte[] binaryData) 53 | : this(0, binaryData) { } 54 | public MessagePackExtensionType(sbyte type, byte[] binaryData) 55 | : this(type, new ArraySegment(binaryData, 0, binaryData.Length)) 56 | { 57 | } 58 | public MessagePackExtensionType(sbyte type, ArraySegment binaryData) 59 | { 60 | if (binaryData.Array == null) throw new ArgumentNullException("binaryData"); 61 | 62 | this.data = binaryData; 63 | this.Type = type; 64 | 65 | var buffer = this.data.Array ?? EmptyBytes; 66 | if (this.data.Count >= 4) 67 | { 68 | this.hashCode = unchecked(this.data.Count * 17 + BitConverter.ToInt32(buffer, this.data.Offset)); 69 | } 70 | else 71 | { 72 | this.hashCode = this.data.Count; 73 | for (var i = this.data.Offset; i < this.data.Offset + this.data.Count; i++) 74 | this.hashCode += unchecked(buffer[i] * 114); 75 | } 76 | } 77 | 78 | public void CopyTo(byte[] destination, int index, int bytesToCopy) 79 | { 80 | Buffer.BlockCopy(this.data.Array ?? EmptyBytes, this.data.Offset, destination, index, Math.Min(bytesToCopy, this.Length)); 81 | } 82 | public byte[] ToByteArray() 83 | { 84 | if (this.data.Offset != 0 || this.Length != this.data.Count) 85 | { 86 | var byteArray = new byte[this.Length]; 87 | Buffer.BlockCopy(this.data.Array ?? EmptyBytes, this.data.Offset, byteArray, 0, byteArray.Length); 88 | return byteArray; 89 | } 90 | 91 | return this.data.Array; 92 | } 93 | public ArraySegment ToArraySegment() 94 | { 95 | return this.data; 96 | } 97 | public string ToBase64() 98 | { 99 | return Convert.ToBase64String(this.data.Array ?? EmptyBytes, this.data.Offset, this.Length); 100 | } 101 | 102 | public override bool Equals(object obj) 103 | { 104 | return this.Equals(obj as MessagePackExtensionType); 105 | } 106 | public override int GetHashCode() 107 | { 108 | return this.hashCode; 109 | } 110 | 111 | public bool Equals(MessagePackExtensionType other) 112 | { 113 | if (other == null) return false; 114 | if (ReferenceEquals(this, other)) return true; 115 | 116 | if (this.Length != other.Length) return false; 117 | if (this.GetHashCode() != other.GetHashCode()) return false; 118 | 119 | for (var i = 0; i < this.Length; i++) 120 | { 121 | if (this[i] != other[i]) return false; 122 | } 123 | 124 | return true; 125 | } 126 | public int CompareTo(object obj) 127 | { 128 | return this.CompareTo(obj as MessagePackExtensionType); 129 | } 130 | public int CompareTo(MessagePackExtensionType other) 131 | { 132 | if (other == null) return 1; 133 | 134 | // wee need to align buffers with different sizes 135 | for (int i = 0, j = 0; i < this.Length || j < other.Length; i++, j++) 136 | { 137 | // we need offsets 138 | var io = this.Length - other.Length; 139 | var jo = other.Length - this.Length; 140 | 141 | // only negative offset is needed 142 | if (io > 0) io = 0; 143 | if (jo > 0) jo = 0; 144 | 145 | // get bytes with offsets 146 | var ib = i + io >= 0 ? this[i + io] : (byte)0; 147 | var jb = j + jo >= 0 ? other[j + jo] : (byte)0; 148 | 149 | // compare 150 | if (ib > jb) return 1; 151 | 152 | if (jb > ib) return -1; 153 | } 154 | 155 | return 0; 156 | } 157 | 158 | public static bool operator ==(MessagePackExtensionType a, MessagePackExtensionType b) 159 | { 160 | if (ReferenceEquals(a, null) && ReferenceEquals(b, null)) return false; 161 | if (ReferenceEquals(a, null) || ReferenceEquals(b, null)) return false; 162 | 163 | return a.Equals(b); 164 | } 165 | public static bool operator !=(MessagePackExtensionType a, MessagePackExtensionType b) 166 | { 167 | return !(a == b); 168 | } 169 | 170 | public static explicit operator byte[] (MessagePackExtensionType messagePackExtension) 171 | { 172 | if (messagePackExtension != null) 173 | return messagePackExtension.ToByteArray(); 174 | else 175 | return null; 176 | } 177 | public static explicit operator ArraySegment(MessagePackExtensionType messagePackExtension) 178 | { 179 | if (messagePackExtension == null) throw new ArgumentNullException("messagePackExtension"); 180 | return messagePackExtension.ToArraySegment(); 181 | } 182 | 183 | public override string ToString() 184 | { 185 | return Convert.ToBase64String(this.data.Array ?? EmptyBytes, this.data.Offset, Math.Min(this.Length, 64)) + ( this.Length > 64 ? "..." : ""); 186 | } 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/MessagePack/MsgPackExtensionTypeHandler.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Collections.Generic; 18 | using System.Linq; 19 | 20 | // ReSharper disable once CheckNamespace 21 | namespace GameDevWare.Serialization.MessagePack 22 | { 23 | public abstract class MessagePackExtensionTypeHandler 24 | { 25 | public abstract IEnumerable ExtensionTypes { get; } 26 | 27 | public abstract bool TryRead(sbyte type, ArraySegment data, out object value); 28 | public abstract bool TryWrite(object value, out sbyte type, ref ArraySegment data); 29 | 30 | /// 31 | public override string ToString() 32 | { 33 | return string.Format("Extension Types: {0}", string.Join(", ", this.ExtensionTypes.Select(t => t.ToString()).ToArray())); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/MessagePack/MsgPackTimestamp.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using GameDevWare.Serialization.Serializers; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization.MessagePack 21 | { 22 | [TypeSerializer(typeof(MsgPackTimestampSerializer))] 23 | public struct MessagePackTimestamp : IEquatable, IComparable 24 | { 25 | public const int MAX_NANO_SECONDS = 999999999; 26 | 27 | public readonly long Seconds; 28 | public readonly uint NanoSeconds; 29 | 30 | public MessagePackTimestamp(long seconds, uint nanoSeconds) 31 | { 32 | if (nanoSeconds > MAX_NANO_SECONDS) 33 | nanoSeconds = MAX_NANO_SECONDS; 34 | 35 | this.Seconds = seconds; 36 | this.NanoSeconds = nanoSeconds; 37 | } 38 | 39 | public static explicit operator DateTime(MessagePackTimestamp timestamp) 40 | { 41 | return new DateTime(JsonUtils.UnixEpochTicks + ((TimeSpan)timestamp).Ticks, DateTimeKind.Unspecified); 42 | } 43 | public static explicit operator TimeSpan(MessagePackTimestamp timestamp) 44 | { 45 | return TimeSpan.FromSeconds(timestamp.Seconds) + TimeSpan.FromTicks(timestamp.NanoSeconds / 100); 46 | } 47 | 48 | /// 49 | public override int GetHashCode() 50 | { 51 | return unchecked(this.Seconds.GetHashCode() * 17 + this.NanoSeconds.GetHashCode()); 52 | } 53 | /// 54 | public override bool Equals(object obj) 55 | { 56 | if (obj is MessagePackTimestamp) 57 | return this.Equals((MessagePackTimestamp)obj); 58 | else 59 | return false; 60 | } 61 | /// 62 | public bool Equals(MessagePackTimestamp other) 63 | { 64 | return this.Seconds.Equals(other.Seconds) && this.NanoSeconds.Equals(other.NanoSeconds); 65 | } 66 | /// 67 | public int CompareTo(MessagePackTimestamp other) 68 | { 69 | var cmp = this.Seconds.CompareTo(other.Seconds); 70 | if (cmp != 0) 71 | return cmp; 72 | return this.NanoSeconds.CompareTo(other.NanoSeconds); 73 | } 74 | 75 | public static bool operator >(MessagePackTimestamp a, MessagePackTimestamp b) 76 | { 77 | return a.CompareTo(b) == 1; 78 | } 79 | public static bool operator <(MessagePackTimestamp a, MessagePackTimestamp b) 80 | { 81 | return a.CompareTo(b) == -1; 82 | } 83 | public static bool operator >=(MessagePackTimestamp a, MessagePackTimestamp b) 84 | { 85 | return a.CompareTo(b) != -1; 86 | } 87 | public static bool operator <=(MessagePackTimestamp a, MessagePackTimestamp b) 88 | { 89 | return a.CompareTo(b) != 1; 90 | } 91 | public static bool operator ==(MessagePackTimestamp a, MessagePackTimestamp b) 92 | { 93 | return a.Equals(b); 94 | } 95 | public static bool operator !=(MessagePackTimestamp a, MessagePackTimestamp b) 96 | { 97 | return !a.Equals(b); 98 | } 99 | 100 | /// 101 | public override string ToString() 102 | { 103 | return string.Format("seconds: {0}, nanoseconds: {1}", this.Seconds, this.NanoSeconds); 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/MessagePack/MsgPackType.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | 17 | // ReSharper disable once CheckNamespace 18 | namespace GameDevWare.Serialization.MessagePack 19 | { 20 | public enum MsgPackType : byte 21 | { 22 | PositiveFixIntStart = 0x00, 23 | PositiveFixIntEnd = 0x7f, 24 | FixMapStart = 0x80, 25 | FixMapEnd = 0x8f, 26 | FixArrayStart = 0x90, 27 | FixArrayEnd = 0x9f, 28 | FixStrStart = 0xa0, 29 | FixStrEnd = 0xbf, 30 | Nil = 0xc0, 31 | Unused = 0xc1, 32 | False = 0xc2, 33 | True = 0xc3, 34 | Bin8 = 0xc4, 35 | Bin16 = 0xc5, 36 | Bin32 = 0xc6, 37 | Ext8 = 0xc7, 38 | Ext16 = 0xc8, 39 | Ext32 = 0xc9, 40 | Float32 = 0xca, 41 | Float64 = 0xcb, 42 | UInt8 = 0xcc, 43 | UInt16 = 0xcd, 44 | UInt32 = 0xce, 45 | UInt64 = 0xcf, 46 | Int8 = 0xd0, 47 | Int16 = 0xd1, 48 | Int32 = 0xd2, 49 | Int64 = 0xd3, 50 | FixExt1 = 0xd4, 51 | FixExt2 = 0xd5, 52 | FixExt4 = 0xd6, 53 | FixExt8 = 0xd7, 54 | FixExt16 = 0xd8, 55 | Str8 = 0xd9, 56 | Str16 = 0xda, 57 | Str32 = 0xdb, 58 | Array16 = 0xdc, 59 | Array32 = 0xdd, 60 | Map16 = 0xde, 61 | Map32 = 0xdf, 62 | NegativeFixIntStart = 0xe0, 63 | NegativeFixIntEnd = 0xff 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/MessagePack/UnknownMsgPackExtentionTypeException.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Runtime.Serialization; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization.MessagePack 21 | { 22 | [Serializable] 23 | public sealed class UnknownMsgPackExtentionTypeException : SerializationException 24 | { 25 | public UnknownMsgPackExtentionTypeException(string message, Exception innerException) : base(message, innerException) 26 | { 27 | } 28 | 29 | public UnknownMsgPackExtentionTypeException(string message) : base(message) 30 | { 31 | } 32 | 33 | public UnknownMsgPackExtentionTypeException(sbyte invalidExtType) 34 | : base(string.Format("Unknown MessagePack extention type '{0}' was readed from stream.", invalidExtType)) 35 | { 36 | } 37 | 38 | private UnknownMsgPackExtentionTypeException(SerializationInfo info, StreamingContext context) 39 | : base(info, context) 40 | { 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/MessagePack/UnknownMsgPackFormatException.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Runtime.Serialization; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization.MessagePack 21 | { 22 | [Serializable] 23 | public sealed class UnknownMsgPackFormatException : SerializationException 24 | { 25 | public UnknownMsgPackFormatException(string message, Exception innerException) : base(message, innerException) 26 | { 27 | } 28 | 29 | public UnknownMsgPackFormatException(string message) : base(message) 30 | { 31 | } 32 | 33 | public UnknownMsgPackFormatException(byte invalidValue) 34 | : base(string.Format("Unknown MessagePack format '{0}' was readed from stream.", invalidValue)) 35 | { 36 | } 37 | 38 | #if !NETSTANDARD 39 | private UnknownMsgPackFormatException(SerializationInfo info, StreamingContext context) 40 | : base(info, context) 41 | { 42 | } 43 | #endif 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Metadata/DataMemberDescription.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.ComponentModel; 18 | using System.Linq; 19 | using System.Reflection; 20 | 21 | // ReSharper disable once CheckNamespace 22 | namespace GameDevWare.Serialization.Metadata 23 | { 24 | internal abstract class DataMemberDescription : MemberDescription 25 | { 26 | public abstract bool CanGet { get; } 27 | public abstract bool CanSet { get; } 28 | public object DefaultValue { get; private set; } 29 | public abstract Type ValueType { get; } 30 | 31 | protected DataMemberDescription(TypeDescription typeDescription, MemberInfo member) 32 | : base(typeDescription, member) 33 | { 34 | var defaultValue = 35 | (DefaultValueAttribute) this.GetAttributesOrEmptyList(typeof (DefaultValueAttribute)).FirstOrDefault(); 36 | if (defaultValue != null) 37 | this.DefaultValue = defaultValue.Value; 38 | } 39 | 40 | public abstract object GetValue(object target); 41 | public abstract void SetValue(object target, object value); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Metadata/FieldDescription.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Reflection; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization.Metadata 21 | { 22 | internal sealed class FieldDescription : DataMemberDescription 23 | { 24 | private readonly FieldInfo fieldInfo; 25 | private readonly Func getFn; 26 | private readonly Action setFn; 27 | 28 | public override bool CanGet { get { return true; } } 29 | public override bool CanSet { get { return this.fieldInfo.IsInitOnly == false; } } 30 | public override Type ValueType { get { return this.fieldInfo.FieldType; } } 31 | 32 | public FieldDescription(TypeDescription typeDescription, FieldInfo fieldInfo) 33 | : base(typeDescription, fieldInfo) 34 | { 35 | if (fieldInfo == null) throw new ArgumentNullException("fieldInfo"); 36 | 37 | this.fieldInfo = fieldInfo; 38 | 39 | MetadataReflection.TryGetMemberAccessFunc(fieldInfo, out this.getFn, out this.setFn); 40 | 41 | } 42 | 43 | public override object GetValue(object target) 44 | { 45 | if (!this.CanGet) throw new InvalidOperationException("Field is write-only."); 46 | 47 | if (this.getFn != null) 48 | return this.getFn(target); 49 | else 50 | return fieldInfo.GetValue(target); 51 | } 52 | 53 | public override void SetValue(object target, object value) 54 | { 55 | if (!this.CanSet) throw new InvalidOperationException("Field is read-only."); 56 | 57 | if (this.setFn != null) 58 | this.setFn(target, value); 59 | else 60 | this.fieldInfo.SetValue(target, value); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Metadata/MemberDescription.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Collections.Generic; 18 | using System.Collections.ObjectModel; 19 | using System.Linq; 20 | using System.Reflection; 21 | 22 | // ReSharper disable once CheckNamespace 23 | namespace GameDevWare.Serialization.Metadata 24 | { 25 | internal abstract class MemberDescription 26 | { 27 | protected const string DATA_CONTRACT_ATTRIBUTE_NAME = "DataContractAttribute"; 28 | protected const string DATA_MEMBER_ATTRIBUTE_NAME = "DataMemberAttribute"; 29 | protected const string IGNORE_DATA_MEMBER_ATTRIBUTE_NAME = "IgnoreDataMemberAttribute"; 30 | 31 | private readonly string name; 32 | private readonly MemberInfo member; 33 | private readonly ReadOnlyCollection attributes; 34 | private readonly ILookup attributesByType; 35 | 36 | public MemberInfo Member { get { return this.member; } } 37 | public ReadOnlyCollection Attributes { get { return this.attributes; } } 38 | public string Name { get { return this.name; } } 39 | 40 | protected MemberDescription(TypeDescription typeDescription, MemberInfo member) 41 | { 42 | if (member == null) throw new ArgumentNullException("member"); 43 | 44 | this.member = member; 45 | this.name = member.Name; 46 | 47 | var attributesList = new List(); 48 | foreach (Attribute attr in member.GetCustomAttributes(true)) 49 | attributesList.Add(attr); 50 | 51 | if (typeDescription != null && typeDescription.IsDataContract) 52 | { 53 | var dataMemberAttribute = attributesList.FirstOrDefault(a => a.GetType().Name == DATA_MEMBER_ATTRIBUTE_NAME); 54 | if (dataMemberAttribute != null) 55 | this.name = ReflectionExtensions.GetDataMemberName(dataMemberAttribute) ?? this.name; 56 | } 57 | 58 | this.attributes = new ReadOnlyCollection(attributesList); 59 | this.attributesByType = attributesList.ToLookup(a => a.GetType()); 60 | } 61 | 62 | public bool HasAttributes(Type type) 63 | { 64 | if (type == null) throw new ArgumentNullException("type"); 65 | 66 | return this.attributesByType.Contains(type); 67 | } 68 | 69 | public IEnumerable GetAttributesOrEmptyList(Type type) 70 | { 71 | if (type == null) throw new ArgumentNullException("type"); 72 | 73 | return this.attributesByType[type]; 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Metadata/PropertyDescription.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Reflection; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization.Metadata 21 | { 22 | internal sealed class PropertyDescription : DataMemberDescription 23 | { 24 | private readonly PropertyInfo propertyInfo; 25 | private readonly Func getFn; 26 | private readonly Action setFn; 27 | private readonly MethodInfo getMethod; 28 | private readonly MethodInfo setMethod; 29 | 30 | public override bool CanGet { get { return this.getMethod != null; } } 31 | public override bool CanSet { get { return this.setMethod != null; } } 32 | public override Type ValueType { get { return this.propertyInfo.PropertyType; } } 33 | 34 | public PropertyDescription(TypeDescription typeDescription, PropertyInfo propertyInfo) 35 | : base(typeDescription, propertyInfo) 36 | { 37 | if (propertyInfo == null) throw new ArgumentNullException("propertyInfo"); 38 | 39 | this.propertyInfo = propertyInfo; 40 | 41 | this.getMethod = propertyInfo.GetGetMethod(nonPublic: true); 42 | this.setMethod = propertyInfo.GetSetMethod(nonPublic: true); 43 | 44 | MetadataReflection.TryGetMemberAccessFunc(this.getMethod, this.setMethod, out this.getFn, out this.setFn); 45 | } 46 | 47 | public override object GetValue(object target) 48 | { 49 | if (!this.CanGet) throw new InvalidOperationException("Property is write-only."); 50 | 51 | if (this.getFn != null) 52 | return this.getFn(target); 53 | else 54 | return this.getMethod.Invoke(target, null); 55 | } 56 | public override void SetValue(object target, object value) 57 | { 58 | if (!this.CanSet) throw new InvalidOperationException("Property is read-only."); 59 | 60 | if (this.setFn != null) 61 | this.setFn(target, value); 62 | else 63 | this.setMethod.Invoke(target, new object[] { value }); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Metadata/TypeDescription.cs: -------------------------------------------------------------------------------- 1 | #if UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_4 || UNITY_4_7 || UNITY_5 || UNITY_5_3_OR_NEWER 2 | #define UNITY 3 | #endif 4 | /* 5 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 6 | 7 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 8 | 9 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 10 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 11 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 12 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 13 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 14 | 15 | This source code is distributed via Unity Asset Store, 16 | to use it in your project you should accept Terms of Service and EULA 17 | https://unity3d.com/ru/legal/as_terms 18 | */ 19 | using System; 20 | using System.Collections; 21 | using System.Collections.Generic; 22 | using System.Collections.ObjectModel; 23 | using System.Linq; 24 | using System.Reflection; 25 | using System.Runtime.CompilerServices; 26 | 27 | #if NET35 || UNITY 28 | using TypeInfo = System.Type; 29 | #endif 30 | 31 | // ReSharper disable once CheckNamespace 32 | namespace GameDevWare.Serialization.Metadata 33 | { 34 | internal class TypeDescription : MemberDescription 35 | { 36 | private static readonly Dictionary TypeDescriptions = new Dictionary(); 37 | private static readonly object[] EmptyParameters = new object[0]; 38 | 39 | private readonly TypeInfo objectType; 40 | private readonly Func constructorFn; 41 | private readonly ConstructorInfo defaultConstructor; 42 | private readonly ReadOnlyCollection members; 43 | private readonly Dictionary membersByName; 44 | 45 | public TypeInfo ObjectType { get { return this.objectType; } } 46 | public bool IsAnonymousType { get; private set; } 47 | public bool IsEnumerable { get; private set; } 48 | public bool IsDictionary { get; private set; } 49 | public bool IsDataContract { get; private set; } 50 | public bool IsSerializable { get; private set; } 51 | public ReadOnlyCollection Members { get { return this.members; } } 52 | 53 | public TypeDescription(TypeInfo objectType) 54 | : base(null, objectType) 55 | { 56 | if (objectType == null) throw new ArgumentNullException("objectType"); 57 | 58 | this.objectType = objectType; 59 | this.IsDataContract = this.Attributes.Any(attribute => attribute.GetType().Name == DATA_CONTRACT_ATTRIBUTE_NAME); 60 | #if NETSTANDARD 61 | this.IsSerializable = this.objectType.GetCustomAttributes(typeof(SerializableAttribute), true).Any(); 62 | #else 63 | this.IsSerializable = objectType.IsSerializable; 64 | #endif 65 | this.IsEnumerable = this.objectType.IsInstantiationOf(typeof(Enumerable)) && this.objectType != typeof(string); 66 | this.IsDictionary = typeof(IDictionary).GetTypeInfo().IsAssignableFrom(this.objectType); 67 | this.IsAnonymousType = this.objectType.IsSealed && this.objectType.IsNotPublic && this.objectType.GetCustomAttributes(typeof(CompilerGeneratedAttribute), true).Any(); 68 | 69 | var allMembers = this.FindMembers(this.objectType); 70 | 71 | this.members = allMembers.AsReadOnly(); 72 | this.membersByName = allMembers.ToDictionary(m => m.Name, StringComparer.Ordinal); 73 | 74 | MetadataReflection.TryGetConstructor(this.objectType, out this.constructorFn, out this.defaultConstructor); 75 | } 76 | 77 | private List FindMembers(TypeInfo objectType) 78 | { 79 | if (objectType == null) throw new ArgumentNullException("objectType"); 80 | 81 | var members = new List(); 82 | var memberNames = new HashSet(StringComparer.Ordinal); 83 | var isOptIn = objectType.GetCustomAttributes(false).Any(a => a.GetType().Name == DATA_CONTRACT_ATTRIBUTE_NAME); 84 | var searchFlags = BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | (isOptIn ? BindingFlags.NonPublic : 0); 85 | var properties = objectType.GetProperties(searchFlags); 86 | var fields = objectType.GetFields(searchFlags); 87 | 88 | foreach (var member in properties.Cast().Concat(fields.Cast())) 89 | { 90 | if (member is PropertyInfo && (member as PropertyInfo).GetIndexParameters().Length != 0) 91 | continue; 92 | 93 | var dataMemberAttribute = member.GetCustomAttributes(false).FirstOrDefault(a => a.GetType().Name == DATA_MEMBER_ATTRIBUTE_NAME); 94 | var ignoreMemberAttribute = member.GetCustomAttributes(false).FirstOrDefault(a => a.GetType().Name == IGNORE_DATA_MEMBER_ATTRIBUTE_NAME); 95 | 96 | if (isOptIn && dataMemberAttribute == null) 97 | continue; 98 | else if (!isOptIn && ignoreMemberAttribute != null) 99 | continue; 100 | 101 | var dataMember = default(DataMemberDescription); 102 | if (member is PropertyInfo) dataMember = new PropertyDescription(this, member as PropertyInfo); 103 | else if (member is FieldInfo) dataMember = new FieldDescription(this, member as FieldInfo); 104 | else throw new InvalidOperationException("Unknown member type. Should be PropertyInfo or FieldInfo."); 105 | 106 | if (string.IsNullOrEmpty(dataMember.Name)) 107 | throw JsonSerializationException.TypeIsNotValid(objectType, "has no members with empty name"); 108 | 109 | if (memberNames.Contains(dataMember.Name)) 110 | { 111 | var conflictingMember = members.First(m => m.Name == dataMember.Name); 112 | throw JsonSerializationException.TypeIsNotValid(objectType, string.Format("has no duplicate member's name '{0}' ('{1}.{2}' and '{3}.{4}')", dataMember.Name, conflictingMember.Member.DeclaringType.Name, conflictingMember.Member.Name, dataMember.Member.DeclaringType.Name, dataMember.Member.Name)); 113 | } 114 | 115 | members.Add(dataMember); 116 | memberNames.Add(dataMember.Name); 117 | } 118 | 119 | return members; 120 | } 121 | 122 | public bool TryGetMember(string name, out DataMemberDescription member) 123 | { 124 | return this.membersByName.TryGetValue(name, out member); 125 | } 126 | 127 | public object CreateInstance() 128 | { 129 | if (this.constructorFn != null) 130 | return this.constructorFn(); 131 | else if (this.defaultConstructor != null && !this.objectType.IsAbstract) 132 | return this.defaultConstructor.Invoke(EmptyParameters); 133 | else 134 | throw JsonSerializationException.CantCreateInstanceOfType(this.objectType); 135 | } 136 | 137 | public static TypeDescription Get(Type type) 138 | { 139 | if (type == null) throw new ArgumentNullException("type"); 140 | 141 | var typeInfo = type.GetTypeInfo(); 142 | lock (TypeDescriptions) 143 | { 144 | TypeDescription objectTypeDescription; 145 | if (!TypeDescriptions.TryGetValue(typeInfo, out objectTypeDescription)) 146 | TypeDescriptions.Add(typeInfo, objectTypeDescription = new TypeDescription(typeInfo)); 147 | return objectTypeDescription; 148 | } 149 | } 150 | 151 | public override string ToString() 152 | { 153 | return this.objectType.ToString(); 154 | } 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/MsgPack.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Collections.Generic; 18 | using System.IO; 19 | using System.Text; 20 | using GameDevWare.Serialization.MessagePack; 21 | using GameDevWare.Serialization.Serializers; 22 | 23 | // ReSharper disable once CheckNamespace 24 | namespace GameDevWare.Serialization 25 | { 26 | public static class MsgPack 27 | { 28 | public static string[] DefaultDateTimeFormats { get { return Json.DefaultDateTimeFormats; } set { Json.DefaultDateTimeFormats = value; } } 29 | public static IFormatProvider DefaultFormat { get { return Json.DefaultFormat; } set { Json.DefaultFormat = value; } } 30 | public static Encoding DefaultEncoding { get { return Json.DefaultEncoding; } set { Json.DefaultEncoding = value; } } 31 | public static List DefaultSerializers { get { return Json.DefaultSerializers; } } 32 | public static MessagePackExtensionTypeHandler ExtensionTypeHandler { get; private set; } 33 | 34 | static MsgPack() 35 | { 36 | ExtensionTypeHandler = new DefaultMessagePackExtensionTypeHandler(EndianBitConverter.Big); 37 | } 38 | 39 | public static void Serialize(T objectToSerialize, Stream msgPackOutput) 40 | { 41 | Serialize(objectToSerialize, msgPackOutput, CreateDefaultContext(SerializationOptions.None)); 42 | } 43 | public static void Serialize(T objectToSerialize, Stream msgPackOutput, SerializationOptions options) 44 | { 45 | Serialize(objectToSerialize, msgPackOutput, CreateDefaultContext(options)); 46 | } 47 | public static void Serialize(T objectToSerialize, Stream msgPackOutput, SerializationContext context) 48 | { 49 | if (msgPackOutput == null) throw new ArgumentNullException("msgPackOutput"); 50 | if (context == null) throw new ArgumentNullException("context"); 51 | 52 | var writer = new MsgPackWriter(msgPackOutput, context); 53 | if (objectToSerialize == null) 54 | { 55 | writer.WriteNull(); 56 | writer.Flush(); 57 | return; 58 | } 59 | writer.WriteValue(objectToSerialize, typeof(T)); 60 | writer.Flush(); 61 | } 62 | 63 | public static object Deserialize(Type objectType, byte[] msgPackInput, int offset, int length) 64 | { 65 | if (msgPackInput == null) throw new ArgumentNullException("msgPackInput"); 66 | 67 | return Deserialize(objectType, new MemoryStream(msgPackInput, offset, length)); 68 | } 69 | public static object Deserialize(Type objectType, byte[] msgPackInput, int offset, int length, SerializationOptions options) 70 | { 71 | if (msgPackInput == null) throw new ArgumentNullException("msgPackInput"); 72 | 73 | return Deserialize(objectType, new MemoryStream(msgPackInput, offset, length), options); 74 | } 75 | public static object Deserialize(Type objectType, byte[] msgPackInput, int offset, int length, SerializationContext context) 76 | { 77 | if (msgPackInput == null) throw new ArgumentNullException("msgPackInput"); 78 | 79 | return Deserialize(objectType, new MemoryStream(msgPackInput, offset, length), context); 80 | } 81 | 82 | public static object Deserialize(Type objectType, Stream msgPackInput) 83 | { 84 | return Deserialize(objectType, msgPackInput, CreateDefaultContext(SerializationOptions.None)); 85 | } 86 | public static object Deserialize(Type objectType, Stream msgPackInput, SerializationOptions options) 87 | { 88 | return Deserialize(objectType, msgPackInput, CreateDefaultContext(options)); 89 | } 90 | public static object Deserialize(Type objectType, Stream msgPackInput, SerializationContext context) 91 | { 92 | if (objectType == null) throw new ArgumentNullException("objectType"); 93 | if (context == null) throw new ArgumentNullException("context"); 94 | if (msgPackInput == null) throw new ArgumentNullException("msgPackInput"); 95 | if (!msgPackInput.CanRead) throw JsonSerializationException.StreamIsNotReadable(); 96 | 97 | var reader = new MsgPackReader(msgPackInput, context); 98 | return reader.ReadValue(objectType, false); 99 | } 100 | 101 | public static T Deserialize(byte[] msgPackInput, int offset, int length) 102 | { 103 | if (msgPackInput == null) throw new ArgumentNullException("msgPackInput"); 104 | 105 | return Deserialize(new MemoryStream(msgPackInput, offset, length)); 106 | } 107 | public static T Deserialize(byte[] msgPackInput, int offset, int length, SerializationOptions options) 108 | { 109 | if (msgPackInput == null) throw new ArgumentNullException("msgPackInput"); 110 | 111 | return Deserialize(new MemoryStream(msgPackInput, offset, length), options); 112 | } 113 | public static T Deserialize(byte[] msgPackInput, int offset, int length, SerializationContext context) 114 | { 115 | if (msgPackInput == null) throw new ArgumentNullException("msgPackInput"); 116 | 117 | return Deserialize(new MemoryStream(msgPackInput, offset, length), context); 118 | } 119 | 120 | public static T Deserialize(Stream msgPackInput) 121 | { 122 | return Deserialize(msgPackInput, CreateDefaultContext(SerializationOptions.None)); 123 | } 124 | public static T Deserialize(Stream msgPackInput, SerializationOptions options) 125 | { 126 | return Deserialize(msgPackInput, CreateDefaultContext(options)); 127 | } 128 | public static T Deserialize(Stream msgPackInput, SerializationContext context) 129 | { 130 | if (context == null) throw new ArgumentNullException("context"); 131 | if (msgPackInput == null) throw new ArgumentNullException("msgPackInput"); 132 | if (!msgPackInput.CanRead) throw JsonSerializationException.StreamIsNotReadable(); 133 | 134 | return (T)Deserialize(typeof(T), msgPackInput, context); 135 | } 136 | 137 | private static SerializationContext CreateDefaultContext(SerializationOptions options) 138 | { 139 | return new SerializationContext 140 | { 141 | Options = options, 142 | EnumSerializerFactory = (enumType) => new EnumNumberSerializer(enumType) 143 | }; 144 | } 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/PathSegment.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | // ReSharper disable once CheckNamespace 4 | namespace GameDevWare.Serialization 5 | { 6 | public struct PathSegment 7 | { 8 | public readonly int Index; 9 | public readonly object MemberName; 10 | 11 | public PathSegment(int index) 12 | { 13 | if (index < 0) throw new ArgumentOutOfRangeException("index"); 14 | 15 | this.Index = index; 16 | this.MemberName = null; 17 | } 18 | public PathSegment(object memberName) 19 | { 20 | if (memberName == null) throw new ArgumentNullException("memberName"); 21 | 22 | this.Index = -1; 23 | this.MemberName = memberName; 24 | } 25 | 26 | /// 27 | public override string ToString() 28 | { 29 | if (this.Index >= 0) 30 | { 31 | return this.Index.ToString(); 32 | } 33 | else if (this.MemberName != null) 34 | { 35 | return this.MemberName.ToString(); 36 | } 37 | else 38 | { 39 | return string.Empty; 40 | } 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/ReflectionExtentions.cs: -------------------------------------------------------------------------------- 1 | #if UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_4 || UNITY_4_7 || UNITY_5 || UNITY_5_3_OR_NEWER 2 | #define UNITY 3 | #endif 4 | /* 5 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 6 | 7 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 8 | 9 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 10 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 11 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 12 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 13 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 14 | 15 | This source code is distributed via Unity Asset Store, 16 | to use it in your project you should accept Terms of Service and EULA 17 | https://unity3d.com/ru/legal/as_terms 18 | */ 19 | using System; 20 | using System.Collections.Generic; 21 | using System.Reflection; 22 | 23 | // ReSharper disable once CheckNamespace 24 | namespace GameDevWare.Serialization 25 | { 26 | internal static class ReflectionExtensions 27 | { 28 | private static readonly Dictionary GetNameMethods = new Dictionary(); 29 | private static readonly object[] EmptyArgs = new object[0]; 30 | 31 | public static bool IsInstantiationOf(this Type type, Type openGenericType) 32 | { 33 | if (type == null) 34 | throw new ArgumentNullException("type"); 35 | if (openGenericType == null) 36 | throw new ArgumentNullException("openGenericType"); 37 | 38 | if (openGenericType.IsGenericType && !openGenericType.IsGenericTypeDefinition) 39 | throw new ArgumentException(string.Format("Type should be open generic type '{0}'.", openGenericType)); 40 | 41 | var genericType = type; 42 | if (type.IsGenericType) 43 | { 44 | if (type.IsGenericType && !type.IsGenericTypeDefinition) 45 | genericType = type.GetGenericTypeDefinition(); 46 | 47 | if (genericType == openGenericType || genericType.IsSubclassOf(openGenericType)) 48 | return true; 49 | } 50 | // clean 51 | genericType = null; 52 | 53 | // check interfaces 54 | foreach (var interfc in type.GetInterfaces()) 55 | { 56 | genericType = interfc; 57 | 58 | if (!interfc.IsGenericType) 59 | continue; 60 | 61 | if (!interfc.IsGenericTypeDefinition) 62 | genericType = interfc.GetGenericTypeDefinition(); 63 | 64 | if (genericType == openGenericType || genericType.IsSubclassOf(openGenericType)) 65 | return true; 66 | } 67 | 68 | if (type.BaseType != null && type.BaseType != typeof (object)) 69 | return IsInstantiationOf(type.BaseType, openGenericType); 70 | 71 | return false; 72 | } 73 | 74 | public static bool HasMultipleInstantiations(this Type type, Type openGenericType) 75 | { 76 | if (type == null) 77 | throw new ArgumentNullException("type"); 78 | if (openGenericType == null) 79 | throw new ArgumentNullException("openGenericType"); 80 | 81 | if (openGenericType.IsGenericType && !openGenericType.IsGenericTypeDefinition) 82 | throw new ArgumentException(string.Format("Type should be open generic type '{0}'.", openGenericType)); 83 | 84 | // can't has multiple implementations of class 85 | if (!openGenericType.IsInterface) 86 | return false; 87 | 88 | var found = 0; 89 | 90 | var genericType = type; 91 | if (type.IsGenericType) 92 | { 93 | if (type.IsGenericType && !type.IsGenericTypeDefinition) 94 | genericType = type.GetGenericTypeDefinition(); 95 | 96 | if (genericType == openGenericType || genericType.IsSubclassOf(openGenericType)) 97 | found++; 98 | } 99 | // clean 100 | genericType = null; 101 | 102 | // check interfaces 103 | foreach (var interfc in type.GetInterfaces()) 104 | { 105 | genericType = interfc; 106 | 107 | if (!interfc.IsGenericType) 108 | continue; 109 | 110 | if (!interfc.IsGenericTypeDefinition) 111 | genericType = interfc.GetGenericTypeDefinition(); 112 | 113 | if (genericType == openGenericType || genericType.IsSubclassOf(openGenericType)) 114 | found++; 115 | } 116 | 117 | 118 | return found > 1; 119 | } 120 | 121 | public static Type[] GetInstantiationArguments(this Type type, Type openGenericType) 122 | { 123 | if (type == null) 124 | throw new ArgumentNullException("type"); 125 | if (openGenericType == null) 126 | throw new ArgumentNullException("openGenericType"); 127 | 128 | if (openGenericType.IsGenericType && !openGenericType.IsGenericTypeDefinition) 129 | throw new ArgumentException(string.Format("Type should be open generic type '{0}'.", openGenericType)); 130 | 131 | var genericType = type; 132 | if (type.IsGenericType) 133 | { 134 | if (type.IsGenericType && !type.IsGenericTypeDefinition) 135 | genericType = type.GetGenericTypeDefinition(); 136 | 137 | if (genericType == openGenericType || genericType.IsSubclassOf(openGenericType)) 138 | return type.GetGenericArguments(); 139 | } 140 | 141 | // clean 142 | genericType = null; 143 | 144 | // check interfaces 145 | foreach (var _interface in type.GetInterfaces()) 146 | { 147 | genericType = _interface; 148 | 149 | if (!_interface.IsGenericType) 150 | continue; 151 | 152 | if (!_interface.IsGenericTypeDefinition) 153 | genericType = _interface.GetGenericTypeDefinition(); 154 | 155 | 156 | if (genericType == openGenericType || genericType.IsSubclassOf(openGenericType)) 157 | return _interface.GetGenericArguments(); 158 | } 159 | 160 | 161 | if (type.BaseType != null && type.BaseType != typeof (object)) 162 | return GetInstantiationArguments(type.BaseType, openGenericType); 163 | 164 | return null; 165 | } 166 | 167 | public static string GetDataMemberName(object dataMemberAttribute) 168 | { 169 | if (dataMemberAttribute == null) throw new ArgumentNullException("dataMemberAttribute"); 170 | 171 | var type = dataMemberAttribute.GetType(); 172 | var getName = default(MethodInfo); 173 | 174 | lock (GetNameMethods) 175 | { 176 | if (!GetNameMethods.TryGetValue(type, out getName)) 177 | { 178 | getName = type.GetMethod("get_Name", BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null); 179 | 180 | if (getName == null || getName.ReturnType != typeof (string) || getName.GetParameters().Length != 0) 181 | getName = null; 182 | 183 | if (getName == null) 184 | { 185 | var getNameProperty = type.GetProperty("Name", BindingFlags.Instance | BindingFlags.Public, null, typeof (string), 186 | Type.EmptyTypes, null); 187 | if (getNameProperty != null) 188 | getName = getNameProperty.GetGetMethod(nonPublic: false); 189 | } 190 | 191 | GetNameMethods.Add(type, getName); 192 | } 193 | } 194 | 195 | if (getName != null) 196 | return (string) getName.Invoke(dataMemberAttribute, EmptyArgs); 197 | else 198 | return null; 199 | } 200 | 201 | #if NET35 || UNITY 202 | public static Type GetTypeInfo(this Type type) 203 | { 204 | return type; 205 | } 206 | #endif 207 | } 208 | } 209 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/SerializationOptions.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | 18 | // ReSharper disable once CheckNamespace 19 | namespace GameDevWare.Serialization 20 | { 21 | [Flags] 22 | public enum SerializationOptions 23 | { 24 | None = 0, 25 | SuppressTypeInformation = 0x1 << 1, 26 | PrettyPrint = 0x1 << 2, 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/ArraySerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Collections; 18 | using System.Collections.Generic; 19 | using System.Linq; 20 | using System.Runtime.CompilerServices; 21 | 22 | // ReSharper disable once CheckNamespace 23 | namespace GameDevWare.Serialization.Serializers 24 | { 25 | public sealed class ArraySerializer : TypeSerializer 26 | { 27 | private readonly Type arrayType; 28 | private readonly Type instantiatedArrayType; 29 | private readonly Type elementType; 30 | 31 | public override Type SerializedType { get { return this.arrayType; } } 32 | 33 | public ArraySerializer(Type enumerableType) 34 | { 35 | if (enumerableType == null) throw new ArgumentNullException("enumerableType"); 36 | 37 | this.arrayType = 38 | this.instantiatedArrayType = enumerableType; 39 | this.elementType = this.GetElementType(arrayType); 40 | 41 | if (this.elementType == null) throw JsonSerializationException.TypeIsNotValid(this.GetType(), "be enumerable"); 42 | 43 | if (this.arrayType == typeof(IList) || this.arrayType == typeof(ICollection) || this.arrayType == typeof(IEnumerable)) 44 | this.instantiatedArrayType = typeof(ArrayList); 45 | else if (arrayType.IsInterface && arrayType.IsGenericType && (arrayType.GetGenericTypeDefinition() == typeof(IList<>) || arrayType.GetGenericTypeDefinition() == typeof(ICollection<>) || arrayType.GetGenericTypeDefinition() == typeof(IEnumerable<>))) 46 | this.instantiatedArrayType = typeof(List<>).MakeGenericType(this.elementType); 47 | } 48 | 49 | public override object Deserialize(IJsonReader reader) 50 | { 51 | if (reader == null) throw new ArgumentNullException("reader"); 52 | 53 | if (reader.Token == JsonToken.Null) 54 | return null; 55 | 56 | var container = new ArrayList(); 57 | if (reader.Token != JsonToken.BeginArray) 58 | throw JsonSerializationException.UnexpectedToken(reader, JsonToken.BeginArray); 59 | 60 | reader.Context.Hierarchy.Push(container); 61 | var i = 0; 62 | while (reader.NextToken() && reader.Token != JsonToken.EndOfArray) 63 | { 64 | reader.Context.Path.Push(new PathSegment(i++)); 65 | 66 | var value = reader.ReadValue(this.elementType, false); 67 | container.Add(value); 68 | 69 | reader.Context.Path.Pop(); 70 | } 71 | reader.Context.Hierarchy.Pop(); 72 | 73 | if (reader.IsEndOfStream()) 74 | throw JsonSerializationException.UnexpectedToken(reader, JsonToken.EndOfArray); 75 | 76 | if (this.instantiatedArrayType == typeof(ArrayList)) 77 | return container; 78 | else if (this.instantiatedArrayType.IsArray) 79 | return container.ToArray(this.elementType); 80 | else 81 | return Activator.CreateInstance(this.instantiatedArrayType, container.ToArray(this.elementType)); 82 | } 83 | 84 | public override void Serialize(IJsonWriter writer, object value) 85 | { 86 | if (writer == null) throw new ArgumentNullException("writer"); 87 | if (value == null) throw new ArgumentNullException("value"); 88 | 89 | var size = 0; 90 | if (value is ICollection) 91 | size = ((ICollection)value).Count; 92 | else 93 | size = ((IEnumerable)value).Cast().Count(); 94 | 95 | writer.WriteArrayBegin(size); 96 | var i = 0; 97 | foreach (var item in (IEnumerable)value) 98 | { 99 | writer.Context.Path.Push(new PathSegment(i++)); 100 | writer.WriteValue(item, this.elementType); 101 | writer.Context.Path.Pop(); 102 | } 103 | writer.WriteArrayEnd(); 104 | } 105 | 106 | private Type GetElementType(Type arrayType) 107 | { 108 | if (arrayType == null) throw new ArgumentNullException("arrayType"); 109 | 110 | 111 | var elementType = (Type)null; 112 | if (arrayType.IsArray) 113 | { 114 | elementType = arrayType.GetElementType(); 115 | return elementType; 116 | } 117 | 118 | if (arrayType.IsInstantiationOf(typeof(IEnumerable<>))) 119 | { 120 | if (arrayType.HasMultipleInstantiations(typeof(IEnumerable<>))) 121 | throw JsonSerializationException.TypeIsNotValid(this.GetType(), "have only one generic IEnumerable interface"); 122 | 123 | elementType = arrayType.GetInstantiationArguments(typeof(IEnumerable<>))[0]; 124 | } 125 | 126 | if (elementType == null && typeof(IEnumerable).IsAssignableFrom(arrayType)) 127 | elementType = typeof(object); 128 | else if (elementType == null) 129 | throw JsonSerializationException.TypeIsNotValid(this.GetType(), "be enumerable"); 130 | 131 | return elementType; 132 | } 133 | 134 | public override string ToString() 135 | { 136 | return string.Format("array of {1}, {0}", this.arrayType, this.elementType); 137 | } 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/BinarySerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using GameDevWare.Serialization.MessagePack; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization.Serializers 21 | { 22 | public sealed class BinarySerializer : TypeSerializer 23 | { 24 | public static readonly BinarySerializer Instance = new BinarySerializer(); 25 | 26 | public override Type SerializedType { get { return typeof(byte[]); } } 27 | 28 | public override object Deserialize(IJsonReader reader) 29 | { 30 | if (reader == null) throw new ArgumentNullException("reader"); 31 | 32 | if (reader.Token == JsonToken.Null) 33 | return null; 34 | 35 | if (reader.RawValue is byte[]) 36 | { 37 | return reader.RawValue; 38 | } 39 | else 40 | { 41 | var value = reader.RawValue as string; 42 | if (value == null) 43 | return null; 44 | 45 | var buffer = Convert.FromBase64String(value); 46 | return buffer; 47 | } 48 | } 49 | 50 | public override void Serialize(IJsonWriter writer, object value) 51 | { 52 | if (writer == null) throw new ArgumentNullException("writer"); 53 | 54 | if (value == null) 55 | { 56 | writer.WriteNull(); 57 | return; 58 | } 59 | if (value != null && value is byte[] == false) throw JsonSerializationException.TypeIsNotValid(this.GetType(), "be array of bytes"); 60 | 61 | var bytes = (byte[])value; 62 | if (writer is MsgPackWriter) 63 | { 64 | ((MsgPackWriter)writer).Write(bytes); 65 | } 66 | else 67 | { 68 | var base64String = Convert.ToBase64String(bytes); 69 | writer.WriteString(base64String); 70 | } 71 | } 72 | 73 | public override string ToString() 74 | { 75 | return "byte[] as Base64"; 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/BoundsSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | #if UNITY_5 || UNITY_4 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_5_3_OR_NEWER 17 | using System; 18 | using UnityEngine; 19 | 20 | // ReSharper disable once CheckNamespace 21 | namespace GameDevWare.Serialization.Serializers 22 | { 23 | public sealed class BoundsSerializer : TypeSerializer 24 | { 25 | public override Type SerializedType { get { return typeof(Bounds); } } 26 | 27 | public override object Deserialize(IJsonReader reader) 28 | { 29 | if (reader == null) throw new ArgumentNullException("reader"); 30 | 31 | if (reader.Token == JsonToken.Null) 32 | return null; 33 | 34 | var value = new Bounds(); 35 | reader.ReadObjectBegin(); 36 | while (reader.Token != JsonToken.EndOfObject) 37 | { 38 | var memberName = reader.ReadMember(); 39 | if (memberName == "center") 40 | value.center = (Vector3)reader.ReadValue(typeof(Vector3)); 41 | else if (memberName == "extents") 42 | value.extents = (Vector3)reader.ReadValue(typeof(Vector3)); 43 | else 44 | reader.ReadValue(typeof(object)); 45 | } 46 | reader.ReadObjectEnd(nextToken: false); 47 | return value; 48 | } 49 | public override void Serialize(IJsonWriter writer, object value) 50 | { 51 | if (writer == null) throw new ArgumentNullException("writer"); 52 | if (value == null) throw new ArgumentNullException("value"); 53 | 54 | var bounds = (Bounds)value; 55 | writer.WriteObjectBegin(2); 56 | writer.WriteMember("center"); 57 | writer.WriteValue(bounds.center, typeof(Vector3)); 58 | writer.WriteMember("extents"); 59 | writer.WriteValue(bounds.extents, typeof(Vector3)); 60 | writer.WriteObjectEnd(); 61 | } 62 | } 63 | } 64 | #endif 65 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/DateTimeOffsetSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Globalization; 18 | using System.Linq; 19 | using System.Runtime.Serialization; 20 | 21 | // ReSharper disable once CheckNamespace 22 | namespace GameDevWare.Serialization.Serializers 23 | { 24 | public sealed class DateTimeOffsetSerializer : TypeSerializer 25 | { 26 | public override Type SerializedType { get { return typeof(DateTimeOffset); } } 27 | 28 | public override object Deserialize(IJsonReader reader) 29 | { 30 | if (reader == null) throw new ArgumentNullException("reader"); 31 | 32 | if (reader.Value.Raw is DateTimeOffset) 33 | return reader.Value.Raw; 34 | else if (reader.Token == JsonToken.DateTime || reader.Value.Raw is DateTime) 35 | return new DateTimeOffset(reader.Value.AsDateTime); 36 | 37 | var dateTimeOffsetStr = reader.ReadString(false); 38 | try 39 | { 40 | var value = default(DateTimeOffset); 41 | if (!DateTimeOffset.TryParse(dateTimeOffsetStr, reader.Context.Format, DateTimeStyles.RoundtripKind, out value)) 42 | value = DateTimeOffset.ParseExact(dateTimeOffsetStr, reader.Context.DateTimeFormats, reader.Context.Format, DateTimeStyles.RoundtripKind); 43 | 44 | return value; 45 | } 46 | catch (FormatException fe) 47 | { 48 | throw new SerializationException(string.Format("Failed to parse date '{0}' in with pattern '{1}'.", dateTimeOffsetStr, reader.Context.DateTimeFormats[0]), fe); 49 | } 50 | } 51 | 52 | public override void Serialize(IJsonWriter writer, object value) 53 | { 54 | if (writer == null) throw new ArgumentNullException("writer"); 55 | if (value == null) throw new ArgumentNullException("value"); 56 | 57 | var dateTimeOffset = (DateTimeOffset)value; 58 | writer.Write(dateTimeOffset); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/DateTimeSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Globalization; 18 | using System.Linq; 19 | using System.Runtime.Serialization; 20 | 21 | // ReSharper disable once CheckNamespace 22 | namespace GameDevWare.Serialization.Serializers 23 | { 24 | public sealed class DateTimeSerializer : TypeSerializer 25 | { 26 | public override Type SerializedType { get { return typeof(DateTime); } } 27 | 28 | public override object Deserialize(IJsonReader reader) 29 | { 30 | if (reader == null) throw new ArgumentNullException("reader"); 31 | 32 | if (reader.Token == JsonToken.DateTime || reader.RawValue is DateTime) 33 | return reader.Value.AsDateTime; 34 | 35 | var dateTimeStr = reader.ReadString(false); 36 | try 37 | { 38 | var value = default(DateTime); 39 | if (!DateTime.TryParse(dateTimeStr, reader.Context.Format, DateTimeStyles.RoundtripKind, out value)) 40 | value = DateTime.ParseExact(dateTimeStr, reader.Context.DateTimeFormats, reader.Context.Format, DateTimeStyles.RoundtripKind); 41 | 42 | return value; 43 | } 44 | catch (FormatException fe) 45 | { 46 | throw new SerializationException(string.Format("Failed to parse date '{0}' in with pattern '{1}'.", dateTimeStr, reader.Context.DateTimeFormats[0]), fe); 47 | } 48 | } 49 | 50 | public override void Serialize(IJsonWriter writer, object value) 51 | { 52 | if (writer == null) throw new ArgumentNullException("writer"); 53 | if (value == null) throw new ArgumentNullException("value"); 54 | 55 | var dataTime = (DateTime)value; 56 | writer.Write(dataTime); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/DictionaryEntrySerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Collections; 18 | using System.Runtime.Serialization; 19 | 20 | // ReSharper disable once CheckNamespace 21 | namespace GameDevWare.Serialization.Serializers 22 | { 23 | public sealed class DictionaryEntrySerializer : TypeSerializer 24 | { 25 | public const string KEY_MEMBER_NAME = "Key"; 26 | public const string VALUE_MEMBER_NAME = "Value"; 27 | 28 | public override Type SerializedType { get { return typeof(DictionaryEntry); } } 29 | 30 | public override object Deserialize(IJsonReader reader) 31 | { 32 | if (reader == null) throw new ArgumentNullException("reader"); 33 | 34 | if (reader.Token == JsonToken.BeginArray) 35 | { 36 | var entry = new DictionaryEntry(); 37 | reader.ReadArrayBegin(); 38 | entry.Key = reader.ReadValue(typeof(object)); 39 | entry.Value = reader.ReadValue(typeof(object)); 40 | reader.ReadArrayEnd(nextToken: false); 41 | return entry; 42 | } 43 | else if (reader.Token == JsonToken.BeginObject) 44 | { 45 | var entry = new DictionaryEntry(); 46 | reader.ReadObjectBegin(); 47 | while (reader.Token != JsonToken.EndOfObject) 48 | { 49 | var memberName = reader.ReadMember(); 50 | switch (memberName) 51 | { 52 | case KEY_MEMBER_NAME: 53 | entry.Key = reader.ReadValue(typeof(object)); 54 | break; 55 | case VALUE_MEMBER_NAME: 56 | entry.Value = reader.ReadValue(typeof(object)); 57 | break; 58 | case ObjectSerializer.TYPE_MEMBER_NAME: 59 | reader.ReadValue(typeof(object)); 60 | break; 61 | default: 62 | throw new SerializationException(string.Format("Unknown member found '{0}' while '{1}' or '{2}' are expected.", memberName, KEY_MEMBER_NAME, VALUE_MEMBER_NAME)); 63 | } 64 | } 65 | reader.ReadObjectEnd(nextToken: false); 66 | return entry; 67 | } 68 | else 69 | { 70 | throw JsonSerializationException.UnexpectedToken(reader, JsonToken.BeginObject, JsonToken.BeginArray); 71 | } 72 | } 73 | public override void Serialize(IJsonWriter writer, object value) 74 | { 75 | if (writer == null) throw new ArgumentNullException("writer"); 76 | if (value == null) throw new ArgumentNullException("value"); 77 | 78 | var entry = (DictionaryEntry)value; 79 | writer.WriteObjectBegin(2); 80 | writer.WriteMember(KEY_MEMBER_NAME); 81 | writer.WriteValue(entry.Key, typeof(object)); 82 | writer.WriteMember(VALUE_MEMBER_NAME); 83 | writer.WriteValue(entry.Value, typeof(object)); 84 | writer.WriteObjectEnd(); 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/EnumNumberSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | 18 | // ReSharper disable once CheckNamespace 19 | namespace GameDevWare.Serialization.Serializers 20 | { 21 | public sealed class EnumNumberSerializer : TypeSerializer 22 | { 23 | private readonly Type enumType; 24 | private readonly Type enumBaseType; 25 | 26 | public override Type SerializedType { get { return this.enumType; } } 27 | 28 | public EnumNumberSerializer(Type enumType) 29 | { 30 | if (enumType == null) throw new ArgumentNullException("enumType"); 31 | if (!enumType.IsEnum) throw JsonSerializationException.TypeIsNotValid(this.GetType(), "be a Enum"); 32 | 33 | this.enumType = enumType; 34 | this.enumBaseType = Enum.GetUnderlyingType(enumType); 35 | } 36 | 37 | public override object Deserialize(IJsonReader reader) 38 | { 39 | if (reader == null) throw new ArgumentNullException("reader"); 40 | 41 | if (reader.Token == JsonToken.StringLiteral) 42 | return Enum.Parse(this.enumType, reader.ReadString(false), true); 43 | else if (reader.Token == JsonToken.Number) 44 | return Enum.ToObject(this.enumType, reader.ReadValue(this.enumBaseType, false)); 45 | else 46 | throw JsonSerializationException.UnexpectedToken(reader, JsonToken.Number, JsonToken.StringLiteral); 47 | } 48 | 49 | public override void Serialize(IJsonWriter writer, object value) 50 | { 51 | if (writer == null) throw new ArgumentNullException("writer"); 52 | if (value == null) throw new ArgumentNullException("value"); 53 | 54 | writer.WriteValue(Convert.ChangeType(value, this.enumBaseType), this.enumBaseType); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/EnumSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | 18 | // ReSharper disable once CheckNamespace 19 | namespace GameDevWare.Serialization.Serializers 20 | { 21 | public sealed class EnumSerializer : TypeSerializer 22 | { 23 | private readonly Type enumType; 24 | private readonly Type enumBaseType; 25 | 26 | public override Type SerializedType { get { return this.enumType; } } 27 | 28 | public EnumSerializer(Type enumType) 29 | { 30 | if (enumType == null) throw new ArgumentNullException("enumType"); 31 | if (!enumType.IsEnum) throw JsonSerializationException.TypeIsNotValid(this.GetType(), "be a Enum"); 32 | 33 | this.enumType = enumType; 34 | this.enumBaseType = Enum.GetUnderlyingType(enumType); 35 | } 36 | 37 | public override object Deserialize(IJsonReader reader) 38 | { 39 | if (reader == null) throw new ArgumentNullException("reader"); 40 | 41 | if (reader.Token == JsonToken.StringLiteral) 42 | return Enum.Parse(this.enumType, reader.ReadString(false), true); 43 | else if (reader.Token == JsonToken.Number) 44 | return Enum.ToObject(this.enumType, reader.ReadValue(this.enumBaseType, false)); 45 | else 46 | throw JsonSerializationException.UnexpectedToken(reader, JsonToken.Number, JsonToken.StringLiteral); 47 | } 48 | 49 | public override void Serialize(IJsonWriter writer, object value) 50 | { 51 | if (writer == null) throw new ArgumentNullException("writer"); 52 | if (value == null) throw new ArgumentNullException("value"); 53 | 54 | var valueStr = Convert.ToString(value, writer.Context.Format); 55 | writer.WriteString(valueStr); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/GuidSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using GameDevWare.Serialization.MessagePack; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization.Serializers 21 | { 22 | public sealed class GuidSerializer : TypeSerializer 23 | { 24 | public override Type SerializedType { get { return typeof(Guid); } } 25 | 26 | public override object Deserialize(IJsonReader reader) 27 | { 28 | if (reader == null) throw new ArgumentNullException("reader"); 29 | 30 | var guidStr = reader.ReadString(false); 31 | var value = new Guid(guidStr); 32 | return value; 33 | } 34 | 35 | public override void Serialize(IJsonWriter writer, object value) 36 | { 37 | if (writer == null) throw new ArgumentNullException("writer"); 38 | if (value == null) throw new ArgumentNullException("value"); 39 | 40 | var messagePackWriter = writer as MsgPackWriter; 41 | if (messagePackWriter != null) 42 | { 43 | // try to write it as Message Pack extension type 44 | var extensionType = default(sbyte); 45 | var buffer = messagePackWriter.GetWriteBuffer(); 46 | if (messagePackWriter.Context.ExtensionTypeHandler.TryWrite(value, out extensionType, ref buffer)) 47 | { 48 | messagePackWriter.Write(extensionType, buffer); 49 | return; 50 | } 51 | // if not, continue default serialization 52 | } 53 | 54 | var guid = (Guid)value; 55 | var guidStr = guid.ToString(); 56 | writer.Write(guidStr); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/Matrix4x4Serializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | #if UNITY_5 || UNITY_4 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_5_3_OR_NEWER 17 | using System; 18 | using UnityEngine; 19 | 20 | // ReSharper disable once CheckNamespace 21 | namespace GameDevWare.Serialization.Serializers 22 | { 23 | public sealed class Matrix4x4Serializer : TypeSerializer 24 | { 25 | public override Type SerializedType { get { return typeof(Matrix4x4); } } 26 | 27 | public override object Deserialize(IJsonReader reader) 28 | { 29 | if (reader == null) throw new ArgumentNullException("reader"); 30 | 31 | if (reader.Token == JsonToken.Null) 32 | return null; 33 | 34 | var value = new Matrix4x4(); 35 | reader.ReadObjectBegin(); 36 | while (reader.Token != JsonToken.EndOfObject) 37 | { 38 | var memberName = reader.ReadMember(); 39 | switch (memberName) 40 | { 41 | case "m00": value.m00 = reader.ReadSingle(); break; 42 | case "m10": value.m10 = reader.ReadSingle(); break; 43 | case "m20": value.m20 = reader.ReadSingle(); break; 44 | case "m30": value.m30 = reader.ReadSingle(); break; 45 | case "m01": value.m01 = reader.ReadSingle(); break; 46 | case "m11": value.m11 = reader.ReadSingle(); break; 47 | case "m21": value.m21 = reader.ReadSingle(); break; 48 | case "m31": value.m31 = reader.ReadSingle(); break; 49 | case "m02": value.m02 = reader.ReadSingle(); break; 50 | case "m12": value.m12 = reader.ReadSingle(); break; 51 | case "m22": value.m22 = reader.ReadSingle(); break; 52 | case "m32": value.m32 = reader.ReadSingle(); break; 53 | case "m03": value.m03 = reader.ReadSingle(); break; 54 | case "m13": value.m13 = reader.ReadSingle(); break; 55 | case "m23": value.m23 = reader.ReadSingle(); break; 56 | case "m33": value.m33 = reader.ReadSingle(); break; 57 | default: 58 | reader.ReadValue(typeof(object)); 59 | break; 60 | } 61 | } 62 | reader.ReadObjectEnd(nextToken: false); 63 | return value; 64 | } 65 | public override void Serialize(IJsonWriter writer, object value) 66 | { 67 | if (writer == null) throw new ArgumentNullException("writer"); 68 | if (value == null) throw new ArgumentNullException("value"); 69 | 70 | var matrix = (Matrix4x4)value; 71 | writer.WriteObjectBegin(16); 72 | writer.WriteMember("m00"); 73 | writer.Write(matrix.m00); 74 | writer.WriteMember("m10"); 75 | writer.Write(matrix.m10); 76 | writer.WriteMember("m20"); 77 | writer.Write(matrix.m20); 78 | writer.WriteMember("m30"); 79 | writer.Write(matrix.m30); 80 | writer.WriteMember("m01"); 81 | writer.Write(matrix.m01); 82 | writer.WriteMember("m11"); 83 | writer.Write(matrix.m11); 84 | writer.WriteMember("m21"); 85 | writer.Write(matrix.m21); 86 | writer.WriteMember("m31"); 87 | writer.Write(matrix.m31); 88 | writer.WriteMember("m02"); 89 | writer.Write(matrix.m02); 90 | writer.WriteMember("m12"); 91 | writer.Write(matrix.m12); 92 | writer.WriteMember("m22"); 93 | writer.Write(matrix.m22); 94 | writer.WriteMember("m32"); 95 | writer.Write(matrix.m32); 96 | writer.WriteMember("m03"); 97 | writer.Write(matrix.m03); 98 | writer.WriteMember("m13"); 99 | writer.Write(matrix.m13); 100 | writer.WriteMember("m23"); 101 | writer.Write(matrix.m23); 102 | writer.WriteMember("m33"); 103 | writer.Write(matrix.m33); 104 | writer.WriteObjectEnd(); 105 | } 106 | } 107 | } 108 | #endif 109 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/MsgPackExtensionTypeSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Globalization; 18 | using GameDevWare.Serialization.MessagePack; 19 | 20 | // ReSharper disable once CheckNamespace 21 | namespace GameDevWare.Serialization.Serializers 22 | { 23 | public sealed class MsgPackExtensionTypeSerializer : TypeSerializer 24 | { 25 | private const string DATA_MEMBER_NAME = "$data"; 26 | private const string TYPE_MEMBER_NAME = "$type"; 27 | 28 | /// 29 | public override Type SerializedType { get { return typeof(MessagePackExtensionType); } } 30 | 31 | public override object Deserialize(IJsonReader reader) 32 | { 33 | if (reader.Token == JsonToken.Null) 34 | { 35 | return null; 36 | } 37 | else if (reader.RawValue is MessagePackExtensionType) 38 | { 39 | return (MessagePackExtensionType)reader.RawValue; 40 | } 41 | else if (reader.RawValue is byte[]) 42 | { 43 | return new MessagePackExtensionType((byte[])reader.RawValue); 44 | } 45 | else if (reader.RawValue is string) 46 | { 47 | return new MessagePackExtensionType(Convert.FromBase64String(reader.Value.AsString)); 48 | } 49 | 50 | // { "$binary" : "", "$type" : "" } 51 | // http://www.mongodb.org/display/DOCS/Mongo+Extended+JSON 52 | 53 | reader.ReadObjectBegin(); 54 | var base64Binary = default(string); 55 | var subtypeHex = default(string); 56 | while (reader.Token != JsonToken.EndOfObject) 57 | { 58 | var member = reader.ReadMember(); 59 | switch (member) 60 | { 61 | case DATA_MEMBER_NAME: 62 | base64Binary = reader.ReadString(); 63 | break; 64 | case TYPE_MEMBER_NAME: 65 | subtypeHex = reader.ReadString(); 66 | break; 67 | default: 68 | reader.ReadValue(typeof(object)); // skip value 69 | break; 70 | } 71 | } 72 | reader.ReadObjectEnd(nextToken: false); 73 | 74 | if (subtypeHex == null) subtypeHex = "0"; 75 | if (base64Binary == null) base64Binary = ""; 76 | 77 | var binaryType = unchecked((sbyte)byte.Parse(subtypeHex, NumberStyles.HexNumber)); 78 | var binary = Convert.FromBase64String(base64Binary); 79 | 80 | var value = new MessagePackExtensionType(binaryType, binary); 81 | return value; 82 | } 83 | public override void Serialize(IJsonWriter writer, object value) 84 | { 85 | if (value == null) 86 | { 87 | writer.WriteNull(); 88 | return; 89 | } 90 | 91 | var extensionType = (MessagePackExtensionType)value; 92 | 93 | var msgPackWriter = writer as MsgPackWriter; 94 | if (msgPackWriter != null) 95 | { 96 | msgPackWriter.Write(extensionType.Type, extensionType.ToArraySegment()); 97 | return; 98 | } 99 | 100 | writer.WriteObjectBegin(2); 101 | writer.WriteMember(DATA_MEMBER_NAME); 102 | writer.WriteString(extensionType.ToBase64()); 103 | writer.WriteMember(TYPE_MEMBER_NAME); 104 | writer.Write(unchecked((byte)extensionType.Type).ToString("X2")); 105 | writer.WriteObjectEnd(); 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/MsgPackTimestampSerializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using GameDevWare.Serialization.MessagePack; 3 | 4 | // ReSharper disable once CheckNamespace 5 | namespace GameDevWare.Serialization.Serializers 6 | { 7 | public class MsgPackTimestampSerializer : TypeSerializer 8 | { 9 | private const string SECONDS_MEMBER_NAME = "$seconds"; 10 | private const string NANO_SECONDS_MEMBER_NAME = "$nanoSeconds"; 11 | 12 | /// 13 | public override Type SerializedType { get { return typeof(MessagePackTimestamp); } } 14 | 15 | public override object Deserialize(IJsonReader reader) 16 | { 17 | if (reader.RawValue is MessagePackTimestamp) 18 | { 19 | return (MessagePackTimestamp)reader.Value.Raw; 20 | } 21 | else if (reader.Token == JsonToken.Null) 22 | { 23 | return null; 24 | } 25 | 26 | reader.ReadObjectBegin(); 27 | var seconds = default(long); 28 | var nanoSeconds = default(uint); 29 | while (reader.Token != JsonToken.EndOfObject) 30 | { 31 | var member = reader.ReadMember(); 32 | switch (member) 33 | { 34 | case SECONDS_MEMBER_NAME: 35 | seconds = reader.ReadInt64(); 36 | break; 37 | case NANO_SECONDS_MEMBER_NAME: 38 | seconds = reader.ReadUInt32(); 39 | break; 40 | default: 41 | reader.ReadValue(typeof(object)); // skip value 42 | break; 43 | } 44 | } 45 | reader.ReadObjectEnd(false); 46 | 47 | var value = new MessagePackTimestamp(seconds, nanoSeconds); 48 | return value; 49 | } 50 | public override void Serialize(IJsonWriter writer, object value) 51 | { 52 | if (value == null) 53 | { 54 | writer.WriteNull(); 55 | return; 56 | } 57 | 58 | var messagePackWriter = writer as MsgPackWriter; 59 | if (messagePackWriter != null) 60 | { 61 | var extensionType = default(sbyte); 62 | var buffer = messagePackWriter.GetWriteBuffer(); 63 | if (messagePackWriter.Context.ExtensionTypeHandler.TryWrite(value, out extensionType, ref buffer)) 64 | { 65 | messagePackWriter.Write(extensionType, buffer); 66 | return; 67 | } 68 | } 69 | 70 | var timeStamp = (MessagePackTimestamp)value; 71 | writer.WriteObjectBegin(2); 72 | writer.WriteMember(SECONDS_MEMBER_NAME); 73 | writer.Write(timeStamp.Seconds); 74 | writer.WriteMember(NANO_SECONDS_MEMBER_NAME); 75 | writer.Write(timeStamp.NanoSeconds); 76 | writer.WriteObjectEnd(); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/PrimitiveTypeSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | 18 | // ReSharper disable once CheckNamespace 19 | namespace GameDevWare.Serialization.Serializers 20 | { 21 | public sealed class PrimitiveSerializer : TypeSerializer 22 | { 23 | private readonly Type primitiveType; 24 | private readonly TypeCode primitiveTypeCode; 25 | 26 | public override Type SerializedType { get { return this.primitiveType; } } 27 | 28 | public PrimitiveSerializer(Type primitiveType) 29 | { 30 | if (primitiveType == null) throw new ArgumentNullException("primitiveType"); 31 | 32 | if (primitiveType.IsGenericType && primitiveType.GetGenericTypeDefinition() == typeof(Nullable<>)) 33 | throw JsonSerializationException.TypeIsNotValid(typeof(PrimitiveSerializer), "can't be nullable type"); 34 | 35 | this.primitiveType = primitiveType; 36 | this.primitiveTypeCode = Type.GetTypeCode(primitiveType); 37 | 38 | if (this.primitiveTypeCode == TypeCode.Object || this.primitiveTypeCode == TypeCode.Empty || 39 | this.primitiveTypeCode == TypeCode.DBNull) 40 | throw JsonSerializationException.TypeIsNotValid(this.GetType(), "be a primitive type"); 41 | } 42 | 43 | public override object Deserialize(IJsonReader reader) 44 | { 45 | if (reader == null) throw new ArgumentNullException("reader"); 46 | 47 | if (reader.Token == JsonToken.Null) 48 | { 49 | if (this.primitiveTypeCode == TypeCode.String) 50 | return null; 51 | 52 | throw JsonSerializationException.UnexpectedToken(reader, JsonToken.Boolean, JsonToken.DateTime, JsonToken.Null, JsonToken.Number, JsonToken.StringLiteral); 53 | } 54 | 55 | var value = default(object); 56 | switch (primitiveTypeCode) 57 | { 58 | case TypeCode.Boolean: 59 | value = reader.ReadBoolean(false); 60 | break; 61 | case TypeCode.Byte: 62 | value = reader.ReadByte(false); 63 | break; 64 | case TypeCode.DateTime: 65 | value = reader.ReadDateTime(false); 66 | break; 67 | case TypeCode.Decimal: 68 | value = reader.ReadDecimal(false); 69 | break; 70 | case TypeCode.Double: 71 | value = reader.ReadDouble(false); 72 | break; 73 | case TypeCode.Int16: 74 | value = reader.ReadInt16(false); 75 | break; 76 | case TypeCode.Int32: 77 | value = reader.ReadInt32(false); 78 | break; 79 | case TypeCode.Int64: 80 | value = reader.ReadInt64(false); 81 | break; 82 | case TypeCode.SByte: 83 | value = reader.ReadSByte(false); 84 | break; 85 | case TypeCode.Single: 86 | value = reader.ReadSingle(false); 87 | break; 88 | case TypeCode.UInt16: 89 | value = reader.ReadUInt16(false); 90 | break; 91 | case TypeCode.UInt32: 92 | value = reader.ReadUInt32(false); 93 | break; 94 | case TypeCode.UInt64: 95 | value = reader.ReadUInt64(false); 96 | break; 97 | default: 98 | var valueStr = reader.ReadString(false); 99 | value = Convert.ChangeType(valueStr, this.primitiveType, reader.Context.Format); 100 | break; 101 | } 102 | return value; 103 | } 104 | 105 | public override void Serialize(IJsonWriter writer, object value) 106 | { 107 | if (writer == null) throw new ArgumentNullException("writer"); 108 | if (value == null) throw new ArgumentNullException("value"); 109 | 110 | switch (primitiveTypeCode) 111 | { 112 | case TypeCode.Boolean: 113 | writer.WriteBoolean((bool)value); 114 | break; 115 | case TypeCode.Byte: 116 | writer.WriteNumber((byte)value); 117 | break; 118 | case TypeCode.DateTime: 119 | writer.WriteDateTime((DateTime)value); 120 | break; 121 | case TypeCode.Decimal: 122 | writer.WriteNumber((decimal)value); 123 | break; 124 | case TypeCode.Double: 125 | writer.WriteNumber((double)value); 126 | break; 127 | case TypeCode.Int16: 128 | writer.WriteNumber((short)value); 129 | break; 130 | case TypeCode.Int32: 131 | writer.WriteNumber((int)value); 132 | break; 133 | case TypeCode.Int64: 134 | writer.WriteNumber((long)value); 135 | break; 136 | case TypeCode.SByte: 137 | writer.WriteNumber((sbyte)value); 138 | break; 139 | case TypeCode.Single: 140 | writer.WriteNumber((float)value); 141 | break; 142 | case TypeCode.UInt16: 143 | writer.WriteNumber((ushort)value); 144 | break; 145 | case TypeCode.UInt32: 146 | writer.WriteNumber((uint)value); 147 | break; 148 | case TypeCode.UInt64: 149 | writer.WriteNumber((ulong)value); 150 | break; 151 | default: 152 | var valueStr = default(string); 153 | 154 | if (value is IFormattable) 155 | valueStr = (string)Convert.ChangeType(value, typeof(string), writer.Context.Format); 156 | else 157 | valueStr = value.ToString(); 158 | 159 | writer.WriteString(valueStr); 160 | break; 161 | } 162 | } 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/QuaternionSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | #if UNITY_5 || UNITY_4 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_5_3_OR_NEWER 17 | using System; 18 | using UnityEngine; 19 | 20 | // ReSharper disable once CheckNamespace 21 | namespace GameDevWare.Serialization.Serializers 22 | { 23 | public sealed class QuaternionSerializer : TypeSerializer 24 | { 25 | public override Type SerializedType { get { return typeof(Quaternion); } } 26 | 27 | public override object Deserialize(IJsonReader reader) 28 | { 29 | if (reader == null) throw new ArgumentNullException("reader"); 30 | 31 | if (reader.Token == JsonToken.Null) 32 | return null; 33 | 34 | var value = new Quaternion(); 35 | reader.ReadObjectBegin(); 36 | while (reader.Token != JsonToken.EndOfObject) 37 | { 38 | var memberName = reader.ReadMember(); 39 | if (memberName == "x") 40 | value.x = reader.ReadSingle(); 41 | else if (memberName == "y") 42 | value.y = reader.ReadSingle(); 43 | else if (memberName == "z") 44 | value.z = reader.ReadSingle(); 45 | else if (memberName == "w") 46 | value.w = reader.ReadSingle(); 47 | else 48 | reader.ReadValue(typeof(object)); 49 | } 50 | reader.ReadObjectEnd(nextToken: false); 51 | return value; 52 | } 53 | public override void Serialize(IJsonWriter writer, object value) 54 | { 55 | if (writer == null) throw new ArgumentNullException("writer"); 56 | if (value == null) throw new ArgumentNullException("value"); 57 | 58 | var quaternion = (Quaternion)value; 59 | writer.WriteObjectBegin(4); 60 | writer.WriteMember("x"); 61 | writer.Write(quaternion.x); 62 | writer.WriteMember("y"); 63 | writer.Write(quaternion.y); 64 | writer.WriteMember("z"); 65 | writer.Write(quaternion.z); 66 | writer.WriteMember("w"); 67 | writer.Write(quaternion.w); 68 | writer.WriteObjectEnd(); 69 | } 70 | } 71 | } 72 | #endif 73 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/RectSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | #if UNITY_5 || UNITY_4 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_5_3_OR_NEWER 17 | using System; 18 | using UnityEngine; 19 | 20 | // ReSharper disable once CheckNamespace 21 | namespace GameDevWare.Serialization.Serializers 22 | { 23 | public sealed class RectSerializer : TypeSerializer 24 | { 25 | public override Type SerializedType { get { return typeof(Rect); } } 26 | 27 | public override object Deserialize(IJsonReader reader) 28 | { 29 | if (reader == null) throw new ArgumentNullException("reader"); 30 | 31 | if (reader.Token == JsonToken.Null) 32 | return null; 33 | 34 | var value = new Rect(); 35 | reader.ReadObjectBegin(); 36 | while (reader.Token != JsonToken.EndOfObject) 37 | { 38 | var memberName = reader.ReadMember(); 39 | if (memberName == "x") 40 | value.x = reader.ReadSingle(); 41 | else if (memberName == "y") 42 | value.y = reader.ReadSingle(); 43 | else if (memberName == "width") 44 | value.width = reader.ReadSingle(); 45 | else if (memberName == "height") 46 | value.height = reader.ReadSingle(); 47 | else 48 | reader.ReadValue(typeof(object)); 49 | } 50 | reader.ReadObjectEnd(nextToken: false); 51 | return value; 52 | } 53 | public override void Serialize(IJsonWriter writer, object value) 54 | { 55 | if (writer == null) throw new ArgumentNullException("writer"); 56 | if (value == null) throw new ArgumentNullException("value"); 57 | 58 | var vector4 = (Rect)value; 59 | writer.WriteObjectBegin(4); 60 | writer.WriteMember("x"); 61 | writer.Write(vector4.x); 62 | writer.WriteMember("y"); 63 | writer.Write(vector4.y); 64 | writer.WriteMember("width"); 65 | writer.Write(vector4.width); 66 | writer.WriteMember("height"); 67 | writer.Write(vector4.height); 68 | writer.WriteObjectEnd(); 69 | } 70 | } 71 | } 72 | #endif 73 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/StreamSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.IO; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization.Serializers 21 | { 22 | public sealed class StreamSerializer : TypeSerializer 23 | { 24 | public static readonly StreamSerializer Instance = new StreamSerializer(); 25 | 26 | public override Type SerializedType { get { return typeof(Stream); } } 27 | 28 | public override object Deserialize(IJsonReader reader) 29 | { 30 | if (reader == null) throw new ArgumentNullException("reader"); 31 | 32 | if (reader.Token == JsonToken.Null) 33 | return null; 34 | 35 | if (reader.RawValue is Stream) 36 | return reader.RawValue; 37 | else if(reader.RawValue is byte[]) 38 | return new MemoryStream((byte[])reader.RawValue); 39 | else 40 | { 41 | var base64Str = Convert.ToString(reader.RawValue, reader.Context.Format); 42 | var bytes = Convert.FromBase64String(base64Str); 43 | return new MemoryStream(bytes); 44 | } 45 | } 46 | 47 | public override void Serialize(IJsonWriter writer, object value) 48 | { 49 | if (writer == null) throw new ArgumentNullException("writer"); 50 | if (value == null) throw new ArgumentNullException("value"); 51 | 52 | var stream = value as Stream; 53 | if (value != null && stream == null) throw JsonSerializationException.TypeIsNotValid(this.GetType(), "be a Stream"); 54 | if (!stream.CanRead) throw new JsonSerializationException("Stream couldn't be readed.", JsonSerializationException.ErrorCode.StreamIsNotReadable); 55 | 56 | if (stream.CanSeek) 57 | { 58 | var position = stream.Position; 59 | var buffer = new byte[stream.Length - stream.Position]; 60 | stream.Read(buffer, 0, buffer.Length); 61 | BinarySerializer.Instance.Serialize(writer, buffer); 62 | stream.Position = position; 63 | } 64 | else 65 | { 66 | var tmpStream = new MemoryStream(); 67 | var buffer = new byte[ushort.MaxValue]; 68 | var readed = 0; 69 | 70 | while ((readed = stream.Read(buffer, 0, buffer.Length)) > 0) 71 | tmpStream.Write(buffer, 0, readed); 72 | 73 | BinarySerializer.Instance.Serialize(writer, tmpStream.ToArray()); 74 | } 75 | } 76 | 77 | public override string ToString() 78 | { 79 | return "stream"; 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/TimeSpanSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | 18 | // ReSharper disable once CheckNamespace 19 | namespace GameDevWare.Serialization.Serializers 20 | { 21 | public sealed class TimeSpanSerializer : TypeSerializer 22 | { 23 | public override Type SerializedType { get { return typeof(TimeSpan); } } 24 | 25 | public override object Deserialize(IJsonReader reader) 26 | { 27 | if (reader == null) throw new ArgumentNullException("reader"); 28 | 29 | if (reader.Token == JsonToken.Number) 30 | return new TimeSpan(reader.Value.AsInt64); 31 | 32 | var timeSpanStr = reader.ReadString(false); 33 | var value = TimeSpan.Parse(timeSpanStr); 34 | return value; 35 | } 36 | 37 | public override void Serialize(IJsonWriter writer, object value) 38 | { 39 | if (writer == null) throw new ArgumentNullException("writer"); 40 | if (value == null) throw new ArgumentNullException("value"); 41 | 42 | var timeSpan = (TimeSpan)value; 43 | writer.Write((long)timeSpan.Ticks); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/UriSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | 18 | // ReSharper disable once CheckNamespace 19 | namespace GameDevWare.Serialization.Serializers 20 | { 21 | public sealed class UriSerializer : TypeSerializer 22 | { 23 | public override Type SerializedType { get { return typeof(Uri); } } 24 | 25 | public override object Deserialize(IJsonReader reader) 26 | { 27 | if (reader == null) throw new ArgumentNullException("reader"); 28 | 29 | var uriStr = reader.ReadString(false); 30 | var value = new Uri(uriStr); 31 | return value; 32 | } 33 | 34 | public override void Serialize(IJsonWriter writer, object value) 35 | { 36 | if (writer == null) throw new ArgumentNullException("writer"); 37 | if (value == null) throw new ArgumentNullException("value"); 38 | 39 | var uri = (Uri)value; 40 | writer.WriteString(uri.OriginalString); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/Vector2Serializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | #if UNITY_5 || UNITY_4 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_5_3_OR_NEWER 17 | using System; 18 | using UnityEngine; 19 | 20 | // ReSharper disable once CheckNamespace 21 | namespace GameDevWare.Serialization.Serializers 22 | { 23 | public sealed class Vector2Serializer : TypeSerializer 24 | { 25 | public override Type SerializedType { get { return typeof(Vector2); } } 26 | 27 | public override object Deserialize(IJsonReader reader) 28 | { 29 | if (reader == null) throw new ArgumentNullException("reader"); 30 | 31 | if (reader.Token == JsonToken.Null) 32 | return null; 33 | 34 | var value = new Vector2(); 35 | reader.ReadObjectBegin(); 36 | while (reader.Token != JsonToken.EndOfObject) 37 | { 38 | var memberName = reader.ReadMember(); 39 | switch (memberName) 40 | { 41 | case "x": value.x = reader.ReadSingle(); break; 42 | case "y": value.y = reader.ReadSingle(); break; 43 | default: reader.ReadValue(typeof(object)); break; 44 | } 45 | } 46 | reader.ReadObjectEnd(nextToken: false); 47 | return value; 48 | } 49 | public override void Serialize(IJsonWriter writer, object value) 50 | { 51 | if (writer == null) throw new ArgumentNullException("writer"); 52 | if (value == null) throw new ArgumentNullException("value"); 53 | 54 | var vector2 = (Vector2)value; 55 | writer.WriteObjectBegin(2); 56 | writer.WriteMember("x"); 57 | writer.Write(vector2.x); 58 | writer.WriteMember("y"); 59 | writer.Write(vector2.y); 60 | writer.WriteObjectEnd(); 61 | } 62 | } 63 | } 64 | #endif 65 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/Vector3Serializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | #if UNITY_5 || UNITY_4 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_5_3_OR_NEWER 17 | using System; 18 | using UnityEngine; 19 | 20 | // ReSharper disable once CheckNamespace 21 | namespace GameDevWare.Serialization.Serializers 22 | { 23 | public sealed class Vector3Serializer : TypeSerializer 24 | { 25 | public override Type SerializedType { get { return typeof(Vector3); } } 26 | 27 | public override object Deserialize(IJsonReader reader) 28 | { 29 | if (reader == null) throw new ArgumentNullException("reader"); 30 | 31 | if (reader.Token == JsonToken.Null) 32 | return null; 33 | 34 | var value = new Vector3(); 35 | reader.ReadObjectBegin(); 36 | while (reader.Token != JsonToken.EndOfObject) 37 | { 38 | var memberName = reader.ReadMember(); 39 | switch (memberName) 40 | { 41 | case "x": value.x = reader.ReadSingle(); break; 42 | case "y": value.y = reader.ReadSingle(); break; 43 | case "z": value.z = reader.ReadSingle(); break; 44 | default: reader.ReadValue(typeof(object)); break; 45 | } 46 | } 47 | reader.ReadObjectEnd(nextToken: false); 48 | return value; 49 | } 50 | public override void Serialize(IJsonWriter writer, object value) 51 | { 52 | if (writer == null) throw new ArgumentNullException("writer"); 53 | if (value == null) throw new ArgumentNullException("value"); 54 | 55 | var vector3 = (Vector3)value; 56 | writer.WriteObjectBegin(3); 57 | writer.WriteMember("x"); 58 | writer.Write(vector3.x); 59 | writer.WriteMember("y"); 60 | writer.Write(vector3.y); 61 | writer.WriteMember("z"); 62 | writer.Write(vector3.z); 63 | writer.WriteObjectEnd(); 64 | } 65 | } 66 | } 67 | #endif 68 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/Vector4Serializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | #if UNITY_5 || UNITY_4 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_5_3_OR_NEWER 17 | using System; 18 | using UnityEngine; 19 | 20 | // ReSharper disable once CheckNamespace 21 | namespace GameDevWare.Serialization.Serializers 22 | { 23 | public sealed class Vector4Serializer : TypeSerializer 24 | { 25 | public override Type SerializedType { get { return typeof(Vector4); } } 26 | 27 | public override object Deserialize(IJsonReader reader) 28 | { 29 | if (reader == null) throw new ArgumentNullException("reader"); 30 | 31 | if (reader.Token == JsonToken.Null) 32 | return null; 33 | 34 | var value = new Vector4(); 35 | reader.ReadObjectBegin(); 36 | while (reader.Token != JsonToken.EndOfObject) 37 | { 38 | var memberName = reader.ReadMember(); 39 | switch (memberName) 40 | { 41 | case "x": value.x = reader.ReadSingle(); break; 42 | case "y": value.y = reader.ReadSingle(); break; 43 | case "z": value.z = reader.ReadSingle(); break; 44 | case "w": value.w = reader.ReadSingle(); break; 45 | default: reader.ReadValue(typeof(object)); break; 46 | } 47 | } 48 | reader.ReadObjectEnd(nextToken: false); 49 | return value; 50 | } 51 | public override void Serialize(IJsonWriter writer, object value) 52 | { 53 | if (writer == null) throw new ArgumentNullException("writer"); 54 | if (value == null) throw new ArgumentNullException("value"); 55 | 56 | var vector4 = (Vector4)value; 57 | writer.WriteObjectBegin(4); 58 | writer.WriteMember("x"); 59 | writer.Write(vector4.x); 60 | writer.WriteMember("y"); 61 | writer.Write(vector4.y); 62 | writer.WriteMember("z"); 63 | writer.Write(vector4.z); 64 | writer.WriteMember("w"); 65 | writer.Write(vector4.w); 66 | writer.WriteObjectEnd(); 67 | } 68 | } 69 | } 70 | #endif 71 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/Serializers/VersionSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | 18 | // ReSharper disable once CheckNamespace 19 | namespace GameDevWare.Serialization.Serializers 20 | { 21 | public sealed class VersionSerializer : TypeSerializer 22 | { 23 | public override Type SerializedType { get { return typeof(Version); } } 24 | 25 | public override object Deserialize(IJsonReader reader) 26 | { 27 | if (reader == null) throw new ArgumentNullException("reader"); 28 | 29 | var versionStr = reader.ReadString(false); 30 | var value = new Version(versionStr); 31 | return value; 32 | } 33 | 34 | public override void Serialize(IJsonWriter writer, object value) 35 | { 36 | if (writer == null) throw new ArgumentNullException("writer"); 37 | if (value == null) throw new ArgumentNullException("value"); 38 | 39 | var version = (Version)value; 40 | writer.WriteString(version.ToString()); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/TypeSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | 17 | using System; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization 21 | { 22 | public abstract class TypeSerializer 23 | { 24 | public abstract Type SerializedType { get; } 25 | 26 | public abstract object Deserialize(IJsonReader reader); 27 | public abstract void Serialize(IJsonWriter writer, object value); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Plugins/GameDevWare.Serialization/TypeSerializerAttribute.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | 17 | using System; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization 21 | { 22 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)] 23 | public class TypeSerializerAttribute : Attribute 24 | { 25 | public Type SerializerType { get; private set; } 26 | 27 | public TypeSerializerAttribute(Type type) 28 | { 29 | if (type == null) throw new ArgumentNullException("type"); 30 | if (typeof(TypeSerializer).IsAssignableFrom(type) == false) throw new ArgumentException(string.Format("Type '{0}' should inherit from '{1}'.", type, typeof(TypeSerializer)), "type"); 31 | 32 | this.SerializerType = type; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Scripts/Benchmark.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: fb3a4e2f3c44e8d4f856ef1b7eb69937 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Scripts/Benchmark/Benchmark.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Collections.Generic; 18 | using System.Diagnostics; 19 | using System.IO; 20 | using System.Linq; 21 | using System.Text; 22 | using Assets.Scripts.Benchmark; 23 | using GameDevWare.Serialization; 24 | using UnityEngine; 25 | 26 | // ReSharper disable once CheckNamespace 27 | public class Benchmark : MonoBehaviour 28 | { 29 | private const int ItemsToSerialize = 100000; 30 | 31 | internal void Awake() 32 | { 33 | UnityEngine.Debug.Log(SystemInfo.processorType); 34 | } 35 | internal void OnGUI() 36 | { 37 | var width = 500.0f; 38 | var height = Screen.height - 40.0f; 39 | 40 | GUILayout.BeginArea(new Rect((Screen.width - width) / 2, (Screen.height - height) / 2, width, height)); 41 | GUILayout.BeginVertical(); 42 | 43 | if (GUILayout.Button("Measure Json Serializer (GameDevWare)")) 44 | new Action(this.MeasureJsonSerializer).BeginInvoke(null, null); 45 | if (GUILayout.Button("Measure MessagePack Serializer (GameDevWare)")) 46 | new Action(this.MeasureMsgPackSerializer).BeginInvoke(null, null); 47 | if (GUILayout.Button("Test MessagePack")) 48 | new Action(Assets.Scripts.Example.SerializeExample.SerializeToMsgPackMemoryStream).BeginInvoke(null, null); 49 | if (GUILayout.Button("Test Json")) 50 | new Action(Assets.Scripts.Example.SerializeExample.SerializeToJsonMemoryStream).BeginInvoke(null, null); 51 | 52 | GUILayout.EndVertical(); 53 | GUILayout.EndArea(); 54 | } 55 | 56 | private void MeasureJsonSerializer() 57 | { 58 | try 59 | { 60 | this.SerializeTestObject(Json.Serialize>); 61 | this.SerializeTestObject(Json.Serialize>); 62 | this.SerializeTestObject(Json.Serialize>); 63 | this.DeserializeTestObject(Json.Serialize>, Json.Deserialize>); 64 | this.DeserializeTestObject(Json.Serialize>, Json.Deserialize>); 65 | this.DeserializeTestObject(Json.Serialize>, Json.Deserialize>); 66 | } 67 | catch (Exception e) 68 | { 69 | UnityEngine.Debug.LogError(e); 70 | } 71 | } 72 | private void MeasureMsgPackSerializer() 73 | { 74 | try 75 | { 76 | this.SerializeTestObject(MsgPack.Serialize>); 77 | this.SerializeTestObject(MsgPack.Serialize>); 78 | this.SerializeTestObject(MsgPack.Serialize>); 79 | this.DeserializeTestObject(MsgPack.Serialize>, MsgPack.Deserialize>); 80 | this.DeserializeTestObject(MsgPack.Serialize>, MsgPack.Deserialize>); 81 | this.DeserializeTestObject(MsgPack.Serialize>, MsgPack.Deserialize>); 82 | } 83 | catch (Exception e) 84 | { 85 | UnityEngine.Debug.LogError(e); 86 | } 87 | } 88 | 89 | private void SerializeTestObject(Action, Stream> serializeFn) where T : ITestObject, new() 90 | { 91 | var output = new ByteCountingStream(); 92 | var value = new T(); 93 | value.Fill(); 94 | var sw = Stopwatch.StartNew(); 95 | 96 | // warmup 97 | //UnityEngine.Debug.Log(string.Format("[{0}] Warming-up {1} Serializer", typeof(T).Name, serializeFn.Method.DeclaringType.Name)); 98 | serializeFn(InfiniteEnumerable(value).Take(ItemsToSerialize / 100), output); 99 | 100 | //UnityEngine.Debug.Log(string.Format("[{0}] Running {1} Serializer", typeof(T).Name, serializeFn.Method.DeclaringType.Name)); 101 | // reset 102 | GC.Collect(); 103 | output.SetLength(0); 104 | sw.Start(); 105 | serializeFn(InfiniteEnumerable(value).Take(ItemsToSerialize), output); 106 | sw.Stop(); 107 | //UnityEngine.Debug.Log(string.Format("[{0}] {1} Serializer finished in {2:F2}ms, {3} bytes are written.", typeof(T).Name, serializeFn.Method.DeclaringType.Name, sw.ElapsedMilliseconds, output.Length)); 108 | UnityEngine.Debug.Log(string.Format("[{0}] {1} | size(bytes) {2} | object/s {3:F0} | bandwidth {4:F2} Mb/s", typeof(T).Name, serializeFn.Method.DeclaringType.Name, 109 | output.Length / ItemsToSerialize, 110 | ItemsToSerialize * (1 / sw.Elapsed.TotalSeconds), 111 | output.Length * (1 / sw.Elapsed.TotalSeconds) / 1024 / 1024)); 112 | } 113 | private void DeserializeTestObject(Action, Stream> serializeFn, Func> deserializeFn) where T : ITestObject, new() 114 | { 115 | var output = new MemoryStream(); 116 | var value = new T(); 117 | value.Fill(); 118 | var sw = Stopwatch.StartNew(); 119 | 120 | // warmup 121 | //UnityEngine.Debug.Log(string.Format("[{0}] Warming-up {1} deserializer", typeof(T).Name, serializeFn.Method.DeclaringType.Name)); 122 | serializeFn(InfiniteEnumerable(value).Take(ItemsToSerialize / 100), output); 123 | output.Position = 0; 124 | deserializeFn(output); 125 | 126 | //UnityEngine.Debug.Log(string.Format("[{0}] Running {1} deserializer", typeof(T).Name, serializeFn.Method.DeclaringType.Name)); 127 | // reset 128 | GC.Collect(); 129 | sw.Start(); 130 | output.Position = 0; 131 | deserializeFn(output); 132 | sw.Stop(); 133 | //UnityEngine.Debug.Log(string.Format("[{0}] {1} Deserializer finished in {2:F2}ms, {3} bytes are readed.", typeof(T).Name, serializeFn.Method.DeclaringType.Name, sw.ElapsedMilliseconds, output.Length)); 134 | UnityEngine.Debug.Log(string.Format("[{0}] {1} | size(bytes) {2} | object/s {3:F0} | bandwidth {4:F2} Mb/s", typeof(T).Name, serializeFn.Method.DeclaringType.Name, 135 | output.Length / (ItemsToSerialize / 100), 136 | ItemsToSerialize / 100.0 * (1 / sw.Elapsed.TotalSeconds), 137 | output.Length * (1 / sw.Elapsed.TotalSeconds) / 1024 / 1024)); 138 | } 139 | 140 | public IEnumerable InfiniteEnumerable(T value) 141 | { 142 | while (true) 143 | yield return value; 144 | } 145 | 146 | /* 147 | Intel(R) Core(TM) i5-3570 CPU @ 3.40GHz 148 | 149 | Serialization: 150 | | size(bytes) | object/sec. | bandwidth 151 | Json | 744 | 7658 | 5.43 Mb/s 152 | Json | 154 | 30853 | 4.53 Mb/s 153 | Json | 102 | 64888 | 6.31 Mb/s 154 | MsgPack | 666 | 15206 | 9.66 Mb/s 155 | MsgPack | 146 | 123475 | 17.19 Mb/s 156 | MsgPack | 92 | 155038 | 13.60 Mb/s 157 | 158 | De-serialization: 159 | Json | 744 | 268 | 0.19 Mb/s 160 | Json | 154 | 7218 | 1.06 Mb/s 161 | Json | 102 | 9981 | 0.97 Mb/s 162 | MsgPack | 666 | 474 | 0.30 Mb/s 163 | MsgPack | 146 | 15153 | 2.11 Mb/s 164 | MsgPack | 92 | 15278 | 1.34 Mb/s 165 | 166 | */ 167 | } 168 | 169 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Scripts/Benchmark/Benchmark.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 3a34c2df7c9f71143bd30b9e1d1e2652 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Scripts/Benchmark/Benchmark.unity: -------------------------------------------------------------------------------- 1 | %YAML 1.1 2 | %TAG !u! tag:unity3d.com,2011: 3 | --- !u!29 &1 4 | OcclusionCullingSettings: 5 | m_ObjectHideFlags: 0 6 | serializedVersion: 2 7 | m_OcclusionBakeSettings: 8 | smallestOccluder: 5 9 | smallestHole: 0.25 10 | backfaceThreshold: 100 11 | m_SceneGUID: 00000000000000000000000000000000 12 | m_OcclusionCullingData: {fileID: 0} 13 | --- !u!104 &2 14 | RenderSettings: 15 | m_ObjectHideFlags: 0 16 | serializedVersion: 9 17 | m_Fog: 0 18 | m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} 19 | m_FogMode: 3 20 | m_FogDensity: 0.01 21 | m_LinearFogStart: 0 22 | m_LinearFogEnd: 300 23 | m_AmbientSkyColor: {r: 0.2, g: 0.2, b: 0.2, a: 1} 24 | m_AmbientEquatorColor: {r: 0.2, g: 0.2, b: 0.2, a: 1} 25 | m_AmbientGroundColor: {r: 0.2, g: 0.2, b: 0.2, a: 1} 26 | m_AmbientIntensity: 1 27 | m_AmbientMode: 3 28 | m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} 29 | m_SkyboxMaterial: {fileID: 0} 30 | m_HaloStrength: 0.5 31 | m_FlareStrength: 1 32 | m_FlareFadeSpeed: 3 33 | m_HaloTexture: {fileID: 0} 34 | m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} 35 | m_DefaultReflectionMode: 0 36 | m_DefaultReflectionResolution: 128 37 | m_ReflectionBounces: 1 38 | m_ReflectionIntensity: 1 39 | m_CustomReflection: {fileID: 0} 40 | m_Sun: {fileID: 0} 41 | m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 1} 42 | m_UseRadianceAmbientProbe: 0 43 | --- !u!196 &3 44 | NavMeshSettings: 45 | serializedVersion: 2 46 | m_ObjectHideFlags: 0 47 | m_BuildSettings: 48 | serializedVersion: 2 49 | agentTypeID: 0 50 | agentRadius: 0.5 51 | agentHeight: 2 52 | agentSlope: 45 53 | agentClimb: 0.4 54 | ledgeDropHeight: 0 55 | maxJumpAcrossDistance: 0 56 | minRegionArea: 2 57 | manualCellSize: 0 58 | cellSize: 0.16666667 59 | manualTileSize: 0 60 | tileSize: 256 61 | accuratePlacement: 0 62 | debug: 63 | m_Flags: 0 64 | m_NavMeshData: {fileID: 0} 65 | --- !u!157 &4 66 | LightmapSettings: 67 | m_ObjectHideFlags: 0 68 | serializedVersion: 11 69 | m_GIWorkflowMode: 1 70 | m_GISettings: 71 | serializedVersion: 2 72 | m_BounceScale: 1 73 | m_IndirectOutputScale: 1 74 | m_AlbedoBoost: 1 75 | m_TemporalCoherenceThreshold: 1 76 | m_EnvironmentLightingMode: 0 77 | m_EnableBakedLightmaps: 1 78 | m_EnableRealtimeLightmaps: 0 79 | m_LightmapEditorSettings: 80 | serializedVersion: 10 81 | m_Resolution: 1 82 | m_BakeResolution: 50 83 | m_AtlasSize: 1024 84 | m_AO: 1 85 | m_AOMaxDistance: 1 86 | m_CompAOExponent: 1 87 | m_CompAOExponentDirect: 0 88 | m_Padding: 2 89 | m_LightmapParameters: {fileID: 0} 90 | m_LightmapsBakeMode: 1 91 | m_TextureCompression: 0 92 | m_FinalGather: 0 93 | m_FinalGatherFiltering: 1 94 | m_FinalGatherRayCount: 256 95 | m_ReflectionCompression: 2 96 | m_MixedBakeMode: 1 97 | m_BakeBackend: 0 98 | m_PVRSampling: 1 99 | m_PVRDirectSampleCount: 32 100 | m_PVRSampleCount: 500 101 | m_PVRBounces: 2 102 | m_PVRFilterTypeDirect: 0 103 | m_PVRFilterTypeIndirect: 0 104 | m_PVRFilterTypeAO: 0 105 | m_PVRFilteringMode: 0 106 | m_PVRCulling: 1 107 | m_PVRFilteringGaussRadiusDirect: 1 108 | m_PVRFilteringGaussRadiusIndirect: 5 109 | m_PVRFilteringGaussRadiusAO: 2 110 | m_PVRFilteringAtrousPositionSigmaDirect: 0.5 111 | m_PVRFilteringAtrousPositionSigmaIndirect: 2 112 | m_PVRFilteringAtrousPositionSigmaAO: 1 113 | m_ShowResolutionOverlay: 1 114 | m_LightingDataAsset: {fileID: 0} 115 | m_UseShadowmask: 0 116 | --- !u!1 &5 117 | GameObject: 118 | m_ObjectHideFlags: 0 119 | m_CorrespondingSourceObject: {fileID: 0} 120 | m_PrefabInternal: {fileID: 0} 121 | serializedVersion: 6 122 | m_Component: 123 | - component: {fileID: 7} 124 | - component: {fileID: 13} 125 | m_Layer: 0 126 | m_Name: Benchmark 127 | m_TagString: Untagged 128 | m_Icon: {fileID: 0} 129 | m_NavMeshLayer: 0 130 | m_StaticEditorFlags: 0 131 | m_IsActive: 1 132 | --- !u!1 &6 133 | GameObject: 134 | m_ObjectHideFlags: 0 135 | m_CorrespondingSourceObject: {fileID: 0} 136 | m_PrefabInternal: {fileID: 0} 137 | serializedVersion: 6 138 | m_Component: 139 | - component: {fileID: 8} 140 | - component: {fileID: 9} 141 | - component: {fileID: 11} 142 | - component: {fileID: 12} 143 | - component: {fileID: 10} 144 | m_Layer: 0 145 | m_Name: Main Camera 146 | m_TagString: MainCamera 147 | m_Icon: {fileID: 0} 148 | m_NavMeshLayer: 0 149 | m_StaticEditorFlags: 0 150 | m_IsActive: 1 151 | --- !u!4 &7 152 | Transform: 153 | m_ObjectHideFlags: 0 154 | m_CorrespondingSourceObject: {fileID: 0} 155 | m_PrefabInternal: {fileID: 0} 156 | m_GameObject: {fileID: 5} 157 | m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} 158 | m_LocalPosition: {x: 0, y: 0, z: 0} 159 | m_LocalScale: {x: 1, y: 1, z: 1} 160 | m_Children: [] 161 | m_Father: {fileID: 0} 162 | m_RootOrder: 0 163 | m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} 164 | --- !u!4 &8 165 | Transform: 166 | m_ObjectHideFlags: 0 167 | m_CorrespondingSourceObject: {fileID: 0} 168 | m_PrefabInternal: {fileID: 0} 169 | m_GameObject: {fileID: 6} 170 | m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} 171 | m_LocalPosition: {x: 0, y: 1, z: -10} 172 | m_LocalScale: {x: 1, y: 1, z: 1} 173 | m_Children: [] 174 | m_Father: {fileID: 0} 175 | m_RootOrder: 1 176 | m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} 177 | --- !u!20 &9 178 | Camera: 179 | m_ObjectHideFlags: 0 180 | m_CorrespondingSourceObject: {fileID: 0} 181 | m_PrefabInternal: {fileID: 0} 182 | m_GameObject: {fileID: 6} 183 | m_Enabled: 1 184 | serializedVersion: 2 185 | m_ClearFlags: 1 186 | m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0.019607844} 187 | m_projectionMatrixMode: 1 188 | m_SensorSize: {x: 36, y: 24} 189 | m_LensShift: {x: 0, y: 0} 190 | m_FocalLength: 50 191 | m_NormalizedViewPortRect: 192 | serializedVersion: 2 193 | x: 0 194 | y: 0 195 | width: 1 196 | height: 1 197 | near clip plane: 0.3 198 | far clip plane: 1000 199 | field of view: 60 200 | orthographic: 0 201 | orthographic size: 100 202 | m_Depth: -1 203 | m_CullingMask: 204 | serializedVersion: 2 205 | m_Bits: 4294967295 206 | m_RenderingPath: -1 207 | m_TargetTexture: {fileID: 0} 208 | m_TargetDisplay: 0 209 | m_TargetEye: 3 210 | m_HDR: 1 211 | m_AllowMSAA: 1 212 | m_AllowDynamicResolution: 0 213 | m_ForceIntoRT: 0 214 | m_OcclusionCulling: 1 215 | m_StereoConvergence: 10 216 | m_StereoSeparation: 0.022 217 | --- !u!81 &10 218 | AudioListener: 219 | m_ObjectHideFlags: 0 220 | m_CorrespondingSourceObject: {fileID: 0} 221 | m_PrefabInternal: {fileID: 0} 222 | m_GameObject: {fileID: 6} 223 | m_Enabled: 1 224 | --- !u!92 &11 225 | Behaviour: 226 | m_ObjectHideFlags: 0 227 | m_CorrespondingSourceObject: {fileID: 0} 228 | m_PrefabInternal: {fileID: 0} 229 | m_GameObject: {fileID: 6} 230 | m_Enabled: 1 231 | --- !u!124 &12 232 | Behaviour: 233 | m_ObjectHideFlags: 0 234 | m_CorrespondingSourceObject: {fileID: 0} 235 | m_PrefabInternal: {fileID: 0} 236 | m_GameObject: {fileID: 6} 237 | m_Enabled: 1 238 | --- !u!114 &13 239 | MonoBehaviour: 240 | m_ObjectHideFlags: 0 241 | m_CorrespondingSourceObject: {fileID: 0} 242 | m_PrefabInternal: {fileID: 0} 243 | m_GameObject: {fileID: 5} 244 | m_Enabled: 1 245 | m_EditorHideFlags: 0 246 | m_Script: {fileID: 11500000, guid: 3a34c2df7c9f71143bd30b9e1d1e2652, type: 3} 247 | m_Name: 248 | m_EditorClassIdentifier: 249 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Scripts/Benchmark/Benchmark.unity.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 4d17fedd317ccf440a0b57f0172350f0 3 | DefaultImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Scripts/Benchmark/BigTestObject.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Collections.Generic; 18 | 19 | namespace Assets.Scripts.Benchmark 20 | { 21 | public class BigTestObject : IEquatable, ITestObject 22 | { 23 | public byte ByteField { get; set; } 24 | public sbyte SByteField { get; set; } 25 | public short Int16Field { get; set; } 26 | public ushort UInt16Field { get; set; } 27 | public int Int32Field { get; set; } 28 | public uint UInt32Field { get; set; } 29 | public long Int64Field { get; set; } 30 | public ulong UInt64Field { get; set; } 31 | public decimal DecimalField { get; set; } 32 | public float SingleFiled { get; set; } 33 | public double DoubleField { get; set; } 34 | public string StringField { get; set; } 35 | public ConsoleColor MyEnumField { get; set; } 36 | public bool BooleanField { get; set; } 37 | public DateTime DateTimeField { get; set; } 38 | public DateTimeOffset DateTimeOffsetField { get; set; } 39 | public Guid GuidField { get; set; } 40 | public TimeSpan TimeSpanField { get; set; } 41 | public Uri UrlField { get; set; } 42 | public string NullField { get; set; } 43 | public int[] IntArrayField { get; set; } 44 | public string[] StringArrayField { get; set; } 45 | public int[] EmptyArrayField { get; set; } 46 | public int[] NullArrayField { get; set; } 47 | public Dictionary DictionaryArrayField { get; set; } 48 | public object[] ObjectArrayField { get; set; } 49 | 50 | public override bool Equals(object obj) 51 | { 52 | var other = obj as BigTestObject; 53 | return this.Equals(other); 54 | } 55 | 56 | public override int GetHashCode() 57 | { 58 | unchecked 59 | { 60 | var hashCode = ByteField.GetHashCode(); 61 | hashCode = (hashCode * 397) ^ SByteField.GetHashCode(); 62 | hashCode = (hashCode * 397) ^ Int16Field.GetHashCode(); 63 | hashCode = (hashCode * 397) ^ UInt16Field.GetHashCode(); 64 | hashCode = (hashCode * 397) ^ Int32Field; 65 | hashCode = (hashCode * 397) ^ (int)UInt32Field; 66 | hashCode = (hashCode * 397) ^ Int64Field.GetHashCode(); 67 | hashCode = (hashCode * 397) ^ UInt64Field.GetHashCode(); 68 | hashCode = (hashCode * 397) ^ DecimalField.GetHashCode(); 69 | hashCode = (hashCode * 397) ^ SingleFiled.GetHashCode(); 70 | hashCode = (hashCode * 397) ^ DoubleField.GetHashCode(); 71 | hashCode = (hashCode * 397) ^ (StringField != null ? StringField.GetHashCode() : 0); 72 | hashCode = (hashCode * 397) ^ (int)MyEnumField; 73 | hashCode = (hashCode * 397) ^ BooleanField.GetHashCode(); 74 | hashCode = (hashCode * 397) ^ DateTimeField.GetHashCode(); 75 | hashCode = (hashCode * 397) ^ DateTimeOffsetField.GetHashCode(); 76 | hashCode = (hashCode * 397) ^ GuidField.GetHashCode(); 77 | hashCode = (hashCode * 397) ^ TimeSpanField.GetHashCode(); 78 | hashCode = (hashCode * 397) ^ (UrlField != null ? UrlField.GetHashCode() : 0); 79 | hashCode = (hashCode * 397) ^ (NullField != null ? NullField.GetHashCode() : 0); 80 | hashCode = (hashCode * 397) ^ (IntArrayField != null ? IntArrayField.GetHashCode() : 0); 81 | hashCode = (hashCode * 397) ^ (StringArrayField != null ? StringArrayField.GetHashCode() : 0); 82 | hashCode = (hashCode * 397) ^ (EmptyArrayField != null ? EmptyArrayField.GetHashCode() : 0); 83 | hashCode = (hashCode * 397) ^ (NullArrayField != null ? NullArrayField.GetHashCode() : 0); 84 | hashCode = (hashCode * 397) ^ (DictionaryArrayField != null ? DictionaryArrayField.GetHashCode() : 0); 85 | hashCode = (hashCode * 397) ^ (ObjectArrayField != null ? ObjectArrayField.GetHashCode() : 0); 86 | return hashCode; 87 | } 88 | } 89 | 90 | public void Fill() 91 | { 92 | ByteField = 1; 93 | SByteField = 2; 94 | Int16Field = 3; 95 | UInt16Field = 4; 96 | Int32Field = 5; 97 | UInt32Field = 6; 98 | Int64Field = 7; 99 | UInt64Field = 8; 100 | DecimalField = 9; 101 | SingleFiled = 10; 102 | DoubleField = 11; 103 | StringField = "12"; 104 | MyEnumField = ConsoleColor.Cyan; 105 | BooleanField = true; 106 | DateTimeField = DateTime.UtcNow; 107 | DateTimeOffsetField = DateTime.UtcNow; 108 | GuidField = Guid.NewGuid(); 109 | TimeSpanField = TimeSpan.FromHours(12.3); 110 | UrlField = new Uri("http://sample.com/fr.ttt?hello=world"); 111 | NullField = null; 112 | IntArrayField = new int[] { 1, 2, 3 }; 113 | StringArrayField = new string[] { "1", "2" }; 114 | EmptyArrayField = new int[0]; 115 | NullArrayField = null; 116 | DictionaryArrayField = new Dictionary { { "a", 0 }, { "b", "c" } }; 117 | ObjectArrayField = new object[] { new object[] { new object() } }; 118 | } 119 | 120 | public bool Equals(BigTestObject other) 121 | { 122 | if (other == null) 123 | return false; 124 | 125 | return this.ByteField == other.ByteField && 126 | this.SByteField == other.SByteField && 127 | this.Int16Field == other.Int16Field && 128 | this.UInt16Field == other.UInt16Field && 129 | this.Int32Field == other.Int32Field && 130 | this.UInt32Field == other.UInt32Field && 131 | this.Int64Field == other.Int64Field && 132 | this.UInt64Field == other.UInt64Field && 133 | this.DecimalField == other.DecimalField && 134 | Math.Abs(this.SingleFiled - other.SingleFiled) < float.Epsilon && 135 | Math.Abs(this.DoubleField - other.DoubleField) < double.Epsilon && 136 | this.StringField == other.StringField && 137 | this.MyEnumField == other.MyEnumField && 138 | this.BooleanField == other.BooleanField && 139 | new TimeSpan(Math.Abs((this.DateTimeField - other.DateTimeField).Ticks)) < TimeSpan.FromSeconds(1) && 140 | new TimeSpan(Math.Abs((this.DateTimeOffsetField - other.DateTimeOffsetField).Ticks)) < TimeSpan.FromSeconds(1) && 141 | this.GuidField == other.GuidField && 142 | this.TimeSpanField == other.TimeSpanField && 143 | this.UrlField.Equals(other.UrlField) && 144 | this.NullField == other.NullField && 145 | this.IntArrayField.Length == other.IntArrayField.Length && 146 | this.StringArrayField.Length == other.StringArrayField.Length && 147 | this.EmptyArrayField.Length == other.EmptyArrayField.Length && 148 | this.NullArrayField == other.NullArrayField && 149 | this.DictionaryArrayField.Count == other.DictionaryArrayField.Count && 150 | this.ObjectArrayField.Length == other.ObjectArrayField.Length; 151 | } 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Scripts/Benchmark/BigTestObject.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: bd58a5d39b3d9f04bb0390fffc2b58a0 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Scripts/Benchmark/ByteCountingStream.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | 17 | // ReSharper disable once CheckNamespace 18 | namespace System.IO 19 | { 20 | class ByteCountingStream : Stream 21 | { 22 | private long length; 23 | private long position; 24 | 25 | public override bool CanRead { get { return false; } } 26 | public override bool CanSeek { get { return true; } } 27 | public override bool CanWrite { get { return true; } } 28 | public override long Length { get { return length; } } 29 | public override long Position { get { return position; } set { this.Seek(value, SeekOrigin.Begin); } } 30 | 31 | public override void Flush() 32 | { 33 | 34 | } 35 | 36 | public override int Read(byte[] buffer, int offset, int count) 37 | { 38 | throw new NotSupportedException(); 39 | } 40 | public override long Seek(long offset, SeekOrigin origin) 41 | { 42 | var value = offset; 43 | 44 | if (origin == SeekOrigin.End) 45 | this.position = this.length - offset; 46 | else if (origin == SeekOrigin.Current) 47 | this.position = this.position + offset; 48 | 49 | value = Math.Max(0, value); 50 | 51 | return (this.position = value); 52 | } 53 | public override void SetLength(long value) 54 | { 55 | this.length = value; 56 | if (this.position > value) 57 | this.position = value; 58 | } 59 | 60 | public override void Write(byte[] buffer, int offset, int count) 61 | { 62 | if (count < 0) 63 | throw new ArgumentOutOfRangeException("count"); 64 | 65 | this.position += count; 66 | 67 | if (this.position > this.length) 68 | this.length = this.position; 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Scripts/Benchmark/ByteCountingStream.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 7bc35f1618094684e837825f9de5828a 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Scripts/Benchmark/ITestObject.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Collections.Generic; 18 | using System.Linq; 19 | using System.Text; 20 | 21 | namespace Assets.Scripts.Benchmark 22 | { 23 | public interface ITestObject 24 | { 25 | void Fill(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Scripts/Benchmark/ITestObject.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: e31abfb739a52eb4dbf08923ee48b2a9 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Scripts/Benchmark/MediumTestObject.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using UnityEngine; 17 | 18 | namespace Assets.Scripts.Benchmark 19 | { 20 | public class MediumTestObject : ITestObject 21 | { 22 | public Vector3 Position { get; set; } 23 | public Quaternion Rotation { get; set; } 24 | 25 | public void Fill() 26 | { 27 | this.Position = new Vector3(10, 100, 1000); 28 | this.Rotation = new Quaternion(1, 100, 1000, 10000); 29 | } 30 | 31 | public override bool Equals(object obj) 32 | { 33 | return this.Equals(obj as MediumTestObject); 34 | } 35 | 36 | protected bool Equals(MediumTestObject other) 37 | { 38 | if (other == null) return false; 39 | 40 | return Position.Equals(other.Position) && Rotation.Equals(other.Rotation); 41 | } 42 | 43 | public override int GetHashCode() 44 | { 45 | unchecked 46 | { 47 | return (Position.GetHashCode() * 397) ^ Rotation.GetHashCode(); 48 | } 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Scripts/Benchmark/MediumTestObject.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: a2fc405e2e75f2c42bf0f03514cfdc99 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Scripts/Benchmark/SmallTestObject.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | 17 | using System; 18 | 19 | namespace Assets.Scripts.Benchmark 20 | { 21 | public class SmallTestObject : ITestObject 22 | { 23 | public int X { get; set; } 24 | public int Y { get; set; } 25 | public float Rotation { get; set; } 26 | 27 | public void Fill() 28 | { 29 | this.X = 100; 30 | this.Y = 500; 31 | this.Rotation = 1.45f; 32 | } 33 | 34 | public override bool Equals(object obj) 35 | { 36 | var other = obj as SmallTestObject; 37 | if (other == null) return false; 38 | 39 | return this.X == other.X && this.Y == other.Y && Math.Abs(this.Rotation - other.Rotation) < float.Epsilon; 40 | } 41 | 42 | protected bool Equals(SmallTestObject other) 43 | { 44 | return X == other.X && Y == other.Y && Rotation.Equals(other.Rotation); 45 | } 46 | 47 | public override int GetHashCode() 48 | { 49 | unchecked 50 | { 51 | var hashCode = X; 52 | hashCode = (hashCode*397) ^ Y; 53 | hashCode = (hashCode*397) ^ Rotation.GetHashCode(); 54 | return hashCode; 55 | } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Scripts/Benchmark/SmallTestObject.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: f200cbc58dc961444b7adeedf3236294 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Scripts/Example.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 593314a249b680b479f0d1d76a64c68a 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Scripts/Example/SerializeExample.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | 17 | using System.Collections.Generic; 18 | using System.IO; 19 | using GameDevWare.Serialization; 20 | using UnityEngine; 21 | 22 | namespace Assets.Scripts.Example 23 | { 24 | public static class SerializeExample 25 | { 26 | public static void SerializeToMsgPackMemoryStream() 27 | { 28 | try 29 | { 30 | var stream = new MemoryStream(); 31 | 32 | // write vector to stream 33 | MsgPack.Serialize(new { x = 1, y = 2 }, stream); 34 | // reset stream's position 35 | stream.Position = 0; 36 | // read vector from stream 37 | var vec = MsgPack.Deserialize(stream); 38 | // 39 | UnityEngine.Debug.Log("vec: " + vec); 40 | } 41 | catch(System.Exception e) 42 | { 43 | UnityEngine.Debug.LogError(e); 44 | } 45 | } 46 | 47 | public static void SerializeToJsonMemoryStream() 48 | { 49 | try 50 | { 51 | var stream = new MemoryStream(); 52 | 53 | // write object to stream 54 | Json.Serialize(new { pos = new Vector3(1, 1, 1), rot = new Quaternion(1, 1, 1, 1) }, stream); 55 | // reset stream's position 56 | stream.Position = 0; 57 | UnityEngine.Debug.Log( System.Text.Encoding.UTF8.GetString(stream.ToArray()) ); 58 | 59 | // read object from stream 60 | var myObject = Json.Deserialize>(stream); 61 | var pos = (IDictionary)myObject["pos"]; 62 | var rot = (IDictionary)myObject["rot"]; 63 | // 64 | UnityEngine.Debug.Log("pos x:y: " + pos["x"] + ":" + pos["y"]); 65 | 66 | } 67 | catch(System.Exception e) 68 | { 69 | UnityEngine.Debug.LogError(e); 70 | } 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.Unity/Assets/Scripts/Example/SerializeExample.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: fdeacb5a1d4f95546ad2f497ef24e48f 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25420.1 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameDevWare.Serialization", "GameDevWare.Serialization\GameDevWare.Serialization.csproj", "{485C9711-2A63-6FB5-985B-2615CE239054}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameDevWare.Serialization.Tests", "GameDevWare.Serialization.Tests\GameDevWare.Serialization.Tests.csproj", "{1317FFA5-80C9-49FC-A851-F93233DC1B81}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {485C9711-2A63-6FB5-985B-2615CE239054}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {485C9711-2A63-6FB5-985B-2615CE239054}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {485C9711-2A63-6FB5-985B-2615CE239054}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {485C9711-2A63-6FB5-985B-2615CE239054}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {1317FFA5-80C9-49FC-A851-F93233DC1B81}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {1317FFA5-80C9-49FC-A851-F93233DC1B81}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {1317FFA5-80C9-49FC-A851-F93233DC1B81}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {1317FFA5-80C9-49FC-A851-F93233DC1B81}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization/GameDevWare.Serialization.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net35;net45;netstandard2.0;netcoreapp2.0 5 | Denis Zykov 6 | 2.4.3 7 | bin\$(Configuration)\$(TargetFramework)\$(MSBuildProjectName).xml 8 | https://github.com/deniszykov/msgpack-unity3d 9 | https://raw.githubusercontent.com/deniszykov/msgpack-unity3d/master/License.md 10 | (c) Denis Zykov, GameDevWare 2019 11 | https://github.com/deniszykov/msgpack-unity3d 12 | git 13 | messagepack msgpack json binary serialization text unity3d aot 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization/GameDevWare.Serialization.csproj.DotSettings: -------------------------------------------------------------------------------- 1 |  2 | CSharp40 -------------------------------------------------------------------------------- /src/GameDevWare.Serialization/NonSerializedAttribute.cs: -------------------------------------------------------------------------------- 1 | #if NETSTANDARD 2 | using System; 3 | 4 | namespace GameDevWare.Serialization 5 | { 6 | [AttributeUsage(AttributeTargets.All)] 7 | internal class NonSerializedAttribute : Attribute 8 | { 9 | } 10 | } 11 | #endif 12 | -------------------------------------------------------------------------------- /src/GameDevWare.Serialization/SerializableAttribute.cs: -------------------------------------------------------------------------------- 1 | #if NETSTANDARD 2 | using System; 3 | 4 | namespace GameDevWare.Serialization 5 | { 6 | [AttributeUsage(AttributeTargets.All)] 7 | internal class SerializableAttribute : Attribute 8 | { 9 | } 10 | } 11 | #endif 12 | --------------------------------------------------------------------------------