diff --git a/Aetheria.Shared/Aetheria.Shared.csproj b/Aetheria.Shared/Aetheria.Shared.csproj index d67dba1e4..3783e7469 100644 --- a/Aetheria.Shared/Aetheria.Shared.csproj +++ b/Aetheria.Shared/Aetheria.Shared.csproj @@ -3,7 +3,7 @@ Compiles ServerShared and its dependencies from source with no Unity defines, so a successful build is the check that the simulation stays independent of the engine. Tools and test harnesses reference this project. --> - + netstandard2.1 9.0 disable @@ -18,7 +18,6 @@ - @@ -27,7 +26,5 @@ - - diff --git a/Assets/Plugins/MessagePack.meta b/Assets/Plugins/MessagePack.meta deleted file mode 100644 index 1afdd561d..000000000 --- a/Assets/Plugins/MessagePack.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 78d7ac1a75fbd3f4d91b72ac2de5f552 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Annotations.meta b/Assets/Plugins/MessagePack/Annotations.meta deleted file mode 100644 index aa53ddd27..000000000 --- a/Assets/Plugins/MessagePack/Annotations.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 258cef354b8273b4ca696ab53c01327a -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Annotations/Attributes.cs b/Assets/Plugins/MessagePack/Annotations/Attributes.cs deleted file mode 100644 index a30280823..000000000 --- a/Assets/Plugins/MessagePack/Annotations/Attributes.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack -{ - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = true)] - public class MessagePackObjectAttribute : Attribute - { - public bool KeyAsPropertyName { get; private set; } - - public MessagePackObjectAttribute(bool keyAsPropertyName = false) - { - this.KeyAsPropertyName = keyAsPropertyName; - } - } - - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] - public class KeyAttribute : Attribute - { - public int? IntKey { get; private set; } - - public string StringKey { get; private set; } - - public KeyAttribute(int x) - { - this.IntKey = x; - } - - public KeyAttribute(string x) - { - this.StringKey = x; - } - } - - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] - public class IgnoreMemberAttribute : Attribute - { - } - - [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class, AllowMultiple = true, Inherited = false)] - public class UnionAttribute : Attribute - { - public int Key { get; private set; } - - public Type SubType { get; private set; } - - public UnionAttribute(int key, Type subType) - { - this.Key = key; - this.SubType = subType; - } - } - - [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = true)] - public class SerializationConstructorAttribute : Attribute - { - } - - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] - public class MessagePackFormatterAttribute : Attribute - { - public Type FormatterType { get; private set; } - - public object[] Arguments { get; private set; } - - public MessagePackFormatterAttribute(Type formatterType) - { - this.FormatterType = formatterType; - } - - public MessagePackFormatterAttribute(Type formatterType, params object[] arguments) - { - this.FormatterType = formatterType; - this.Arguments = arguments; - } - } -} diff --git a/Assets/Plugins/MessagePack/Annotations/Attributes.cs.meta b/Assets/Plugins/MessagePack/Annotations/Attributes.cs.meta deleted file mode 100644 index 44ea4ea1e..000000000 --- a/Assets/Plugins/MessagePack/Annotations/Attributes.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: db21d74c4f54408a9acd69873192155c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Annotations/IMessagePackSerializationCallbackReceiver.cs b/Assets/Plugins/MessagePack/Annotations/IMessagePackSerializationCallbackReceiver.cs deleted file mode 100644 index 3b1daf4cc..000000000 --- a/Assets/Plugins/MessagePack/Annotations/IMessagePackSerializationCallbackReceiver.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -namespace MessagePack -{ - public interface IMessagePackSerializationCallbackReceiver - { - void OnBeforeSerialize(); - - void OnAfterDeserialize(); - } -} diff --git a/Assets/Plugins/MessagePack/Annotations/IMessagePackSerializationCallbackReceiver.cs.meta b/Assets/Plugins/MessagePack/Annotations/IMessagePackSerializationCallbackReceiver.cs.meta deleted file mode 100644 index c770043be..000000000 --- a/Assets/Plugins/MessagePack/Annotations/IMessagePackSerializationCallbackReceiver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ef32599edd0f43366891b8da5d4aed1e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/BitOperations.cs b/Assets/Plugins/MessagePack/BitOperations.cs deleted file mode 100644 index 09b2ca0dc..000000000 --- a/Assets/Plugins/MessagePack/BitOperations.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. -// - -#if !NETCOREAPP - -using System.Runtime.CompilerServices; - -// Some routines inspired by the Stanford Bit Twiddling Hacks by Sean Eron Anderson: -// http://graphics.stanford.edu/~seander/bithacks.html - -namespace System.Numerics -{ - /// - /// Utility methods for intrinsic bit-twiddling operations. - /// The methods use hardware intrinsics when available on the underlying platform, - /// otherwise they use optimized software fallbacks. - /// - internal static class BitOperations - { - /// - /// Rotates the specified value left by the specified number of bits. - /// Similar in behavior to the x86 instruction ROL. - /// - /// The value to rotate. - /// The number of bits to rotate by. - /// Any value outside the range [0..31] is treated as congruent mod 32. - /// The rotated value. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static uint RotateLeft(uint value, int offset) - => (value << offset) | (value >> (32 - offset)); - } -} - -#endif diff --git a/Assets/Plugins/MessagePack/BitOperations.cs.meta b/Assets/Plugins/MessagePack/BitOperations.cs.meta deleted file mode 100644 index 589ad79c1..000000000 --- a/Assets/Plugins/MessagePack/BitOperations.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3c1e411a42f526567af32d094a9de348 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/BufferWriter.cs b/Assets/Plugins/MessagePack/BufferWriter.cs deleted file mode 100644 index eba48fb11..000000000 --- a/Assets/Plugins/MessagePack/BufferWriter.cs +++ /dev/null @@ -1,260 +0,0 @@ -// // We want to keep this file as-is since it's shared with other repos. - -// Copyright (c) .NET Foundation. All rights reserved. -// Copyright (c) Andrew Arnott. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Buffers; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace MessagePack -{ - /// - /// A fast access struct that wraps . - /// - internal ref struct BufferWriter - { - /// - /// The underlying . - /// - private IBufferWriter _output; - - /// - /// The result of the last call to , less any bytes already "consumed" with . - /// Backing field for the property. - /// - private Span _span; - - /// - /// The result of the last call to , less any bytes already "consumed" with . - /// - private ArraySegment _segment; - - /// - /// The number of uncommitted bytes (all the calls to since the last call to ). - /// - private int _buffered; - - /// - /// The total number of bytes written with this writer. - /// Backing field for the property. - /// - private long _bytesCommitted; - - private SequencePool _sequencePool; - - private SequencePool.Rental _rental; - - /// - /// Initializes a new instance of the struct. - /// - /// The to be wrapped. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public BufferWriter(IBufferWriter output) - { - _buffered = 0; - _bytesCommitted = 0; - _output = output ?? throw new ArgumentNullException(nameof(output)); - - _sequencePool = default; - _rental = default; - - var memory = _output.GetMemoryCheckResult(); - MemoryMarshal.TryGetArray(memory, out _segment); - _span = memory.Span; - } - - /// - /// Initializes a new instance of the struct. - /// - /// The pool from which to draw an if required.. - /// An array to start with so we can avoid accessing the if possible. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal BufferWriter(SequencePool sequencePool, byte[] array) - { - _buffered = 0; - _bytesCommitted = 0; - _sequencePool = sequencePool ?? throw new ArgumentNullException(nameof(sequencePool)); - _rental = default; - _output = null; - - _segment = new ArraySegment(array); - _span = _segment.AsSpan(); - } - - /// - /// Gets the result of the last call to . - /// - public Span Span => _span; - - /// - /// Gets the total number of bytes written with this writer. - /// - public long BytesCommitted => _bytesCommitted; - - /// - /// Gets the underlying this instance. - /// - internal IBufferWriter UnderlyingWriter => _output; - - internal SequencePool.Rental SequenceRental => _rental; - - public Span GetSpan(int sizeHint) - { - Ensure(sizeHint); - return this.Span; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ref byte GetPointer(int sizeHint) - { - Ensure(sizeHint); - - if (_segment.Array != null) - { - return ref _segment.Array[_segment.Offset + _buffered]; - } - else - { - return ref _span.GetPinnableReference(); - } - } - - /// - /// Calls on the underlying writer - /// with the number of uncommitted bytes. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Commit() - { - var buffered = _buffered; - if (buffered > 0) - { - this.MigrateToSequence(); - - _bytesCommitted += buffered; - _buffered = 0; - _output.Advance(buffered); - _span = default; - } - } - - /// - /// Used to indicate that part of the buffer has been written to. - /// - /// The number of bytes written to. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Advance(int count) - { - _buffered += count; - _span = _span.Slice(count); - } - - /// - /// Copies the caller's buffer into this writer and calls with the length of the source buffer. - /// - /// The buffer to copy in. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(ReadOnlySpan source) - { - if (_span.Length >= source.Length) - { - source.CopyTo(_span); - Advance(source.Length); - } - else - { - WriteMultiBuffer(source); - } - } - - /// - /// Acquires a new buffer if necessary to ensure that some given number of bytes can be written to a single buffer. - /// - /// The number of bytes that must be allocated in a single buffer. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Ensure(int count = 1) - { - if (_span.Length < count) - { - EnsureMore(count); - } - } - - /// - /// Gets the span to the bytes written if they were never committed to the underlying buffer writer. - /// - /// - /// - internal bool TryGetUncommittedSpan(out ReadOnlySpan span) - { - if (this._sequencePool != null) - { - span = _segment.AsSpan(0, _buffered); - return true; - } - - span = default; - return false; - } - - /// - /// Gets a fresh span to write to, with an optional minimum size. - /// - /// The minimum size for the next requested buffer. - [MethodImpl(MethodImplOptions.NoInlining)] - private void EnsureMore(int count = 0) - { - if (_buffered > 0) - { - Commit(); - } - else - { - this.MigrateToSequence(); - } - - var memory = _output.GetMemoryCheckResult(count); - MemoryMarshal.TryGetArray(memory, out _segment); - _span = memory.Span; - } - - /// - /// Copies the caller's buffer into this writer, potentially across multiple buffers from the underlying writer. - /// - /// The buffer to copy into this writer. - private void WriteMultiBuffer(ReadOnlySpan source) - { - int copiedBytes = 0; - int bytesLeftToCopy = source.Length; - while (bytesLeftToCopy > 0) - { - if (_span.Length == 0) - { - EnsureMore(); - } - - var writable = Math.Min(bytesLeftToCopy, _span.Length); - source.Slice(copiedBytes, writable).CopyTo(_span); - copiedBytes += writable; - bytesLeftToCopy -= writable; - Advance(writable); - } - } - - private void MigrateToSequence() - { - if (this._sequencePool != null) - { - // We were writing to our private scratch memory, so we have to copy it into the actual writer. - _rental = _sequencePool.Rent(); - _output = _rental.Value; - var realSpan = _output.GetSpan(_buffered); - _segment.AsSpan(0, _buffered).CopyTo(realSpan); - _sequencePool = null; - } - } - } -} diff --git a/Assets/Plugins/MessagePack/BufferWriter.cs.meta b/Assets/Plugins/MessagePack/BufferWriter.cs.meta deleted file mode 100644 index a709cf6ca..000000000 --- a/Assets/Plugins/MessagePack/BufferWriter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 91a2222860edec5ff9ee6e4fe1af7668 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/ExtensionHeader.cs b/Assets/Plugins/MessagePack/ExtensionHeader.cs deleted file mode 100644 index 833e7299e..000000000 --- a/Assets/Plugins/MessagePack/ExtensionHeader.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; - -namespace MessagePack -{ -#if MESSAGEPACK_INTERNAL - internal -#else - public -#endif - struct ExtensionHeader : IEquatable - { - public sbyte TypeCode { get; private set; } - - public uint Length { get; private set; } - - public ExtensionHeader(sbyte typeCode, uint length) - { - this.TypeCode = typeCode; - this.Length = length; - } - - public ExtensionHeader(sbyte typeCode, int length) - { - this.TypeCode = typeCode; - this.Length = (uint)length; - } - - public bool Equals(ExtensionHeader other) => this.TypeCode == other.TypeCode && this.Length == other.Length; - } -} diff --git a/Assets/Plugins/MessagePack/ExtensionHeader.cs.meta b/Assets/Plugins/MessagePack/ExtensionHeader.cs.meta deleted file mode 100644 index b5af89635..000000000 --- a/Assets/Plugins/MessagePack/ExtensionHeader.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 92a76851178ab369fbc386556cb866ce -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/ExtensionResult.cs b/Assets/Plugins/MessagePack/ExtensionResult.cs deleted file mode 100644 index 780d9bbbc..000000000 --- a/Assets/Plugins/MessagePack/ExtensionResult.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; - -namespace MessagePack -{ -#if MESSAGEPACK_INTERNAL - internal -#else - public -#endif - struct ExtensionResult - { - public ExtensionResult(sbyte typeCode, Memory data) - { - this.TypeCode = typeCode; - this.Data = new ReadOnlySequence(data); - } - - public ExtensionResult(sbyte typeCode, ReadOnlySequence data) - { - this.TypeCode = typeCode; - this.Data = data; - } - - public sbyte TypeCode { get; private set; } - - public ReadOnlySequence Data { get; private set; } - - public ExtensionHeader Header => new ExtensionHeader(this.TypeCode, (uint)this.Data.Length); - } -} diff --git a/Assets/Plugins/MessagePack/ExtensionResult.cs.meta b/Assets/Plugins/MessagePack/ExtensionResult.cs.meta deleted file mode 100644 index cf5d492b8..000000000 --- a/Assets/Plugins/MessagePack/ExtensionResult.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 153f71ac242b4218d9debb5971c7b5d4 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Formatters.meta b/Assets/Plugins/MessagePack/Formatters.meta deleted file mode 100644 index 541f0d57c..000000000 --- a/Assets/Plugins/MessagePack/Formatters.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 4e7629820f4485c4790dbe9265bb2830 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Formatters/CollectionFormatter.cs b/Assets/Plugins/MessagePack/Formatters/CollectionFormatter.cs deleted file mode 100644 index 550c7f312..000000000 --- a/Assets/Plugins/MessagePack/Formatters/CollectionFormatter.cs +++ /dev/null @@ -1,1074 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Diagnostics; -using System.Linq; -using System.Runtime.InteropServices; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - public sealed class ArrayFormatter : IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, T[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - writer.WriteArrayHeader(value.Length); - - for (int i = 0; i < value.Length; i++) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, value[i], options); - } - } - } - - public T[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var len = reader.ReadArrayHeader(); - var array = new T[len]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < array.Length; i++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - array[i] = formatter.Deserialize(ref reader, options); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } - } - - public sealed class ByteArraySegmentFormatter : IMessagePackFormatter> - { - public static readonly ByteArraySegmentFormatter Instance = new ByteArraySegmentFormatter(); - - private ByteArraySegmentFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, ArraySegment value, MessagePackSerializerOptions options) - { - if (value.Array == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value); - } - } - - public ArraySegment Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadBytes() is ReadOnlySequence bytes ? new ArraySegment(bytes.ToArray()) : default; - } - } - - public sealed class ArraySegmentFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, ArraySegment value, MessagePackSerializerOptions options) - { - if (value.Array == null) - { - writer.WriteNil(); - } - else - { - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - writer.WriteArrayHeader(value.Count); - - T[] array = value.Array; - for (int i = 0; i < value.Count; i++) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - T item = array[value.Offset + i]; - formatter.Serialize(ref writer, item, options); - } - } - } - - public ArraySegment Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - T[] array = options.Resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - return new ArraySegment(array); - } - } - } - - // List is popular format, should avoid abstraction. - public sealed class ListFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, List value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var c = value.Count; - writer.WriteArrayHeader(c); - - for (int i = 0; i < c; i++) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, value[i], options); - } - } - } - - public List Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var len = reader.ReadArrayHeader(); - var list = new List((int)len); - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < len; i++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - list.Add(formatter.Deserialize(ref reader, options)); - } - } - finally - { - reader.Depth--; - } - - return list; - } - } - } - - public abstract class CollectionFormatterBase : IMessagePackFormatter - where TCollection : IEnumerable - where TEnumerator : IEnumerator - { - public void Serialize(ref MessagePackWriter writer, TCollection value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - // Optimize iteration(array is fastest) - if (value is TElement[] array) - { - writer.WriteArrayHeader(array.Length); - - foreach (TElement item in array) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, item, options); - } - } - else - { - // knows count or not. - var seqCount = this.GetCount(value); - if (seqCount != null) - { - writer.WriteArrayHeader(seqCount.Value); - - // Unity's foreach struct enumerator causes boxing so iterate manually. - using (var e = this.GetSourceEnumerator(value)) - { - while (e.MoveNext()) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, e.Current, options); - } - } - } - else - { - using (var scratchRental = SequencePool.Shared.Rent()) - { - var scratch = scratchRental.Value; - MessagePackWriter scratchWriter = writer.Clone(scratch); - var count = 0; - using (var e = this.GetSourceEnumerator(value)) - { - while (e.MoveNext()) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - count++; - formatter.Serialize(ref scratchWriter, e.Current, options); - } - } - - scratchWriter.Flush(); - writer.WriteArrayHeader(count); - writer.WriteRaw(scratch.AsReadOnlySequence); - } - } - } - } - } - - public TCollection Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default(TCollection); - } - else - { - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var len = reader.ReadArrayHeader(); - - TIntermediate list = this.Create(len, options); - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < len; i++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - this.Add(list, i, formatter.Deserialize(ref reader, options), options); - } - } - finally - { - reader.Depth--; - } - - return this.Complete(list); - } - } - - // abstraction for serialize - protected virtual int? GetCount(TCollection sequence) - { - var collection = sequence as ICollection; - if (collection != null) - { - return collection.Count; - } - else - { - var c2 = sequence as IReadOnlyCollection; - if (c2 != null) - { - return c2.Count; - } - } - - return null; - } - - // Some collections can use struct iterator, this is optimization path - protected abstract TEnumerator GetSourceEnumerator(TCollection source); - - // abstraction for deserialize - protected abstract TIntermediate Create(int count, MessagePackSerializerOptions options); - - protected abstract void Add(TIntermediate collection, int index, TElement value, MessagePackSerializerOptions options); - - protected abstract TCollection Complete(TIntermediate intermediateCollection); - } - - public abstract class CollectionFormatterBase : CollectionFormatterBase, TCollection> - where TCollection : IEnumerable - { - protected override IEnumerator GetSourceEnumerator(TCollection source) - { - return source.GetEnumerator(); - } - } - - public abstract class CollectionFormatterBase : CollectionFormatterBase - where TCollection : IEnumerable - { - protected sealed override TCollection Complete(TCollection intermediateCollection) - { - return intermediateCollection; - } - } - - public sealed class GenericCollectionFormatter : CollectionFormatterBase - where TCollection : ICollection, new() - { - protected override TCollection Create(int count, MessagePackSerializerOptions options) - { - return new TCollection(); - } - - protected override void Add(TCollection collection, int index, TElement value, MessagePackSerializerOptions options) - { - collection.Add(value); - } - } - - public sealed class LinkedListFormatter : CollectionFormatterBase, LinkedList.Enumerator, LinkedList> - { - protected override void Add(LinkedList collection, int index, T value, MessagePackSerializerOptions options) - { - collection.AddLast(value); - } - - protected override LinkedList Complete(LinkedList intermediateCollection) - { - return intermediateCollection; - } - - protected override LinkedList Create(int count, MessagePackSerializerOptions options) - { - return new LinkedList(); - } - - protected override LinkedList.Enumerator GetSourceEnumerator(LinkedList source) - { - return source.GetEnumerator(); - } - } - - public sealed class QueueFormatter : CollectionFormatterBase, Queue.Enumerator, Queue> - { - protected override int? GetCount(Queue sequence) - { - return sequence.Count; - } - - protected override void Add(Queue collection, int index, T value, MessagePackSerializerOptions options) - { - collection.Enqueue(value); - } - - protected override Queue Create(int count, MessagePackSerializerOptions options) - { - return new Queue(count); - } - - protected override Queue.Enumerator GetSourceEnumerator(Queue source) - { - return source.GetEnumerator(); - } - - protected override Queue Complete(Queue intermediateCollection) - { - return intermediateCollection; - } - } - - // should deserialize reverse order. - public sealed class StackFormatter : CollectionFormatterBase.Enumerator, Stack> - { - protected override int? GetCount(Stack sequence) - { - return sequence.Count; - } - - protected override void Add(T[] collection, int index, T value, MessagePackSerializerOptions options) - { - // add reverse - collection[collection.Length - 1 - index] = value; - } - - protected override T[] Create(int count, MessagePackSerializerOptions options) - { - return new T[count]; - } - - protected override Stack.Enumerator GetSourceEnumerator(Stack source) - { - return source.GetEnumerator(); - } - - protected override Stack Complete(T[] intermediateCollection) - { - return new Stack(intermediateCollection); - } - } - - public sealed class HashSetFormatter : CollectionFormatterBase, HashSet.Enumerator, HashSet> - { - protected override int? GetCount(HashSet sequence) - { - return sequence.Count; - } - - protected override void Add(HashSet collection, int index, T value, MessagePackSerializerOptions options) - { - collection.Add(value); - } - - protected override HashSet Complete(HashSet intermediateCollection) - { - return intermediateCollection; - } - - protected override HashSet Create(int count, MessagePackSerializerOptions options) - { - return new HashSet(options.Security.GetEqualityComparer()); - } - - protected override HashSet.Enumerator GetSourceEnumerator(HashSet source) - { - return source.GetEnumerator(); - } - } - - public sealed class ReadOnlyCollectionFormatter : CollectionFormatterBase> - { - protected override void Add(T[] collection, int index, T value, MessagePackSerializerOptions options) - { - collection[index] = value; - } - - protected override ReadOnlyCollection Complete(T[] intermediateCollection) - { - return new ReadOnlyCollection(intermediateCollection); - } - - protected override T[] Create(int count, MessagePackSerializerOptions options) - { - return new T[count]; - } - } - - [Obsolete("Use " + nameof(InterfaceListFormatter2) + " instead.")] - public sealed class InterfaceListFormatter : CollectionFormatterBase> - { - protected override void Add(T[] collection, int index, T value, MessagePackSerializerOptions options) - { - collection[index] = value; - } - - protected override T[] Create(int count, MessagePackSerializerOptions options) - { - return new T[count]; - } - - protected override IList Complete(T[] intermediateCollection) - { - return intermediateCollection; - } - } - - [Obsolete("Use " + nameof(InterfaceCollectionFormatter2) + " instead.")] - public sealed class InterfaceCollectionFormatter : CollectionFormatterBase> - { - protected override void Add(T[] collection, int index, T value, MessagePackSerializerOptions options) - { - collection[index] = value; - } - - protected override T[] Create(int count, MessagePackSerializerOptions options) - { - return new T[count]; - } - - protected override ICollection Complete(T[] intermediateCollection) - { - return intermediateCollection; - } - } - - public sealed class InterfaceListFormatter2 : CollectionFormatterBase, IList> - { - protected override void Add(List collection, int index, T value, MessagePackSerializerOptions options) - { - collection.Add(value); - } - - protected override List Create(int count, MessagePackSerializerOptions options) - { - return new List(count); - } - - protected override IList Complete(List intermediateCollection) - { - return intermediateCollection; - } - } - - public sealed class InterfaceCollectionFormatter2 : CollectionFormatterBase, ICollection> - { - protected override void Add(List collection, int index, T value, MessagePackSerializerOptions options) - { - collection.Add(value); - } - - protected override List Create(int count, MessagePackSerializerOptions options) - { - return new List(count); - } - - protected override ICollection Complete(List intermediateCollection) - { - return intermediateCollection; - } - } - - public sealed class InterfaceEnumerableFormatter : CollectionFormatterBase> - { - protected override void Add(T[] collection, int index, T value, MessagePackSerializerOptions options) - { - collection[index] = value; - } - - protected override T[] Create(int count, MessagePackSerializerOptions options) - { - return new T[count]; - } - - protected override IEnumerable Complete(T[] intermediateCollection) - { - return intermediateCollection; - } - } - - // [Key, [Array]] - public sealed class InterfaceGroupingFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, IGrouping value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(2); - options.Resolver.GetFormatterWithVerify().Serialize(ref writer, value.Key, options); - options.Resolver.GetFormatterWithVerify>().Serialize(ref writer, value, options); - } - } - - public IGrouping Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - var count = reader.ReadArrayHeader(); - - if (count != 2) - { - throw new MessagePackSerializationException("Invalid Grouping format."); - } - - options.Security.DepthStep(ref reader); - try - { - TKey key = options.Resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - IEnumerable value = options.Resolver.GetFormatterWithVerify>().Deserialize(ref reader, options); - return new Grouping(key, value); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class InterfaceLookupFormatter : CollectionFormatterBase, Dictionary>, ILookup> - { - protected override void Add(Dictionary> collection, int index, IGrouping value, MessagePackSerializerOptions options) - { - collection.Add(value.Key, value); - } - - protected override ILookup Complete(Dictionary> intermediateCollection) - { - return new Lookup(intermediateCollection); - } - - protected override Dictionary> Create(int count, MessagePackSerializerOptions options) - { - return new Dictionary>(count); - } - } - - internal class Grouping : IGrouping - { - private readonly TKey key; - private readonly IEnumerable elements; - - public Grouping(TKey key, IEnumerable elements) - { - this.key = key; - this.elements = elements; - } - - public TKey Key - { - get - { - return this.key; - } - } - - public IEnumerator GetEnumerator() - { - return this.elements.GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return this.elements.GetEnumerator(); - } - } - - internal class Lookup : ILookup - { - private readonly Dictionary> groupings; - - public Lookup(Dictionary> groupings) - { - this.groupings = groupings; - } - - public IEnumerable this[TKey key] - { - get - { - return this.groupings[key]; - } - } - - public int Count - { - get - { - return this.groupings.Count; - } - } - - public bool Contains(TKey key) - { - return this.groupings.ContainsKey(key); - } - - public IEnumerator> GetEnumerator() - { - return this.groupings.Values.GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return this.groupings.Values.GetEnumerator(); - } - } - - /* NonGenerics */ - - public sealed class NonGenericListFormatter : IMessagePackFormatter - where T : class, IList, new() - { - public void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - writer.WriteArrayHeader(value.Count); - foreach (var item in value) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, item, options); - } - } - - public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default(T); - } - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var count = reader.ReadArrayHeader(); - - var list = new T(); - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < count; i++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - list.Add(formatter.Deserialize(ref reader, options)); - } - } - finally - { - reader.Depth--; - } - - return list; - } - } - - public sealed class NonGenericInterfaceListFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new NonGenericInterfaceListFormatter(); - - private NonGenericInterfaceListFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, IList value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - writer.WriteArrayHeader(value.Count); - foreach (var item in value) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, item, options); - } - } - - public IList Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default(IList); - } - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var count = reader.ReadArrayHeader(); - - var list = new object[count]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < count; i++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - list[i] = formatter.Deserialize(ref reader, options); - } - } - finally - { - reader.Depth--; - } - - return list; - } - } - - public sealed class NonGenericDictionaryFormatter : IMessagePackFormatter - where T : class, IDictionary, new() - { - public void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - writer.WriteMapHeader(value.Count); - foreach (DictionaryEntry item in value) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, item.Key, options); - formatter.Serialize(ref writer, item.Value, options); - } - } - - public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var count = reader.ReadMapHeader(); - - var dict = CollectionHelpers.CreateHashCollection(count, options.Security.GetEqualityComparer()); - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < count; i++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - var key = formatter.Deserialize(ref reader, options); - var value = formatter.Deserialize(ref reader, options); - dict.Add(key, value); - } - } - finally - { - reader.Depth--; - } - - return dict; - } - } - - public sealed class NonGenericInterfaceDictionaryFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new NonGenericInterfaceDictionaryFormatter(); - - private NonGenericInterfaceDictionaryFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, IDictionary value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - writer.WriteMapHeader(value.Count); - foreach (DictionaryEntry item in value) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, item.Key, options); - formatter.Serialize(ref writer, item.Value, options); - } - } - - public IDictionary Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var count = reader.ReadMapHeader(); - - var dict = new Dictionary(count, options.Security.GetEqualityComparer()); - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < count; i++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - var key = formatter.Deserialize(ref reader, options); - var value = formatter.Deserialize(ref reader, options); - dict.Add(key, value); - } - } - finally - { - reader.Depth--; - } - - return dict; - } - } - - public sealed class ObservableCollectionFormatter : CollectionFormatterBase> - { - protected override void Add(ObservableCollection collection, int index, T value, MessagePackSerializerOptions options) - { - collection.Add(value); - } - - protected override ObservableCollection Create(int count, MessagePackSerializerOptions options) - { - return new ObservableCollection(); - } - } - - public sealed class ReadOnlyObservableCollectionFormatter : CollectionFormatterBase, ReadOnlyObservableCollection> - { - protected override void Add(ObservableCollection collection, int index, T value, MessagePackSerializerOptions options) - { - collection.Add(value); - } - - protected override ObservableCollection Create(int count, MessagePackSerializerOptions options) - { - return new ObservableCollection(); - } - - protected override ReadOnlyObservableCollection Complete(ObservableCollection intermediateCollection) - { - return new ReadOnlyObservableCollection(intermediateCollection); - } - } - - public sealed class InterfaceReadOnlyListFormatter : CollectionFormatterBase> - { - protected override void Add(T[] collection, int index, T value, MessagePackSerializerOptions options) - { - collection[index] = value; - } - - protected override T[] Create(int count, MessagePackSerializerOptions options) - { - return new T[count]; - } - - protected override IReadOnlyList Complete(T[] intermediateCollection) - { - return intermediateCollection; - } - } - - public sealed class InterfaceReadOnlyCollectionFormatter : CollectionFormatterBase> - { - protected override void Add(T[] collection, int index, T value, MessagePackSerializerOptions options) - { - collection[index] = value; - } - - protected override T[] Create(int count, MessagePackSerializerOptions options) - { - return new T[count]; - } - - protected override IReadOnlyCollection Complete(T[] intermediateCollection) - { - return intermediateCollection; - } - } - - public sealed class InterfaceSetFormatter : CollectionFormatterBase, ISet> - { - protected override void Add(HashSet collection, int index, T value, MessagePackSerializerOptions options) - { - collection.Add(value); - } - - protected override ISet Complete(HashSet intermediateCollection) - { - return intermediateCollection; - } - - protected override HashSet Create(int count, MessagePackSerializerOptions options) - { - return new HashSet(options.Security.GetEqualityComparer()); - } - } - - public sealed class ConcurrentBagFormatter : CollectionFormatterBase> - { - protected override int? GetCount(ConcurrentBag sequence) - { - return sequence.Count; - } - - protected override void Add(ConcurrentBag collection, int index, T value, MessagePackSerializerOptions options) - { - collection.Add(value); - } - - protected override ConcurrentBag Create(int count, MessagePackSerializerOptions options) - { - return new ConcurrentBag(); - } - } - - public sealed class ConcurrentQueueFormatter : CollectionFormatterBase> - { - protected override int? GetCount(ConcurrentQueue sequence) - { - return sequence.Count; - } - - protected override void Add(ConcurrentQueue collection, int index, T value, MessagePackSerializerOptions options) - { - collection.Enqueue(value); - } - - protected override ConcurrentQueue Create(int count, MessagePackSerializerOptions options) - { - return new ConcurrentQueue(); - } - } - - public sealed class ConcurrentStackFormatter : CollectionFormatterBase> - { - protected override int? GetCount(ConcurrentStack sequence) - { - return sequence.Count; - } - - protected override void Add(T[] collection, int index, T value, MessagePackSerializerOptions options) - { - // add reverse - collection[collection.Length - 1 - index] = value; - } - - protected override T[] Create(int count, MessagePackSerializerOptions options) - { - return new T[count]; - } - - protected override ConcurrentStack Complete(T[] intermediateCollection) - { - return new ConcurrentStack(intermediateCollection); - } - } -} diff --git a/Assets/Plugins/MessagePack/Formatters/CollectionFormatter.cs.meta b/Assets/Plugins/MessagePack/Formatters/CollectionFormatter.cs.meta deleted file mode 100644 index 7254af620..000000000 --- a/Assets/Plugins/MessagePack/Formatters/CollectionFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f92b8946eec0ab476a689a0dfa8c2498 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Formatters/CollectionHelpers`2.cs b/Assets/Plugins/MessagePack/Formatters/CollectionHelpers`2.cs deleted file mode 100644 index bb1a3c6d1..000000000 --- a/Assets/Plugins/MessagePack/Formatters/CollectionHelpers`2.cs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Linq.Expressions; - -namespace MessagePack.Formatters -{ - /// - /// Provides general helpers for creating collections (including dictionaries). - /// - /// The concrete type of collection to create. - /// The type of equality comparer that we would hope to pass into the collection's constructor. - internal static class CollectionHelpers - where TCollection : new() - { - /// - /// The delegate that will create the collection, if the typical (int count, IEqualityComparer{T} equalityComparer) constructor was found. - /// - private static Func collectionCreator; - - /// - /// Initializes static members of the class. - /// - /// - /// Initializes a delegate that is optimized to create a collection of a given size and using the given equality comparer, if possible. - /// - static CollectionHelpers() - { - var ctor = typeof(TCollection).GetConstructor(new Type[] { typeof(int), typeof(TEqualityComparer) }); - if (ctor != null) - { - ParameterExpression param1 = Expression.Parameter(typeof(int), "count"); - ParameterExpression param2 = Expression.Parameter(typeof(TEqualityComparer), "equalityComparer"); - NewExpression body = Expression.New(ctor, param1, param2); - collectionCreator = Expression.Lambda>(body, param1, param2).Compile(); - } - } - - /// - /// Initializes a new instance of the collection. - /// - /// The number of elements the collection should be prepared to receive. - /// The equality comparer to initialize the collection with. - /// The newly initialized collection. - /// - /// Use of the and are a best effort. - /// If we can't find a constructor on the collection in the expected shape, we'll just instantiate the collection with its default constructor. - /// - internal static TCollection CreateHashCollection(int count, TEqualityComparer equalityComparer) => collectionCreator != null ? collectionCreator.Invoke(count, equalityComparer) : new TCollection(); - } -} diff --git a/Assets/Plugins/MessagePack/Formatters/CollectionHelpers`2.cs.meta b/Assets/Plugins/MessagePack/Formatters/CollectionHelpers`2.cs.meta deleted file mode 100644 index d61034b79..000000000 --- a/Assets/Plugins/MessagePack/Formatters/CollectionHelpers`2.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 25f9fe82ddb369c8f9600901293b80f8 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Formatters/DateTimeFormatters.cs b/Assets/Plugins/MessagePack/Formatters/DateTimeFormatters.cs deleted file mode 100644 index e7d948109..000000000 --- a/Assets/Plugins/MessagePack/Formatters/DateTimeFormatters.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - /// - /// Serialize by .NET native DateTime binary format. - /// - public sealed class NativeDateTimeFormatter : IMessagePackFormatter - { - public static readonly NativeDateTimeFormatter Instance = new NativeDateTimeFormatter(); - - public void Serialize(ref MessagePackWriter writer, DateTime value, MessagePackSerializerOptions options) - { - var dateData = value.ToBinary(); - writer.Write(dateData); - } - - public DateTime Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - var dateData = reader.ReadInt64(); - return DateTime.FromBinary(dateData); - } - } - - public sealed class NativeDateTimeArrayFormatter : IMessagePackFormatter - { - public static readonly NativeDateTimeArrayFormatter Instance = new NativeDateTimeArrayFormatter(); - - public void Serialize(ref MessagePackWriter writer, DateTime[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i].ToBinary()); - } - } - } - - public DateTime[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - var len = reader.ReadArrayHeader(); - var array = new DateTime[len]; - for (int i = 0; i < array.Length; i++) - { - var dateData = reader.ReadInt64(); - array[i] = DateTime.FromBinary(dateData); - } - - return array; - } - } - } -} diff --git a/Assets/Plugins/MessagePack/Formatters/DateTimeFormatters.cs.meta b/Assets/Plugins/MessagePack/Formatters/DateTimeFormatters.cs.meta deleted file mode 100644 index 6dfbe36a6..000000000 --- a/Assets/Plugins/MessagePack/Formatters/DateTimeFormatters.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e28b94bd9483c36efae78067f97c65cb -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Formatters/DictionaryFormatter.cs b/Assets/Plugins/MessagePack/Formatters/DictionaryFormatter.cs deleted file mode 100644 index 4b9347a14..000000000 --- a/Assets/Plugins/MessagePack/Formatters/DictionaryFormatter.cs +++ /dev/null @@ -1,280 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Reflection; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - // unfortunately, can't use IDictionary because supports IReadOnlyDictionary. - public abstract class DictionaryFormatterBase : IMessagePackFormatter - where TDictionary : IEnumerable> - where TEnumerator : IEnumerator> - { - public void Serialize(ref MessagePackWriter writer, TDictionary value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - IFormatterResolver resolver = options.Resolver; - IMessagePackFormatter keyFormatter = resolver.GetFormatterWithVerify(); - IMessagePackFormatter valueFormatter = resolver.GetFormatterWithVerify(); - - int count; - { - var col = value as ICollection>; - if (col != null) - { - count = col.Count; - } - else - { - var col2 = value as IReadOnlyCollection>; - if (col2 != null) - { - count = col2.Count; - } - else - { - throw new MessagePackSerializationException("DictionaryFormatterBase's TDictionary supports only ICollection or IReadOnlyCollection"); - } - } - } - - writer.WriteMapHeader(count); - - TEnumerator e = this.GetSourceEnumerator(value); - try - { - while (e.MoveNext()) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - KeyValuePair item = e.Current; - keyFormatter.Serialize(ref writer, item.Key, options); - valueFormatter.Serialize(ref writer, item.Value, options); - } - } - finally - { - e.Dispose(); - } - } - } - - public TDictionary Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default(TDictionary); - } - else - { - IFormatterResolver resolver = options.Resolver; - IMessagePackFormatter keyFormatter = resolver.GetFormatterWithVerify(); - IMessagePackFormatter valueFormatter = resolver.GetFormatterWithVerify(); - - var len = reader.ReadMapHeader(); - - TIntermediate dict = this.Create(len, options); - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < len; i++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - TKey key = keyFormatter.Deserialize(ref reader, options); - - TValue value = valueFormatter.Deserialize(ref reader, options); - - this.Add(dict, i, key, value, options); - } - } - finally - { - reader.Depth--; - } - - return this.Complete(dict); - } - } - - // abstraction for serialize - - // Some collections can use struct iterator, this is optimization path - protected abstract TEnumerator GetSourceEnumerator(TDictionary source); - - // abstraction for deserialize - protected abstract TIntermediate Create(int count, MessagePackSerializerOptions options); - - protected abstract void Add(TIntermediate collection, int index, TKey key, TValue value, MessagePackSerializerOptions options); - - protected abstract TDictionary Complete(TIntermediate intermediateCollection); - } - - public abstract class DictionaryFormatterBase : DictionaryFormatterBase>, TDictionary> - where TDictionary : IEnumerable> - { - protected override IEnumerator> GetSourceEnumerator(TDictionary source) - { - return source.GetEnumerator(); - } - } - - public abstract class DictionaryFormatterBase : DictionaryFormatterBase - where TDictionary : IDictionary - { - protected override TDictionary Complete(TDictionary intermediateCollection) - { - return intermediateCollection; - } - } - - public sealed class DictionaryFormatter : DictionaryFormatterBase, Dictionary.Enumerator, Dictionary> - { - protected override void Add(Dictionary collection, int index, TKey key, TValue value, MessagePackSerializerOptions options) - { - collection.Add(key, value); - } - - protected override Dictionary Complete(Dictionary intermediateCollection) - { - return intermediateCollection; - } - - protected override Dictionary Create(int count, MessagePackSerializerOptions options) - { - return new Dictionary(count, options.Security.GetEqualityComparer()); - } - - protected override Dictionary.Enumerator GetSourceEnumerator(Dictionary source) - { - return source.GetEnumerator(); - } - } - - public sealed class GenericDictionaryFormatter : DictionaryFormatterBase - where TDictionary : IDictionary, new() - { - protected override void Add(TDictionary collection, int index, TKey key, TValue value, MessagePackSerializerOptions options) - { - collection.Add(key, value); - } - - protected override TDictionary Create(int count, MessagePackSerializerOptions options) - { - return CollectionHelpers>.CreateHashCollection(count, options.Security.GetEqualityComparer()); - } - } - - public sealed class InterfaceDictionaryFormatter : DictionaryFormatterBase, IDictionary> - { - protected override void Add(Dictionary collection, int index, TKey key, TValue value, MessagePackSerializerOptions options) - { - collection.Add(key, value); - } - - protected override Dictionary Create(int count, MessagePackSerializerOptions options) - { - return new Dictionary(count, options.Security.GetEqualityComparer()); - } - - protected override IDictionary Complete(Dictionary intermediateCollection) - { - return intermediateCollection; - } - } - - public sealed class SortedListFormatter : DictionaryFormatterBase> - { - protected override void Add(SortedList collection, int index, TKey key, TValue value, MessagePackSerializerOptions options) - { - collection.Add(key, value); - } - - protected override SortedList Create(int count, MessagePackSerializerOptions options) - { - return new SortedList(count); - } - } - - public sealed class SortedDictionaryFormatter : DictionaryFormatterBase, SortedDictionary.Enumerator, SortedDictionary> - { - protected override void Add(SortedDictionary collection, int index, TKey key, TValue value, MessagePackSerializerOptions options) - { - collection.Add(key, value); - } - - protected override SortedDictionary Complete(SortedDictionary intermediateCollection) - { - return intermediateCollection; - } - - protected override SortedDictionary Create(int count, MessagePackSerializerOptions options) - { - return new SortedDictionary(); - } - - protected override SortedDictionary.Enumerator GetSourceEnumerator(SortedDictionary source) - { - return source.GetEnumerator(); - } - } - - public sealed class ReadOnlyDictionaryFormatter : DictionaryFormatterBase, ReadOnlyDictionary> - { - protected override void Add(Dictionary collection, int index, TKey key, TValue value, MessagePackSerializerOptions options) - { - collection.Add(key, value); - } - - protected override ReadOnlyDictionary Complete(Dictionary intermediateCollection) - { - return new ReadOnlyDictionary(intermediateCollection); - } - - protected override Dictionary Create(int count, MessagePackSerializerOptions options) - { - return new Dictionary(count, options.Security.GetEqualityComparer()); - } - } - - public sealed class InterfaceReadOnlyDictionaryFormatter : DictionaryFormatterBase, IReadOnlyDictionary> - { - protected override void Add(Dictionary collection, int index, TKey key, TValue value, MessagePackSerializerOptions options) - { - collection.Add(key, value); - } - - protected override IReadOnlyDictionary Complete(Dictionary intermediateCollection) - { - return intermediateCollection; - } - - protected override Dictionary Create(int count, MessagePackSerializerOptions options) - { - return new Dictionary(count, options.Security.GetEqualityComparer()); - } - } - - public sealed class ConcurrentDictionaryFormatter : DictionaryFormatterBase> - { - protected override void Add(ConcurrentDictionary collection, int index, TKey key, TValue value, MessagePackSerializerOptions options) - { - collection.TryAdd(key, value); - } - - protected override ConcurrentDictionary Create(int count, MessagePackSerializerOptions options) - { - // concurrent dictionary can't access defaultConcurrecyLevel so does not use count overload. - return new ConcurrentDictionary(options.Security.GetEqualityComparer()); - } - } -} diff --git a/Assets/Plugins/MessagePack/Formatters/DictionaryFormatter.cs.meta b/Assets/Plugins/MessagePack/Formatters/DictionaryFormatter.cs.meta deleted file mode 100644 index c78f568e9..000000000 --- a/Assets/Plugins/MessagePack/Formatters/DictionaryFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3f0984a238b11bd2c97eb781371bb121 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Formatters/DynamicObjectTypeFallbackFormatter.cs b/Assets/Plugins/MessagePack/Formatters/DynamicObjectTypeFallbackFormatter.cs deleted file mode 100644 index 5bd6d77df..000000000 --- a/Assets/Plugins/MessagePack/Formatters/DynamicObjectTypeFallbackFormatter.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Linq.Expressions; -using System.Reflection; - -namespace MessagePack.Formatters -{ - /// - /// This formatter can serialize any value whose static type is - /// for which another resolver can provide a formatter for the runtime type. - /// Its deserialization is limited to forwarding all calls to the . - /// - public sealed class DynamicObjectTypeFallbackFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new DynamicObjectTypeFallbackFormatter(); - - private delegate void SerializeMethod(object dynamicFormatter, ref MessagePackWriter writer, object value, MessagePackSerializerOptions options); - - private static readonly Internal.ThreadsafeTypeKeyHashTable SerializerDelegates = new Internal.ThreadsafeTypeKeyHashTable(); - - private DynamicObjectTypeFallbackFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, object value, MessagePackSerializerOptions options) - { - if (value is null) - { - writer.WriteNil(); - return; - } - - Type type = value.GetType(); - TypeInfo ti = type.GetTypeInfo(); - - if (type == typeof(object)) - { - // serialize to empty map - writer.WriteMapHeader(0); - return; - } - - object formatter = options.Resolver.GetFormatterDynamicWithVerify(type); - if (!SerializerDelegates.TryGetValue(type, out SerializeMethod serializerDelegate)) - { - lock (SerializerDelegates) - { - if (!SerializerDelegates.TryGetValue(type, out serializerDelegate)) - { - Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(type); - ParameterExpression param0 = Expression.Parameter(typeof(object), "formatter"); - ParameterExpression param1 = Expression.Parameter(typeof(MessagePackWriter).MakeByRefType(), "writer"); - ParameterExpression param2 = Expression.Parameter(typeof(object), "value"); - ParameterExpression param3 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - - MethodInfo serializeMethodInfo = formatterType.GetRuntimeMethod("Serialize", new[] { typeof(MessagePackWriter).MakeByRefType(), type, typeof(MessagePackSerializerOptions) }); - - MethodCallExpression body = Expression.Call( - Expression.Convert(param0, formatterType), - serializeMethodInfo, - param1, - ti.IsValueType ? Expression.Unbox(param2, type) : Expression.Convert(param2, type), - param3); - - serializerDelegate = Expression.Lambda(body, param0, param1, param2, param3).Compile(); - - SerializerDelegates.TryAdd(type, serializerDelegate); - } - } - } - - serializerDelegate(formatter, ref writer, value, options); - } - - public object Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return PrimitiveObjectFormatter.Instance.Deserialize(ref reader, options); - } - } -} diff --git a/Assets/Plugins/MessagePack/Formatters/DynamicObjectTypeFallbackFormatter.cs.meta b/Assets/Plugins/MessagePack/Formatters/DynamicObjectTypeFallbackFormatter.cs.meta deleted file mode 100644 index a5400f97b..000000000 --- a/Assets/Plugins/MessagePack/Formatters/DynamicObjectTypeFallbackFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bc47abc7cd51279d9ac40fe1da6ffa1d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Formatters/EnumAsStringFormatter`1.cs b/Assets/Plugins/MessagePack/Formatters/EnumAsStringFormatter`1.cs deleted file mode 100644 index 933396618..000000000 --- a/Assets/Plugins/MessagePack/Formatters/EnumAsStringFormatter`1.cs +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Runtime.Serialization; - -namespace MessagePack.Formatters -{ - // Note:This implementation is 'not' fastest, should more improve. - public sealed class EnumAsStringFormatter : IMessagePackFormatter - { - private readonly IReadOnlyDictionary nameValueMapping; - private readonly IReadOnlyDictionary valueNameMapping; - private readonly IReadOnlyDictionary clrToSerializationName; - private readonly IReadOnlyDictionary serializationToClrName; - private readonly bool enumMemberOverridesPresent; - private readonly bool isFlags; - - public EnumAsStringFormatter() - { - this.isFlags = typeof(T).GetCustomAttribute() is object; - - var fields = typeof(T).GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static); - var nameValueMapping = new Dictionary(fields.Length); - var valueNameMapping = new Dictionary(); - Dictionary clrToSerializationName = null; - Dictionary serializationToClrName = null; - - foreach (FieldInfo enumValueMember in fields) - { - string name = enumValueMember.Name; - T value = (T)enumValueMember.GetValue(null); - - // Consider the case where the serialized form of the enum value is overridden via an attribute. - var attribute = enumValueMember.GetCustomAttribute(); - if (attribute?.IsValueSetExplicitly ?? false) - { - clrToSerializationName = clrToSerializationName ?? new Dictionary(); - serializationToClrName = serializationToClrName ?? new Dictionary(); - - clrToSerializationName.Add(name, attribute.Value); - serializationToClrName.Add(attribute.Value, name); - - name = attribute.Value; - this.enumMemberOverridesPresent = true; - } - - nameValueMapping[name] = value; - valueNameMapping[value] = name; - } - - this.nameValueMapping = nameValueMapping; - this.valueNameMapping = valueNameMapping; - this.clrToSerializationName = clrToSerializationName; - this.serializationToClrName = serializationToClrName; - } - - public void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options) - { - // Enum.ToString() is slow, so avoid it when we can. - if (!this.valueNameMapping.TryGetValue(value, out string valueString)) - { - // fallback for flags, values with no name, etc - valueString = this.GetSerializedNames(value.ToString()); - } - - writer.Write(valueString); - } - - public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - string name = reader.ReadString(); - - // Avoid Enum.Parse when we can because it is too slow. - if (!this.nameValueMapping.TryGetValue(name, out T value)) - { - value = (T)Enum.Parse(typeof(T), this.GetClrNames(name)); - } - - return value; - } - - private string GetClrNames(string serializedNames) - { - if (this.enumMemberOverridesPresent && this.isFlags && serializedNames.IndexOf(", ", StringComparison.Ordinal) >= 0) - { - return Translate(serializedNames, this.serializationToClrName); - } - - // We don't need to consider the trivial case of no commas because our caller would have found that in the lookup table and not called us. - return serializedNames; - } - - private string GetSerializedNames(string clrNames) - { - if (this.enumMemberOverridesPresent && this.isFlags && clrNames.IndexOf(", ", StringComparison.Ordinal) >= 0) - { - return Translate(clrNames, this.clrToSerializationName); - } - - // We don't need to consider the trivial case of no commas because our caller would have found that in the lookup table and not called us. - return clrNames; - } - - private static string Translate(string items, IReadOnlyDictionary mapping) - { - string[] elements = items.Split(','); - - for (int i = 0; i < elements.Length; i++) - { - // Trim the leading space if there is one (due to the delimiter being ", "). - if (i > 0 && elements[i].Length > 0 && elements[i][0] == ' ') - { - elements[i] = elements[i].Substring(1); - } - - if (mapping.TryGetValue(elements[i], out string substituteValue)) - { - elements[i] = substituteValue; - } - } - - return string.Join(", ", elements); - } - } -} diff --git a/Assets/Plugins/MessagePack/Formatters/EnumAsStringFormatter`1.cs.meta b/Assets/Plugins/MessagePack/Formatters/EnumAsStringFormatter`1.cs.meta deleted file mode 100644 index 8c34d09c4..000000000 --- a/Assets/Plugins/MessagePack/Formatters/EnumAsStringFormatter`1.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f7cdc1e759af9873989648baa08f0350 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Formatters/GenericEnumFormatter`1.cs b/Assets/Plugins/MessagePack/Formatters/GenericEnumFormatter`1.cs deleted file mode 100644 index 02c64fa33..000000000 --- a/Assets/Plugins/MessagePack/Formatters/GenericEnumFormatter`1.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Runtime.CompilerServices; - -namespace MessagePack.Formatters -{ - public sealed class GenericEnumFormatter : IMessagePackFormatter - where T : Enum - { - private delegate void EnumSerialize(ref MessagePackWriter writer, ref T value); - - private delegate T EnumDeserialize(ref MessagePackReader reader); - - private readonly EnumSerialize serializer; - private readonly EnumDeserialize deserializer; - - public GenericEnumFormatter() - { - var underlyingType = typeof(T).GetEnumUnderlyingType(); - switch (Type.GetTypeCode(underlyingType)) - { -#pragma warning disable SA1107 // Avoid multiple statements on same line. - case TypeCode.Byte: - serializer = (ref MessagePackWriter writer, ref T value) => writer.Write(Unsafe.As(ref value)); - deserializer = (ref MessagePackReader reader) => { var v = reader.ReadByte(); return Unsafe.As(ref v); }; - break; - case TypeCode.Int16: - serializer = (ref MessagePackWriter writer, ref T value) => writer.Write(Unsafe.As(ref value)); - deserializer = (ref MessagePackReader reader) => { var v = reader.ReadInt16(); return Unsafe.As(ref v); }; - break; - case TypeCode.Int32: - serializer = (ref MessagePackWriter writer, ref T value) => writer.Write(Unsafe.As(ref value)); - deserializer = (ref MessagePackReader reader) => { var v = reader.ReadInt32(); return Unsafe.As(ref v); }; - break; - case TypeCode.Int64: - serializer = (ref MessagePackWriter writer, ref T value) => writer.Write(Unsafe.As(ref value)); - deserializer = (ref MessagePackReader reader) => { var v = reader.ReadInt64(); return Unsafe.As(ref v); }; - break; - case TypeCode.SByte: - serializer = (ref MessagePackWriter writer, ref T value) => writer.Write(Unsafe.As(ref value)); - deserializer = (ref MessagePackReader reader) => { var v = reader.ReadSByte(); return Unsafe.As(ref v); }; - break; - case TypeCode.UInt16: - serializer = (ref MessagePackWriter writer, ref T value) => writer.Write(Unsafe.As(ref value)); - deserializer = (ref MessagePackReader reader) => { var v = reader.ReadUInt16(); return Unsafe.As(ref v); }; - break; - case TypeCode.UInt32: - serializer = (ref MessagePackWriter writer, ref T value) => writer.Write(Unsafe.As(ref value)); - deserializer = (ref MessagePackReader reader) => { var v = reader.ReadUInt32(); return Unsafe.As(ref v); }; - break; - case TypeCode.UInt64: - serializer = (ref MessagePackWriter writer, ref T value) => writer.Write(Unsafe.As(ref value)); - deserializer = (ref MessagePackReader reader) => { var v = reader.ReadUInt64(); return Unsafe.As(ref v); }; - break; - default: - break; -#pragma warning restore SA1107 // Avoid multiple statements on same line. - } - } - - public void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options) - { - serializer(ref writer, ref value); - } - - public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return deserializer(ref reader); - } - } -} diff --git a/Assets/Plugins/MessagePack/Formatters/GenericEnumFormatter`1.cs.meta b/Assets/Plugins/MessagePack/Formatters/GenericEnumFormatter`1.cs.meta deleted file mode 100644 index 8b435a6bd..000000000 --- a/Assets/Plugins/MessagePack/Formatters/GenericEnumFormatter`1.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 7f3275d9a9f3275ec9cc43d6859964fe -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Formatters/IMessagePackFormatter`1.cs b/Assets/Plugins/MessagePack/Formatters/IMessagePackFormatter`1.cs deleted file mode 100644 index 510d2d143..000000000 --- a/Assets/Plugins/MessagePack/Formatters/IMessagePackFormatter`1.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Buffers; -using System.ComponentModel; - -namespace MessagePack.Formatters -{ -#pragma warning disable SA1649 // File name should match first type name - /// - /// A base interface for so that all generic implementations - /// can be detected by a common base type. - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public interface IMessagePackFormatter - { - } -#pragma warning restore SA1649 // File name should match first type name - - /// - /// The contract for serialization of some specific type. - /// - /// The type to be serialized or deserialized. - public interface IMessagePackFormatter : IMessagePackFormatter - { - /// - /// Serializes a value. - /// - /// The writer to use when serializing the value. - /// The value to be serialized. - /// The serialization settings to use, including the resolver to use to obtain formatters for types that make up the composite type . - void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options); - - /// - /// Deserializes a value. - /// - /// The reader to deserialize from. - /// The serialization settings to use, including the resolver to use to obtain formatters for types that make up the composite type . - /// The deserialized value. - T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options); - } -} diff --git a/Assets/Plugins/MessagePack/Formatters/IMessagePackFormatter`1.cs.meta b/Assets/Plugins/MessagePack/Formatters/IMessagePackFormatter`1.cs.meta deleted file mode 100644 index e7cf1e01e..000000000 --- a/Assets/Plugins/MessagePack/Formatters/IMessagePackFormatter`1.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: cd75a2bcccf20dfb6824d447ec99a1fa -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Formatters/IgnoreFormatter`1.cs b/Assets/Plugins/MessagePack/Formatters/IgnoreFormatter`1.cs deleted file mode 100644 index 12e3857cb..000000000 --- a/Assets/Plugins/MessagePack/Formatters/IgnoreFormatter`1.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Buffers; - -namespace MessagePack.Formatters -{ - public sealed class IgnoreFormatter : IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options) - { - writer.WriteNil(); - } - - public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - reader.Skip(); - return default(T); - } - } -} diff --git a/Assets/Plugins/MessagePack/Formatters/IgnoreFormatter`1.cs.meta b/Assets/Plugins/MessagePack/Formatters/IgnoreFormatter`1.cs.meta deleted file mode 100644 index 9864e3b11..000000000 --- a/Assets/Plugins/MessagePack/Formatters/IgnoreFormatter`1.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 64fa7163708478803a466c61cdb596d6 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Formatters/MultiDimensionalArrayFormatter.cs b/Assets/Plugins/MessagePack/Formatters/MultiDimensionalArrayFormatter.cs deleted file mode 100644 index dfeb9d908..000000000 --- a/Assets/Plugins/MessagePack/Formatters/MultiDimensionalArrayFormatter.cs +++ /dev/null @@ -1,293 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections.Generic; -using System.Text; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - /* multi dimensional array serialize to [i, j, [seq]] */ - - public sealed class TwoDimensionalArrayFormatter : IMessagePackFormatter - { - private const int ArrayLength = 3; - - public void Serialize(ref MessagePackWriter writer, T[,] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - var i = value.GetLength(0); - var j = value.GetLength(1); - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - writer.WriteArrayHeader(ArrayLength); - writer.Write(i); - writer.Write(j); - - writer.WriteArrayHeader(value.Length); - foreach (T item in value) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, item, options); - } - } - } - - public T[,] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var len = reader.ReadArrayHeader(); - if (len != ArrayLength) - { - throw new MessagePackSerializationException("Invalid T[,] format"); - } - - var iLength = reader.ReadInt32(); - var jLength = reader.ReadInt32(); - var maxLen = reader.ReadArrayHeader(); - - var array = new T[iLength, jLength]; - - var i = 0; - var j = -1; - options.Security.DepthStep(ref reader); - try - { - for (int loop = 0; loop < maxLen; loop++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - if (j < jLength - 1) - { - j++; - } - else - { - j = 0; - i++; - } - - array[i, j] = formatter.Deserialize(ref reader, options); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } - } - - public sealed class ThreeDimensionalArrayFormatter : IMessagePackFormatter - { - private const int ArrayLength = 4; - - public void Serialize(ref MessagePackWriter writer, T[,,] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - var i = value.GetLength(0); - var j = value.GetLength(1); - var k = value.GetLength(2); - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - writer.WriteArrayHeader(ArrayLength); - writer.Write(i); - writer.Write(j); - writer.Write(k); - - writer.WriteArrayHeader(value.Length); - foreach (T item in value) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, item, options); - } - } - } - - public T[,,] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var len = reader.ReadArrayHeader(); - if (len != ArrayLength) - { - throw new MessagePackSerializationException("Invalid T[,,] format"); - } - - var iLength = reader.ReadInt32(); - var jLength = reader.ReadInt32(); - var kLength = reader.ReadInt32(); - var maxLen = reader.ReadArrayHeader(); - - var array = new T[iLength, jLength, kLength]; - - var i = 0; - var j = 0; - var k = -1; - options.Security.DepthStep(ref reader); - try - { - for (int loop = 0; loop < maxLen; loop++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - if (k < kLength - 1) - { - k++; - } - else if (j < jLength - 1) - { - k = 0; - j++; - } - else - { - k = 0; - j = 0; - i++; - } - - array[i, j, k] = formatter.Deserialize(ref reader, options); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } - } - - public sealed class FourDimensionalArrayFormatter : IMessagePackFormatter - { - private const int ArrayLength = 5; - - public void Serialize(ref MessagePackWriter writer, T[,,,] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - var i = value.GetLength(0); - var j = value.GetLength(1); - var k = value.GetLength(2); - var l = value.GetLength(3); - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - writer.WriteArrayHeader(ArrayLength); - writer.Write(i); - writer.Write(j); - writer.Write(k); - writer.Write(l); - - writer.WriteArrayHeader(value.Length); - foreach (T item in value) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, item, options); - } - } - } - - public T[,,,] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var len = reader.ReadArrayHeader(); - if (len != ArrayLength) - { - throw new MessagePackSerializationException("Invalid T[,,,] format"); - } - - var iLength = reader.ReadInt32(); - var jLength = reader.ReadInt32(); - var kLength = reader.ReadInt32(); - var lLength = reader.ReadInt32(); - var maxLen = reader.ReadArrayHeader(); - var array = new T[iLength, jLength, kLength, lLength]; - - var i = 0; - var j = 0; - var k = 0; - var l = -1; - options.Security.DepthStep(ref reader); - try - { - for (int loop = 0; loop < maxLen; loop++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - if (l < lLength - 1) - { - l++; - } - else if (k < kLength - 1) - { - l = 0; - k++; - } - else if (j < jLength - 1) - { - l = 0; - k = 0; - j++; - } - else - { - l = 0; - k = 0; - j = 0; - i++; - } - - array[i, j, k, l] = formatter.Deserialize(ref reader, options); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } - } -} diff --git a/Assets/Plugins/MessagePack/Formatters/MultiDimensionalArrayFormatter.cs.meta b/Assets/Plugins/MessagePack/Formatters/MultiDimensionalArrayFormatter.cs.meta deleted file mode 100644 index 1c33d133d..000000000 --- a/Assets/Plugins/MessagePack/Formatters/MultiDimensionalArrayFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8a4af86ee0f0a74de9e88b1fe8c9826d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Formatters/NilFormatter.cs b/Assets/Plugins/MessagePack/Formatters/NilFormatter.cs deleted file mode 100644 index 61aad63fe..000000000 --- a/Assets/Plugins/MessagePack/Formatters/NilFormatter.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -namespace MessagePack.Formatters -{ - public class NilFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new NilFormatter(); - - private NilFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Nil value, MessagePackSerializerOptions options) - { - writer.WriteNil(); - } - - public Nil Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadNil(); - } - } - - // NullableNil is same as Nil. - public class NullableNilFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new NullableNilFormatter(); - - private NullableNilFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Nil? value, MessagePackSerializerOptions options) - { - writer.WriteNil(); - } - - public Nil? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadNil(); - } - } -} diff --git a/Assets/Plugins/MessagePack/Formatters/NilFormatter.cs.meta b/Assets/Plugins/MessagePack/Formatters/NilFormatter.cs.meta deleted file mode 100644 index dfaeb7f32..000000000 --- a/Assets/Plugins/MessagePack/Formatters/NilFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 708c91d45dcbf19469504ec78aa2abee -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Formatters/NullableFormatter.cs b/Assets/Plugins/MessagePack/Formatters/NullableFormatter.cs deleted file mode 100644 index bba535aea..000000000 --- a/Assets/Plugins/MessagePack/Formatters/NullableFormatter.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Buffers; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - public sealed class NullableFormatter : IMessagePackFormatter - where T : struct - { - public void Serialize(ref MessagePackWriter writer, T? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - options.Resolver.GetFormatterWithVerify().Serialize(ref writer, value.Value, options); - } - } - - public T? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - reader.ReadNil(); - return null; - } - else - { - return options.Resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - } - } - } - - public sealed class StaticNullableFormatter : IMessagePackFormatter - where T : struct - { - private readonly IMessagePackFormatter underlyingFormatter; - - public StaticNullableFormatter(IMessagePackFormatter underlyingFormatter) - { - this.underlyingFormatter = underlyingFormatter; - } - - public void Serialize(ref MessagePackWriter writer, T? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - this.underlyingFormatter.Serialize(ref writer, value.Value, options); - } - } - - public T? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - return this.underlyingFormatter.Deserialize(ref reader, options); - } - } - } -} diff --git a/Assets/Plugins/MessagePack/Formatters/NullableFormatter.cs.meta b/Assets/Plugins/MessagePack/Formatters/NullableFormatter.cs.meta deleted file mode 100644 index 35681b6c6..000000000 --- a/Assets/Plugins/MessagePack/Formatters/NullableFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 88e906d65ee7d29d3ae1fb5865b8f6ab -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Formatters/PrimitiveObjectFormatter.cs b/Assets/Plugins/MessagePack/Formatters/PrimitiveObjectFormatter.cs deleted file mode 100644 index 4534bd9d2..000000000 --- a/Assets/Plugins/MessagePack/Formatters/PrimitiveObjectFormatter.cs +++ /dev/null @@ -1,337 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections.Generic; -using System.Reflection; - -namespace MessagePack.Formatters -{ - public sealed class PrimitiveObjectFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new PrimitiveObjectFormatter(); - - private static readonly Dictionary TypeToJumpCode = new Dictionary() - { - // When adding types whose size exceeds 32-bits, add support in MessagePackSecurity.GetHashCollisionResistantEqualityComparer() - { typeof(Boolean), 0 }, - { typeof(Char), 1 }, - { typeof(SByte), 2 }, - { typeof(Byte), 3 }, - { typeof(Int16), 4 }, - { typeof(UInt16), 5 }, - { typeof(Int32), 6 }, - { typeof(UInt32), 7 }, - { typeof(Int64), 8 }, - { typeof(UInt64), 9 }, - { typeof(Single), 10 }, - { typeof(Double), 11 }, - { typeof(DateTime), 12 }, - { typeof(string), 13 }, - { typeof(byte[]), 14 }, - }; - - private PrimitiveObjectFormatter() - { - } - -#if !UNITY_2018_3_OR_NEWER - - public static bool IsSupportedType(Type type, TypeInfo typeInfo, object value) - { - if (value == null) - { - return true; - } - - if (TypeToJumpCode.ContainsKey(type)) - { - return true; - } - - if (typeInfo.IsEnum) - { - return true; - } - - if (value is System.Collections.IDictionary) - { - return true; - } - - if (value is System.Collections.ICollection) - { - return true; - } - - return false; - } - -#endif - - public void Serialize(ref MessagePackWriter writer, object value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - Type t = value.GetType(); - - int code; - if (TypeToJumpCode.TryGetValue(t, out code)) - { - switch (code) - { - case 0: - writer.Write((bool)value); - return; - case 1: - writer.Write((char)value); - return; - case 2: - writer.WriteInt8((sbyte)value); - return; - case 3: - writer.WriteUInt8((byte)value); - return; - case 4: - writer.WriteInt16((Int16)value); - return; - case 5: - writer.WriteUInt16((UInt16)value); - return; - case 6: - writer.WriteInt32((Int32)value); - return; - case 7: - writer.WriteUInt32((UInt32)value); - return; - case 8: - writer.WriteInt64((Int64)value); - return; - case 9: - writer.WriteUInt64((UInt64)value); - return; - case 10: - writer.Write((Single)value); - return; - case 11: - writer.Write((double)value); - return; - case 12: - writer.Write((DateTime)value); - return; - case 13: - writer.Write((string)value); - return; - case 14: - writer.Write((byte[])value); - return; - default: - throw new MessagePackSerializationException("Not supported primitive object resolver. type:" + t.Name); - } - } - else - { -#if UNITY_2018_3_OR_NEWER && !NETFX_CORE - if (t.IsEnum) -#else - if (t.GetTypeInfo().IsEnum) -#endif - { - Type underlyingType = Enum.GetUnderlyingType(t); - var code2 = TypeToJumpCode[underlyingType]; - switch (code2) - { - case 2: - writer.WriteInt8((sbyte)value); - return; - case 3: - writer.WriteUInt8((byte)value); - return; - case 4: - writer.WriteInt16((Int16)value); - return; - case 5: - writer.WriteUInt16((UInt16)value); - return; - case 6: - writer.WriteInt32((Int32)value); - return; - case 7: - writer.WriteUInt32((UInt32)value); - return; - case 8: - writer.WriteInt64((Int64)value); - return; - case 9: - writer.WriteUInt64((UInt64)value); - return; - default: - break; - } - } - else if (value is System.Collections.IDictionary) - { - // check IDictionary first - var d = value as System.Collections.IDictionary; - writer.WriteMapHeader(d.Count); - foreach (System.Collections.DictionaryEntry item in d) - { - this.Serialize(ref writer, item.Key, options); - this.Serialize(ref writer, item.Value, options); - } - - return; - } - else if (value is System.Collections.ICollection) - { - var c = value as System.Collections.ICollection; - writer.WriteArrayHeader(c.Count); - foreach (var item in c) - { - this.Serialize(ref writer, item, options); - } - - return; - } - } - - throw new MessagePackSerializationException("Not supported primitive object resolver. type:" + t.Name); - } - - public object Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - MessagePackType type = reader.NextMessagePackType; - IFormatterResolver resolver = options.Resolver; - switch (type) - { - case MessagePackType.Integer: - var code = reader.NextCode; - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return reader.ReadSByte(); - } - else if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return reader.ReadByte(); - } - else if (code == MessagePackCode.Int8) - { - return reader.ReadSByte(); - } - else if (code == MessagePackCode.Int16) - { - return reader.ReadInt16(); - } - else if (code == MessagePackCode.Int32) - { - return reader.ReadInt32(); - } - else if (code == MessagePackCode.Int64) - { - return reader.ReadInt64(); - } - else if (code == MessagePackCode.UInt8) - { - return reader.ReadByte(); - } - else if (code == MessagePackCode.UInt16) - { - return reader.ReadUInt16(); - } - else if (code == MessagePackCode.UInt32) - { - return reader.ReadUInt32(); - } - else if (code == MessagePackCode.UInt64) - { - return reader.ReadUInt64(); - } - - throw new MessagePackSerializationException("Invalid primitive bytes."); - case MessagePackType.Boolean: - return reader.ReadBoolean(); - case MessagePackType.Float: - if (reader.NextCode == MessagePackCode.Float32) - { - return reader.ReadSingle(); - } - else - { - return reader.ReadDouble(); - } - - case MessagePackType.String: - return reader.ReadString(); - case MessagePackType.Binary: - // We must copy the sequence returned by ReadBytes since the reader's sequence is only valid during deserialization. - return reader.ReadBytes()?.ToArray(); - case MessagePackType.Extension: - ExtensionHeader ext = reader.ReadExtensionFormatHeader(); - if (ext.TypeCode == ReservedMessagePackExtensionTypeCode.DateTime) - { - return reader.ReadDateTime(ext); - } - - throw new MessagePackSerializationException("Invalid primitive bytes."); - case MessagePackType.Array: - { - var length = reader.ReadArrayHeader(); - - IMessagePackFormatter objectFormatter = resolver.GetFormatter(); - var array = new object[length]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < length; i++) - { - array[i] = objectFormatter.Deserialize(ref reader, options); - } - } - finally - { - reader.Depth--; - } - - return array; - } - - case MessagePackType.Map: - { - var length = reader.ReadMapHeader(); - - IMessagePackFormatter objectFormatter = resolver.GetFormatter(); - var hash = new Dictionary(length, options.Security.GetEqualityComparer()); - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < length; i++) - { - var key = objectFormatter.Deserialize(ref reader, options); - - var value = objectFormatter.Deserialize(ref reader, options); - - hash.Add(key, value); - } - } - finally - { - reader.Depth--; - } - - return hash; - } - - case MessagePackType.Nil: - reader.ReadNil(); - return null; - default: - throw new MessagePackSerializationException("Invalid primitive bytes."); - } - } - } -} diff --git a/Assets/Plugins/MessagePack/Formatters/PrimitiveObjectFormatter.cs.meta b/Assets/Plugins/MessagePack/Formatters/PrimitiveObjectFormatter.cs.meta deleted file mode 100644 index 1b8766a23..000000000 --- a/Assets/Plugins/MessagePack/Formatters/PrimitiveObjectFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d46d293dc804af1669409cc12690a3ad -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Formatters/StandardClassLibraryFormatter.cs b/Assets/Plugins/MessagePack/Formatters/StandardClassLibraryFormatter.cs deleted file mode 100644 index 703d3bda5..000000000 --- a/Assets/Plugins/MessagePack/Formatters/StandardClassLibraryFormatter.cs +++ /dev/null @@ -1,599 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Text; -using MessagePack.Internal; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - // NET40 -> BigInteger, Complex, Tuple - - // byte[] is special. represents bin type. - public sealed class ByteArrayFormatter : IMessagePackFormatter - { - public static readonly ByteArrayFormatter Instance = new ByteArrayFormatter(); - - private ByteArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, byte[] value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public byte[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadBytes()?.ToArray(); - } - } - - public sealed class NullableStringFormatter : IMessagePackFormatter - { - public static readonly NullableStringFormatter Instance = new NullableStringFormatter(); - - private NullableStringFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, string value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public string Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadString(); - } - } - - public sealed class NullableStringArrayFormatter : IMessagePackFormatter - { - public static readonly NullableStringArrayFormatter Instance = new NullableStringArrayFormatter(); - - private NullableStringArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, String[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public String[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - var len = reader.ReadArrayHeader(); - var array = new String[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadString(); - } - - return array; - } - } - } - - public sealed class DecimalFormatter : IMessagePackFormatter - { - public static readonly DecimalFormatter Instance = new DecimalFormatter(); - - private DecimalFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, decimal value, MessagePackSerializerOptions options) - { - var dest = writer.GetSpan(MessagePackRange.MaxFixStringLength); - if (System.Buffers.Text.Utf8Formatter.TryFormat(value, dest.Slice(1), out var written)) - { - // write header - dest[0] = (byte)(MessagePackCode.MinFixStr | written); - writer.Advance(written + 1); - } - else - { - // reset writer's span previously acquired that does not use - writer.Advance(0); - writer.Write(value.ToString(CultureInfo.InvariantCulture)); - } - } - - public decimal Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (!(reader.ReadStringSequence() is ReadOnlySequence sequence)) - { - throw new MessagePackSerializationException(string.Format("Unexpected msgpack code {0} ({1}) encountered.", MessagePackCode.Nil, MessagePackCode.ToFormatName(MessagePackCode.Nil))); - } - - if (sequence.IsSingleSegment) - { - var span = sequence.First.Span; - if (System.Buffers.Text.Utf8Parser.TryParse(span, out decimal result, out var bytesConsumed)) - { - if (span.Length != bytesConsumed) - { - throw new MessagePackSerializationException("Unexpected length of string."); - } - - return result; - } - } - else - { - // sequence.Length is not free - var seqLen = (int)sequence.Length; - if (seqLen < 128) - { - Span span = stackalloc byte[seqLen]; - sequence.CopyTo(span); - if (System.Buffers.Text.Utf8Parser.TryParse(span, out decimal result, out var bytesConsumed)) - { - if (seqLen != bytesConsumed) - { - throw new MessagePackSerializationException("Unexpected length of string."); - } - - return result; - } - } - else - { - var rentArray = ArrayPool.Shared.Rent(seqLen); - try - { - sequence.CopyTo(rentArray); - if (System.Buffers.Text.Utf8Parser.TryParse(rentArray.AsSpan(0, seqLen), out decimal result, out var bytesConsumed)) - { - if (seqLen != bytesConsumed) - { - throw new MessagePackSerializationException("Unexpected length of string."); - } - - return result; - } - } - finally - { - ArrayPool.Shared.Return(rentArray); - } - } - } - - throw new MessagePackSerializationException("Can't parse to decimal, input string was not in a correct format."); - } - } - - public sealed class TimeSpanFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new TimeSpanFormatter(); - - private TimeSpanFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, TimeSpan value, MessagePackSerializerOptions options) - { - writer.Write(value.Ticks); - return; - } - - public TimeSpan Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return new TimeSpan(reader.ReadInt64()); - } - } - - public sealed class DateTimeOffsetFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new DateTimeOffsetFormatter(); - - private DateTimeOffsetFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, DateTimeOffset value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(2); - writer.Write(new DateTime(value.Ticks, DateTimeKind.Utc)); // current ticks as is - writer.Write((short)value.Offset.TotalMinutes); // offset is normalized in minutes - return; - } - - public DateTimeOffset Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - var count = reader.ReadArrayHeader(); - - if (count != 2) - { - throw new MessagePackSerializationException("Invalid DateTimeOffset format."); - } - - DateTime utc = reader.ReadDateTime(); - - var dtOffsetMinutes = reader.ReadInt16(); - - return new DateTimeOffset(utc.Ticks, TimeSpan.FromMinutes(dtOffsetMinutes)); - } - } - - public sealed class GuidFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new GuidFormatter(); - - private GuidFormatter() - { - } - - public unsafe void Serialize(ref MessagePackWriter writer, Guid value, MessagePackSerializerOptions options) - { - byte* pBytes = stackalloc byte[36]; - Span bytes = new Span(pBytes, 36); - new GuidBits(ref value).Write(bytes); - writer.WriteString(bytes); - } - - public Guid Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - ReadOnlySequence segment = reader.ReadStringSequence().Value; - if (segment.Length != 36) - { - throw new MessagePackSerializationException("Unexpected length of string."); - } - - GuidBits result; - if (segment.IsSingleSegment) - { - result = new GuidBits(segment.First.Span); - } - else - { - Span bytes = stackalloc byte[36]; - segment.CopyTo(bytes); - result = new GuidBits(bytes); - } - - return result.Value; - } - } - - public sealed class UriFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new UriFormatter(); - - private UriFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Uri value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.ToString()); - } - } - - public Uri Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - return new Uri(reader.ReadString(), UriKind.RelativeOrAbsolute); - } - } - } - - public sealed class VersionFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new VersionFormatter(); - - private VersionFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Version value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.ToString()); - } - } - - public Version Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - return new Version(reader.ReadString()); - } - } - } - - public sealed class KeyValuePairFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, KeyValuePair value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(2); - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Key, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Value, options); - return; - } - - public KeyValuePair Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - var count = reader.ReadArrayHeader(); - - if (count != 2) - { - throw new MessagePackSerializationException("Invalid KeyValuePair format."); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - TKey key = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - TValue value = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - return new KeyValuePair(key, value); - } - finally - { - reader.Depth--; - } - } - } - - public sealed class StringBuilderFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new StringBuilderFormatter(); - - private StringBuilderFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, StringBuilder value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.ToString()); - } - } - - public StringBuilder Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - return new StringBuilder(reader.ReadString()); - } - } - } - - public sealed class BitArrayFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new BitArrayFormatter(); - - private BitArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, BitArray value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - var len = value.Length; - writer.WriteArrayHeader(len); - for (int i = 0; i < len; i++) - { - writer.Write(value.Get(i)); - } - - return; - } - } - - public BitArray Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - var len = reader.ReadArrayHeader(); - - var array = new BitArray(len); - for (int i = 0; i < len; i++) - { - array[i] = reader.ReadBoolean(); - } - - return array; - } - } - } - - public sealed class BigIntegerFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new BigIntegerFormatter(); - - private BigIntegerFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, System.Numerics.BigInteger value, MessagePackSerializerOptions options) - { -#if NETCOREAPP2_1 - if (!writer.OldSpec) - { - // try to get bin8 buffer. - var span = writer.GetSpan(byte.MaxValue); - if (value.TryWriteBytes(span.Slice(2), out var written)) - { - span[0] = MessagePackCode.Bin8; - span[1] = (byte)written; - - writer.Advance(written + 2); - return; - } - else - { - // reset writer's span previously acquired that does not use - writer.Advance(0); - } - } -#endif - - writer.Write(value.ToByteArray()); - return; - } - - public System.Numerics.BigInteger Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - ReadOnlySequence bytes = reader.ReadBytes().Value; -#if NETCOREAPP2_1 - if (bytes.IsSingleSegment) - { - return new System.Numerics.BigInteger(bytes.First.Span); - } - else - { - byte[] bytesArray = ArrayPool.Shared.Rent((int)bytes.Length); - try - { - bytes.CopyTo(bytesArray); - return new System.Numerics.BigInteger(bytesArray.AsSpan(0, (int)bytes.Length)); - } - finally - { - ArrayPool.Shared.Return(bytesArray); - } - } -#else - return new System.Numerics.BigInteger(bytes.ToArray()); -#endif - } - } - - public sealed class ComplexFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new ComplexFormatter(); - - private ComplexFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, System.Numerics.Complex value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(2); - writer.Write(value.Real); - writer.Write(value.Imaginary); - return; - } - - public System.Numerics.Complex Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - var count = reader.ReadArrayHeader(); - - if (count != 2) - { - throw new MessagePackSerializationException("Invalid Complex format."); - } - - var real = reader.ReadDouble(); - - var imaginary = reader.ReadDouble(); - - return new System.Numerics.Complex(real, imaginary); - } - } - - public sealed class LazyFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, Lazy value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Value, options); - } - } - - public Lazy Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - options.Security.DepthStep(ref reader); - try - { - // deserialize immediately(no delay, because capture byte[] causes memory leak) - IFormatterResolver resolver = options.Resolver; - T v = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - return new Lazy(() => v); - } - finally - { - reader.Depth--; - } - } - } - } -} diff --git a/Assets/Plugins/MessagePack/Formatters/StandardClassLibraryFormatter.cs.meta b/Assets/Plugins/MessagePack/Formatters/StandardClassLibraryFormatter.cs.meta deleted file mode 100644 index 4a3c25ca2..000000000 --- a/Assets/Plugins/MessagePack/Formatters/StandardClassLibraryFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6dc8f5f9191421c21bd1ba87f5a70d27 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Formatters/TypelessFormatter.cs b/Assets/Plugins/MessagePack/Formatters/TypelessFormatter.cs deleted file mode 100644 index e7a476014..000000000 --- a/Assets/Plugins/MessagePack/Formatters/TypelessFormatter.cs +++ /dev/null @@ -1,309 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Text.RegularExpressions; -using MessagePack.Internal; - -namespace MessagePack.Formatters -{ - /// - /// For `object` field that holds derived from `object` value, ex: var arr = new object[] { 1, "a", new Model() };. - /// - public sealed class TypelessFormatter : IMessagePackFormatter - { - private delegate void SerializeMethod(object dynamicContractlessFormatter, ref MessagePackWriter writer, object value, MessagePackSerializerOptions options); - - private delegate object DeserializeMethod(object dynamicContractlessFormatter, ref MessagePackReader reader, MessagePackSerializerOptions options); - - /// - /// The singleton instance that can be used. - /// - public static readonly IMessagePackFormatter Instance = new TypelessFormatter(); - - private readonly ThreadsafeTypeKeyHashTable serializers = new ThreadsafeTypeKeyHashTable(); - private readonly ThreadsafeTypeKeyHashTable deserializers = new ThreadsafeTypeKeyHashTable(); - private readonly ThreadsafeTypeKeyHashTable fullTypeNameCache = new ThreadsafeTypeKeyHashTable(); - private readonly ThreadsafeTypeKeyHashTable shortenedTypeNameCache = new ThreadsafeTypeKeyHashTable(); - private readonly AsymmetricKeyHashTable, Type> typeCache = new AsymmetricKeyHashTable, Type>(new StringArraySegmentByteAscymmetricEqualityComparer()); - - private static readonly HashSet UseBuiltinTypes = new HashSet - { - typeof(Boolean), - ////typeof(Char), - typeof(SByte), - typeof(Byte), - typeof(Int16), - typeof(UInt16), - typeof(Int32), - typeof(UInt32), - typeof(Int64), - typeof(UInt64), - typeof(Single), - typeof(Double), - typeof(string), - typeof(byte[]), - - // array should save their types. - ////typeof(Boolean[]), - ////typeof(Char[]), - ////typeof(SByte[]), - ////typeof(Int16[]), - ////typeof(UInt16[]), - ////typeof(Int32[]), - ////typeof(UInt32[]), - ////typeof(Int64[]), - ////typeof(UInt64[]), - ////typeof(Single[]), - ////typeof(Double[]), - ////typeof(string[]), - - typeof(Boolean?), - ////typeof(Char?), - typeof(SByte?), - typeof(Byte?), - typeof(Int16?), - typeof(UInt16?), - typeof(Int32?), - typeof(UInt32?), - typeof(Int64?), - typeof(UInt64?), - typeof(Single?), - typeof(Double?), - }; - - //ForceSizePrimitiveObjectResolver.Instance, - //ContractlessStandardResolverAllowPrivate.Instance); - - // mscorlib or System.Private.CoreLib - private static readonly bool IsMscorlib = typeof(int).AssemblyQualifiedName.Contains("mscorlib"); - - public TypelessFormatter() - { - this.serializers.TryAdd(typeof(object), _ => (object p1, ref MessagePackWriter p2, object p3, MessagePackSerializerOptions p4) => { }); - this.deserializers.TryAdd(typeof(object), _ => (object p1, ref MessagePackReader p2, MessagePackSerializerOptions p3) => new object()); - } - - private string BuildTypeName(Type type, MessagePackSerializerOptions options) - { - if (options.OmitAssemblyVersion) - { - string full = type.AssemblyQualifiedName; - - var shortened = MessagePackSerializerOptions.AssemblyNameVersionSelectorRegex.Replace(full, string.Empty); - if (Type.GetType(shortened, false) == null) - { - // if type cannot be found with shortened name - use full name - shortened = full; - } - - return shortened; - } - else - { - return type.AssemblyQualifiedName; - } - } - - public void Serialize(ref MessagePackWriter writer, object value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - Type type = value.GetType(); - - byte[] typeName; - var typeNameCache = options.OmitAssemblyVersion ? this.shortenedTypeNameCache : this.fullTypeNameCache; - if (!typeNameCache.TryGetValue(type, out typeName)) - { - TypeInfo ti = type.GetTypeInfo(); - if (ti.IsAnonymous() || UseBuiltinTypes.Contains(type)) - { - typeName = null; - } - else - { - typeName = StringEncoding.UTF8.GetBytes(this.BuildTypeName(type, options)); - } - - typeNameCache.TryAdd(type, typeName); - } - - if (typeName == null) - { - DynamicObjectTypeFallbackFormatter.Instance.Serialize(ref writer, value, options); - return; - } - - var formatter = options.Resolver.GetFormatterDynamicWithVerify(type); - - // don't use GetOrAdd for avoid closure capture. - if (!this.serializers.TryGetValue(type, out SerializeMethod serializeMethod)) - { - // double check locking... - lock (this.serializers) - { - if (!this.serializers.TryGetValue(type, out serializeMethod)) - { - TypeInfo ti = type.GetTypeInfo(); - - Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(type); - ParameterExpression param0 = Expression.Parameter(typeof(object), "formatter"); - ParameterExpression param1 = Expression.Parameter(typeof(MessagePackWriter).MakeByRefType(), "writer"); - ParameterExpression param2 = Expression.Parameter(typeof(object), "value"); - ParameterExpression param3 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - - MethodInfo serializeMethodInfo = formatterType.GetRuntimeMethod("Serialize", new[] { typeof(MessagePackWriter).MakeByRefType(), type, typeof(MessagePackSerializerOptions) }); - - MethodCallExpression body = Expression.Call( - Expression.Convert(param0, formatterType), - serializeMethodInfo, - param1, - ti.IsValueType ? Expression.Unbox(param2, type) : Expression.Convert(param2, type), - param3); - - serializeMethod = Expression.Lambda(body, param0, param1, param2, param3).Compile(); - - this.serializers.TryAdd(type, serializeMethod); - } - } - } - - // mark will be written at the end, when size is known - using (var scratchRental = SequencePool.Shared.Rent()) - { - MessagePackWriter scratchWriter = writer.Clone(scratchRental.Value); - scratchWriter.WriteString(typeName); - serializeMethod(formatter, ref scratchWriter, value, options); - scratchWriter.Flush(); - - // mark as extension with code 100 - writer.WriteExtensionFormat(new ExtensionResult((sbyte)ThisLibraryExtensionTypeCodes.TypelessFormatter, scratchRental.Value)); - } - } - - public object Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - if (reader.NextMessagePackType == MessagePackType.Extension) - { - ExtensionHeader ext = reader.ReadExtensionFormatHeader(); - if (ext.TypeCode == ThisLibraryExtensionTypeCodes.TypelessFormatter) - { - // it has type name serialized - ReadOnlySequence typeName = reader.ReadStringSequence().Value; - ArraySegment typeNameArraySegment; - byte[] rented = null; - if (!typeName.IsSingleSegment || !MemoryMarshal.TryGetArray(typeName.First, out typeNameArraySegment)) - { - rented = ArrayPool.Shared.Rent((int)typeName.Length); - typeName.CopyTo(rented); - typeNameArraySegment = new ArraySegment(rented, 0, (int)typeName.Length); - } - - var result = this.DeserializeByTypeName(typeNameArraySegment, ref reader, options); - - if (rented != null) - { - ArrayPool.Shared.Return(rented); - } - - return result; - } - } - - // fallback - return DynamicObjectTypeFallbackFormatter.Instance.Deserialize(ref reader, options); - } - - /// - /// Does not support deserializing of anonymous types - /// Type should be covered by preceeding resolvers in complex/standard resolver. - /// - private object DeserializeByTypeName(ArraySegment typeName, ref MessagePackReader byteSequence, MessagePackSerializerOptions options) - { - // try get type with assembly name, throw if not found - Type type; - if (!this.typeCache.TryGetValue(typeName, out type)) - { - var buffer = new byte[typeName.Count]; - Buffer.BlockCopy(typeName.Array, typeName.Offset, buffer, 0, buffer.Length); - var str = StringEncoding.UTF8.GetString(buffer); - type = options.LoadType(str); - if (type == null) - { - if (IsMscorlib && str.Contains("System.Private.CoreLib")) - { - str = str.Replace("System.Private.CoreLib", "mscorlib"); - type = Type.GetType(str, true); // throw - } - else if (!IsMscorlib && str.Contains("mscorlib")) - { - str = str.Replace("mscorlib", "System.Private.CoreLib"); - type = Type.GetType(str, true); // throw - } - else - { - type = Type.GetType(str, true); // re-throw - } - } - - this.typeCache.TryAdd(buffer, type); - } - - options.ThrowIfDeserializingTypeIsDisallowed(type); - - var formatter = options.Resolver.GetFormatterDynamicWithVerify(type); - - if (!this.deserializers.TryGetValue(type, out DeserializeMethod deserializeMethod)) - { - lock (this.deserializers) - { - if (!this.deserializers.TryGetValue(type, out deserializeMethod)) - { - TypeInfo ti = type.GetTypeInfo(); - - Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(type); - ParameterExpression param0 = Expression.Parameter(typeof(object), "formatter"); - ParameterExpression param1 = Expression.Parameter(typeof(MessagePackReader).MakeByRefType(), "reader"); - ParameterExpression param2 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - - MethodInfo deserializeMethodInfo = formatterType.GetRuntimeMethod("Deserialize", new[] { typeof(MessagePackReader).MakeByRefType(), typeof(MessagePackSerializerOptions) }); - - MethodCallExpression deserialize = Expression.Call( - Expression.Convert(param0, formatterType), - deserializeMethodInfo, - param1, - param2); - - Expression body = deserialize; - if (ti.IsValueType) - { - body = Expression.Convert(deserialize, typeof(object)); - } - - deserializeMethod = Expression.Lambda(body, param0, param1, param2).Compile(); - - this.deserializers.TryAdd(type, deserializeMethod); - } - } - } - - return deserializeMethod(formatter, ref byteSequence, options); - } - } -} diff --git a/Assets/Plugins/MessagePack/Formatters/TypelessFormatter.cs.meta b/Assets/Plugins/MessagePack/Formatters/TypelessFormatter.cs.meta deleted file mode 100644 index ba44e44f6..000000000 --- a/Assets/Plugins/MessagePack/Formatters/TypelessFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: fe17a811684aa2fa786684f83f7fbbe7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Formatters/UnsafeBinaryFormatters.cs b/Assets/Plugins/MessagePack/Formatters/UnsafeBinaryFormatters.cs deleted file mode 100644 index 56f589961..000000000 --- a/Assets/Plugins/MessagePack/Formatters/UnsafeBinaryFormatters.cs +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - public sealed class NativeGuidFormatter : IMessagePackFormatter - { - /// - /// Unsafe binary Guid formatter. this is only allowed on LittleEndian environment. - /// - public static readonly IMessagePackFormatter Instance = new NativeGuidFormatter(); - - private NativeGuidFormatter() - { - } - - /* Guid's underlying _a,...,_k field is sequential and same layout as .NET Framework and Mono(Unity). - * But target machines must be same endian so restrict only for little endian. */ - - public unsafe void Serialize(ref MessagePackWriter writer, Guid value, MessagePackSerializerOptions options) - { - if (!BitConverter.IsLittleEndian) - { - throw new InvalidOperationException("NativeGuidFormatter only allows on little endian env."); - } - - var valueSpan = new ReadOnlySpan(&value, sizeof(Guid)); - writer.Write(valueSpan); - } - - public unsafe Guid Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (!BitConverter.IsLittleEndian) - { - throw new InvalidOperationException("NativeGuidFormatter only allows on little endian env."); - } - - ReadOnlySequence valueSequence = reader.ReadBytes().Value; - if (valueSequence.Length != sizeof(Guid)) - { - throw new MessagePackSerializationException("Invalid Guid Size."); - } - - Guid result; - var resultSpan = new Span(&result, sizeof(Guid)); - valueSequence.CopyTo(resultSpan); - return result; - } - } - - public sealed class NativeDecimalFormatter : IMessagePackFormatter - { - /// - /// Unsafe binary Decimal formatter. this is only allows on LittleEndian environment. - /// - public static readonly IMessagePackFormatter Instance = new NativeDecimalFormatter(); - - private NativeDecimalFormatter() - { - } - - /* decimal underlying "flags, hi, lo, mid" fields are sequential and same layuout with .NET Framework and Mono(Unity) - * But target machines must be same endian so restrict only for little endian. */ - - public unsafe void Serialize(ref MessagePackWriter writer, Decimal value, MessagePackSerializerOptions options) - { - if (!BitConverter.IsLittleEndian) - { - throw new InvalidOperationException("NativeDecimalFormatter only allows on little endian env."); - } - - var valueSpan = new ReadOnlySpan(&value, sizeof(Decimal)); - writer.Write(valueSpan); - } - - public unsafe Decimal Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (!BitConverter.IsLittleEndian) - { - throw new InvalidOperationException("NativeDecimalFormatter only allows on little endian env."); - } - - ReadOnlySequence valueSequence = reader.ReadBytes().Value; - if (valueSequence.Length != sizeof(decimal)) - { - throw new MessagePackSerializationException("Invalid decimal Size."); - } - - decimal result; - var resultSpan = new Span(&result, sizeof(decimal)); - valueSequence.CopyTo(resultSpan); - return result; - } - } -} diff --git a/Assets/Plugins/MessagePack/Formatters/UnsafeBinaryFormatters.cs.meta b/Assets/Plugins/MessagePack/Formatters/UnsafeBinaryFormatters.cs.meta deleted file mode 100644 index dafce71d0..000000000 --- a/Assets/Plugins/MessagePack/Formatters/UnsafeBinaryFormatters.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2c4fcfc3f496806c7915aba0cdb3f1ba -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/HashCode.cs b/Assets/Plugins/MessagePack/HashCode.cs deleted file mode 100644 index 8d48c08fd..000000000 --- a/Assets/Plugins/MessagePack/HashCode.cs +++ /dev/null @@ -1,481 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. -// - -/* - -The xxHash32 implementation is based on the code published by Yann Collet: -https://raw.githubusercontent.com/Cyan4973/xxHash/5c174cfa4e45a42f94082dc0d4539b39696afea1/xxhash.c - - xxHash - Fast Hash algorithm - Copyright (C) 2012-2016, Yann Collet - - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - xxHash homepage: http://www.xxhash.com - - xxHash source repository : https://github.com/Cyan4973/xxHash - -*/ - -#if !NETCOREAPP - -using System.Collections.Generic; -using System.ComponentModel; -using System.Numerics; -using System.Runtime.CompilerServices; -using System.Security.Cryptography; - -namespace System -{ - // xxHash32 is used for the hash code. - // https://github.com/Cyan4973/xxHash - - internal struct HashCode - { - private static readonly uint s_seed = GenerateGlobalSeed(); - - private const uint Prime1 = 2654435761U; - private const uint Prime2 = 2246822519U; - private const uint Prime3 = 3266489917U; - private const uint Prime4 = 668265263U; - private const uint Prime5 = 374761393U; - - private uint _v1, _v2, _v3, _v4; - private uint _queue1, _queue2, _queue3; - private uint _length; - - private static uint GenerateGlobalSeed() - { - var bytes = new byte[4]; - using (var rng = RandomNumberGenerator.Create()) - { - rng.GetBytes(bytes); - } - - return BitConverter.ToUInt32(bytes, 0); - } - - public static int Combine(T1 value1) - { - unchecked - { - // Provide a way of diffusing bits from something with a limited - // input hash space. For example, many enums only have a few - // possible hashes, only using the bottom few bits of the code. Some - // collections are built on the assumption that hashes are spread - // over a larger space, so diffusing the bits may help the - // collection work more efficiently. - - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - - uint hash = MixEmptyState(); - hash += 4; - - hash = QueueRound(hash, hc1); - - hash = MixFinal(hash); - return (int)hash; - } - } - - public static int Combine(T1 value1, T2 value2) - { - unchecked - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - - uint hash = MixEmptyState(); - hash += 8; - - hash = QueueRound(hash, hc1); - hash = QueueRound(hash, hc2); - - hash = MixFinal(hash); - return (int)hash; - } - } - - public static int Combine(T1 value1, T2 value2, T3 value3) - { - unchecked - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - - uint hash = MixEmptyState(); - hash += 12; - - hash = QueueRound(hash, hc1); - hash = QueueRound(hash, hc2); - hash = QueueRound(hash, hc3); - - hash = MixFinal(hash); - return (int)hash; - } - } - - public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4) - { - unchecked - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - uint hc4 = (uint)(value4?.GetHashCode() ?? 0); - - Initialize(out uint v1, out uint v2, out uint v3, out uint v4); - - v1 = Round(v1, hc1); - v2 = Round(v2, hc2); - v3 = Round(v3, hc3); - v4 = Round(v4, hc4); - - uint hash = MixState(v1, v2, v3, v4); - hash += 16; - - hash = MixFinal(hash); - return (int)hash; - } - } - - public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5) - { - unchecked - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - uint hc4 = (uint)(value4?.GetHashCode() ?? 0); - uint hc5 = (uint)(value5?.GetHashCode() ?? 0); - - Initialize(out uint v1, out uint v2, out uint v3, out uint v4); - - v1 = Round(v1, hc1); - v2 = Round(v2, hc2); - v3 = Round(v3, hc3); - v4 = Round(v4, hc4); - - uint hash = MixState(v1, v2, v3, v4); - hash += 20; - - hash = QueueRound(hash, hc5); - - hash = MixFinal(hash); - return (int)hash; - } - } - - public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6) - { - unchecked - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - uint hc4 = (uint)(value4?.GetHashCode() ?? 0); - uint hc5 = (uint)(value5?.GetHashCode() ?? 0); - uint hc6 = (uint)(value6?.GetHashCode() ?? 0); - - Initialize(out uint v1, out uint v2, out uint v3, out uint v4); - - v1 = Round(v1, hc1); - v2 = Round(v2, hc2); - v3 = Round(v3, hc3); - v4 = Round(v4, hc4); - - uint hash = MixState(v1, v2, v3, v4); - hash += 24; - - hash = QueueRound(hash, hc5); - hash = QueueRound(hash, hc6); - - hash = MixFinal(hash); - return (int)hash; - } - } - - public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7) - { - unchecked - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - uint hc4 = (uint)(value4?.GetHashCode() ?? 0); - uint hc5 = (uint)(value5?.GetHashCode() ?? 0); - uint hc6 = (uint)(value6?.GetHashCode() ?? 0); - uint hc7 = (uint)(value7?.GetHashCode() ?? 0); - - Initialize(out uint v1, out uint v2, out uint v3, out uint v4); - - v1 = Round(v1, hc1); - v2 = Round(v2, hc2); - v3 = Round(v3, hc3); - v4 = Round(v4, hc4); - - uint hash = MixState(v1, v2, v3, v4); - hash += 28; - - hash = QueueRound(hash, hc5); - hash = QueueRound(hash, hc6); - hash = QueueRound(hash, hc7); - - hash = MixFinal(hash); - return (int)hash; - } - } - - public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7, T8 value8) - { - unchecked - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - uint hc4 = (uint)(value4?.GetHashCode() ?? 0); - uint hc5 = (uint)(value5?.GetHashCode() ?? 0); - uint hc6 = (uint)(value6?.GetHashCode() ?? 0); - uint hc7 = (uint)(value7?.GetHashCode() ?? 0); - uint hc8 = (uint)(value8?.GetHashCode() ?? 0); - - Initialize(out uint v1, out uint v2, out uint v3, out uint v4); - - v1 = Round(v1, hc1); - v2 = Round(v2, hc2); - v3 = Round(v3, hc3); - v4 = Round(v4, hc4); - - v1 = Round(v1, hc5); - v2 = Round(v2, hc6); - v3 = Round(v3, hc7); - v4 = Round(v4, hc8); - - uint hash = MixState(v1, v2, v3, v4); - hash += 32; - - hash = MixFinal(hash); - return (int)hash; - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void Initialize(out uint v1, out uint v2, out uint v3, out uint v4) - { - unchecked - { - v1 = s_seed + Prime1 + Prime2; - v2 = s_seed + Prime2; - v3 = s_seed; - v4 = s_seed - Prime1; - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static uint Round(uint hash, uint input) - { - unchecked - { - return BitOperations.RotateLeft(hash + input * Prime2, 13) * Prime1; - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static uint QueueRound(uint hash, uint queuedValue) - { - unchecked - { - return BitOperations.RotateLeft(hash + queuedValue * Prime3, 17) * Prime4; - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static uint MixState(uint v1, uint v2, uint v3, uint v4) - { - unchecked - { - return BitOperations.RotateLeft(v1, 1) + BitOperations.RotateLeft(v2, 7) + BitOperations.RotateLeft(v3, 12) + BitOperations.RotateLeft(v4, 18); - } - } - - private static uint MixEmptyState() - { - unchecked - { - return s_seed + Prime5; - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static uint MixFinal(uint hash) - { - unchecked - { - hash ^= hash >> 15; - hash *= Prime2; - hash ^= hash >> 13; - hash *= Prime3; - hash ^= hash >> 16; - return hash; - } - } - - public void Add(T value) - { - Add(value?.GetHashCode() ?? 0); - } - - public void Add(T value, IEqualityComparer comparer) - { - Add(comparer != null ? comparer.GetHashCode(value) : (value?.GetHashCode() ?? 0)); - } - - private void Add(int value) - { - unchecked - { - // The original xxHash works as follows: - // 0. Initialize immediately. We can't do this in a struct (no - // default ctor). - // 1. Accumulate blocks of length 16 (4 uints) into 4 accumulators. - // 2. Accumulate remaining blocks of length 4 (1 uint) into the - // hash. - // 3. Accumulate remaining blocks of length 1 into the hash. - - // There is no need for #3 as this type only accepts ints. _queue1, - // _queue2 and _queue3 are basically a buffer so that when - // ToHashCode is called we can execute #2 correctly. - - // We need to initialize the xxHash32 state (_v1 to _v4) lazily (see - // #0) nd the last place that can be done if you look at the - // original code is just before the first block of 16 bytes is mixed - // in. The xxHash32 state is never used for streams containing fewer - // than 16 bytes. - - // To see what's really going on here, have a look at the Combine - // methods. - - uint val = (uint)value; - - // Storing the value of _length locally shaves of quite a few bytes - // in the resulting machine code. - uint previousLength = _length++; - uint position = previousLength % 4; - - // Switch can't be inlined. - - if (position == 0) - _queue1 = val; - else if (position == 1) - _queue2 = val; - else if (position == 2) - _queue3 = val; - else // position == 3 - { - if (previousLength == 3) - Initialize(out _v1, out _v2, out _v3, out _v4); - - _v1 = Round(_v1, _queue1); - _v2 = Round(_v2, _queue2); - _v3 = Round(_v3, _queue3); - _v4 = Round(_v4, val); - } - } - } - - public int ToHashCode() - { - unchecked - { - // Storing the value of _length locally shaves of quite a few bytes - // in the resulting machine code. - uint length = _length; - - // position refers to the *next* queue position in this method, so - // position == 1 means that _queue1 is populated; _queue2 would have - // been populated on the next call to Add. - uint position = length % 4; - - // If the length is less than 4, _v1 to _v4 don't contain anything - // yet. xxHash32 treats this differently. - - uint hash = length < 4 ? MixEmptyState() : MixState(_v1, _v2, _v3, _v4); - - // _length is incremented once per Add(Int32) and is therefore 4 - // times too small (xxHash length is in bytes, not ints). - - hash += length * 4; - - // Mix what remains in the queue - - // Switch can't be inlined right now, so use as few branches as - // possible by manually excluding impossible scenarios (position > 1 - // is always false if position is not > 0). - if (position > 0) - { - hash = QueueRound(hash, _queue1); - if (position > 1) - { - hash = QueueRound(hash, _queue2); - if (position > 2) - hash = QueueRound(hash, _queue3); - } - } - - hash = MixFinal(hash); - return (int)hash; - } - } - -#pragma warning disable 0809 - // Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - // Disallowing GetHashCode and Equals is by design - - // * We decided to not override GetHashCode() to produce the hash code - // as this would be weird, both naming-wise as well as from a - // behavioral standpoint (GetHashCode() should return the object's - // hash code, not the one being computed). - - // * Even though ToHashCode() can be called safely multiple times on - // this implementation, it is not part of the contract. If the - // implementation has to change in the future we don't want to worry - // about people who might have incorrectly used this type. - - [Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes. Use ToHashCode to retrieve the computed hash code.", error: true)] - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => throw new NotSupportedException(); - - [Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes.", error: true)] - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => throw new NotSupportedException(); -#pragma warning restore 0809 - } -} - -#endif diff --git a/Assets/Plugins/MessagePack/HashCode.cs.meta b/Assets/Plugins/MessagePack/HashCode.cs.meta deleted file mode 100644 index 1b90d9175..000000000 --- a/Assets/Plugins/MessagePack/HashCode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9909e9074ddc955f18803bd2037102f7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/IFormatterResolver.cs b/Assets/Plugins/MessagePack/IFormatterResolver.cs deleted file mode 100644 index 0638fc65f..000000000 --- a/Assets/Plugins/MessagePack/IFormatterResolver.cs +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.ExceptionServices; -using MessagePack.Formatters; - -namespace MessagePack -{ - /// - /// Allows querying for a formatter for serializing or deserializing a particular . - /// - public interface IFormatterResolver - { - /// - /// Gets an instance that can serialize or deserialize some type . - /// - /// The type of value to be serialized or deserialized. - /// A formatter, if this resolver supplies one for type ; otherwise null. - IMessagePackFormatter GetFormatter(); - } - - public static class FormatterResolverExtensions - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IMessagePackFormatter GetFormatterWithVerify(this IFormatterResolver resolver) - { - if (resolver is null) - { - throw new ArgumentNullException(nameof(resolver)); - } - - IMessagePackFormatter formatter; - try - { - formatter = resolver.GetFormatter(); - } - catch (TypeInitializationException ex) - { - // The fact that we're using static constructors to initialize this is an internal detail. - // Rethrow the inner exception if there is one. - // Do it carefully so as to not stomp on the original callstack. - Throw(ex); - return default; // not reachable - } - - if (formatter == null) - { - Throw(typeof(T), resolver); - } - - return formatter; - } - - private static void Throw(TypeInitializationException ex) - { - ExceptionDispatchInfo.Capture(ex.InnerException ?? ex).Throw(); - } - - private static void Throw(Type t, IFormatterResolver resolver) - { - throw new FormatterNotRegisteredException(t.FullName + " is not registered in resolver: " + resolver.GetType()); - } - - public static object GetFormatterDynamic(this IFormatterResolver resolver, Type type) - { - if (resolver is null) - { - throw new ArgumentNullException(nameof(resolver)); - } - - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } - - MethodInfo methodInfo = typeof(IFormatterResolver).GetRuntimeMethod(nameof(IFormatterResolver.GetFormatter), Type.EmptyTypes); - - var formatter = methodInfo.MakeGenericMethod(type).Invoke(resolver, null); - return formatter; - } - - internal static object GetFormatterDynamicWithVerify(this IFormatterResolver resolver, Type type) - { - object result = GetFormatterDynamic(resolver, type); - if (result == null) - { - Throw(type, resolver); - } - - return result; - } - } - - public class FormatterNotRegisteredException : MessagePackSerializationException - { - public FormatterNotRegisteredException(string message) - : base(message) - { - } - } -} diff --git a/Assets/Plugins/MessagePack/IFormatterResolver.cs.meta b/Assets/Plugins/MessagePack/IFormatterResolver.cs.meta deleted file mode 100644 index 5ff4bd7a4..000000000 --- a/Assets/Plugins/MessagePack/IFormatterResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 51a5ebbfbdf12b0cc80f0f57550f61a0 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Internal.meta b/Assets/Plugins/MessagePack/Internal.meta deleted file mode 100644 index 09938949d..000000000 --- a/Assets/Plugins/MessagePack/Internal.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 7303cf02620047543873c4663322e112 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Internal/AsymmetricKeyHashTable.cs b/Assets/Plugins/MessagePack/Internal/AsymmetricKeyHashTable.cs deleted file mode 100644 index 250512356..000000000 --- a/Assets/Plugins/MessagePack/Internal/AsymmetricKeyHashTable.cs +++ /dev/null @@ -1,302 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Internal -{ - /* Safe for multiple-read, single-write. - * Add and Get Key is asymmetric. */ - - internal interface IAsymmetricEqualityComparer - { - int GetHashCode(TKey1 key1); - - int GetHashCode(TKey2 key2); - - bool Equals(TKey1 x, TKey1 y); // when used rehash - - bool Equals(TKey1 x, TKey2 y); // when used get - } - - internal class StringArraySegmentByteAscymmetricEqualityComparer : IAsymmetricEqualityComparer> - { - private static readonly bool Is32Bit = IntPtr.Size == 4; - - public bool Equals(byte[] x, byte[] y) - { - if (x.Length != y.Length) - { - return false; - } - - for (int i = 0; i < x.Length; i++) - { - if (x[i] != y[i]) - { - return false; - } - } - - return true; - } - - public bool Equals(byte[] x, ArraySegment y) - { - return x.AsSpan().SequenceEqual(y); - } - - public int GetHashCode(byte[] key1) - { - return this.GetHashCode(new ArraySegment(key1, 0, key1.Length)); - } - - public int GetHashCode(ArraySegment key2) - { - unchecked - { - if (Is32Bit) - { - return (int)FarmHash.Hash32(key2); - } - else - { - return (int)FarmHash.Hash64(key2); - } - } - } - } - - internal sealed class AsymmetricKeyHashTable - { - private Entry[] buckets; - private int size; // only use in writer lock - - private readonly object writerLock = new object(); - private readonly float loadFactor; - private readonly IAsymmetricEqualityComparer comparer; - - public AsymmetricKeyHashTable(IAsymmetricEqualityComparer comparer) - : this(4, 0.72f, comparer) - { - } - - public AsymmetricKeyHashTable(int capacity, float loadFactor, IAsymmetricEqualityComparer comparer) - { - var tableSize = CalculateCapacity(capacity, loadFactor); - this.buckets = new Entry[tableSize]; - this.loadFactor = loadFactor; - this.comparer = comparer; - } - - public TValue AddOrGet(TKey1 key1, Func valueFactory) - { - TValue v; - this.TryAddInternal(key1, valueFactory, out v); - return v; - } - - public bool TryAdd(TKey1 key, TValue value) - { - return this.TryAdd(key, _ => value); // closure capture - } - - public bool TryAdd(TKey1 key, Func valueFactory) - { - return this.TryAddInternal(key, valueFactory, out TValue _); - } - - private bool TryAddInternal(TKey1 key, Func valueFactory, out TValue resultingValue) - { - lock (this.writerLock) - { - var nextCapacity = CalculateCapacity(this.size + 1, this.loadFactor); - - if (this.buckets.Length < nextCapacity) - { - // rehash - var nextBucket = new Entry[nextCapacity]; - for (int i = 0; i < this.buckets.Length; i++) - { - Entry e = this.buckets[i]; - while (e != null) - { - var newEntry = new Entry { Key = e.Key, Value = e.Value, Hash = e.Hash }; - this.AddToBuckets(nextBucket, key, newEntry, null, out resultingValue); - e = e.Next; - } - } - - // add entry(if failed to add, only do resize) - var successAdd = this.AddToBuckets(nextBucket, key, null, valueFactory, out resultingValue); - - // replace field(threadsafe for read) - VolatileWrite(ref this.buckets, nextBucket); - - if (successAdd) - { - this.size++; - } - - return successAdd; - } - else - { - // add entry(insert last is thread safe for read) - var successAdd = this.AddToBuckets(this.buckets, key, null, valueFactory, out resultingValue); - if (successAdd) - { - this.size++; - } - - return successAdd; - } - } - } - - private bool AddToBuckets(Entry[] buckets, TKey1 newKey, Entry newEntryOrNull, Func valueFactory, out TValue resultingValue) - { - var h = (newEntryOrNull != null) ? newEntryOrNull.Hash : this.comparer.GetHashCode(newKey); - if (buckets[h & (buckets.Length - 1)] == null) - { - if (newEntryOrNull != null) - { - resultingValue = newEntryOrNull.Value; - VolatileWrite(ref buckets[h & (buckets.Length - 1)], newEntryOrNull); - } - else - { - resultingValue = valueFactory(newKey); - VolatileWrite(ref buckets[h & (buckets.Length - 1)], new Entry { Key = newKey, Value = resultingValue, Hash = h }); - } - } - else - { - Entry searchLastEntry = buckets[h & (buckets.Length - 1)]; - while (true) - { - if (this.comparer.Equals(searchLastEntry.Key, newKey)) - { - resultingValue = searchLastEntry.Value; - return false; - } - - if (searchLastEntry.Next == null) - { - if (newEntryOrNull != null) - { - resultingValue = newEntryOrNull.Value; - VolatileWrite(ref searchLastEntry.Next, newEntryOrNull); - } - else - { - resultingValue = valueFactory(newKey); - VolatileWrite(ref searchLastEntry.Next, new Entry { Key = newKey, Value = resultingValue, Hash = h }); - } - - break; - } - - searchLastEntry = searchLastEntry.Next; - } - } - - return true; - } - - public bool TryGetValue(TKey2 key, out TValue value) - { - Entry[] table = this.buckets; - var hash = this.comparer.GetHashCode(key); - Entry entry = table[hash & table.Length - 1]; - - if (entry == null) - { - goto NOT_FOUND; - } - - if (this.comparer.Equals(entry.Key, key)) - { - value = entry.Value; - return true; - } - - Entry next = entry.Next; - while (next != null) - { - if (this.comparer.Equals(next.Key, key)) - { - value = next.Value; - return true; - } - - next = next.Next; - } - -NOT_FOUND: - value = default(TValue); - return false; - } - - private static int CalculateCapacity(int collectionSize, float loadFactor) - { - var initialCapacity = (int)(((float)collectionSize) / loadFactor); - var capacity = 1; - while (capacity < initialCapacity) - { - capacity <<= 1; - } - - if (capacity < 8) - { - return 8; - } - - return capacity; - } - - private static void VolatileWrite(ref Entry location, Entry value) - { - System.Threading.Volatile.Write(ref location, value); - } - - private static void VolatileWrite(ref Entry[] location, Entry[] value) - { - System.Threading.Volatile.Write(ref location, value); - } - - private class Entry - { -#pragma warning disable SA1401 // Fields should be private - internal TKey1 Key; - internal TValue Value; - internal int Hash; - internal Entry Next; -#pragma warning restore SA1401 // Fields should be private - - // from debugger only - public override string ToString() - { - return "Count:" + this.Count; - } - - internal int Count - { - get - { - var count = 1; - Entry n = this; - while (n.Next != null) - { - count++; - n = n.Next; - } - - return count; - } - } - } - } -} diff --git a/Assets/Plugins/MessagePack/Internal/AsymmetricKeyHashTable.cs.meta b/Assets/Plugins/MessagePack/Internal/AsymmetricKeyHashTable.cs.meta deleted file mode 100644 index 3a33ed1c0..000000000 --- a/Assets/Plugins/MessagePack/Internal/AsymmetricKeyHashTable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6862254987b9738ab9482616a323c2b5 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Internal/AutomataDictionary.cs b/Assets/Plugins/MessagePack/Internal/AutomataDictionary.cs deleted file mode 100644 index 811390b42..000000000 --- a/Assets/Plugins/MessagePack/Internal/AutomataDictionary.cs +++ /dev/null @@ -1,504 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Reflection.Emit; -using System.Runtime.InteropServices; -using System.Text; - -#pragma warning disable SA1509 // Opening braces should not be preceded by blank line - -namespace MessagePack.Internal -{ - // Key = long, Value = int for UTF8String Dictionary - - /// - /// This code is used by dynamically generated code as well as AOT generated code, - /// and thus must be public for the "C# generated and compiled into saved assembly" scenario. - /// - public class AutomataDictionary : IEnumerable> - { - private readonly AutomataNode root; - - public AutomataDictionary() - { - this.root = new AutomataNode(0); - } - - public void Add(string str, int value) - { - ReadOnlySpan bytes = Encoding.UTF8.GetBytes(str); - AutomataNode node = this.root; - - while (bytes.Length > 0) - { - var key = AutomataKeyGen.GetKey(ref bytes); - - if (bytes.Length == 0) - { - node = node.Add(key, value, str); - } - else - { - node = node.Add(key); - } - } - } - - public bool TryGetValue(in ReadOnlySequence bytes, out int value) => this.TryGetValue(bytes.ToArray(), out value); - - public bool TryGetValue(ReadOnlySpan bytes, out int value) - { - AutomataNode node = this.root; - - while (bytes.Length > 0 && node != null) - { - node = node.SearchNext(ref bytes); - } - - if (node == null) - { - value = -1; - return false; - } - else - { - value = node.Value; - return true; - } - } - - // for debugging - public override string ToString() - { - var sb = new StringBuilder(); - ToStringCore(this.root.YieldChildren(), sb, 0); - return sb.ToString(); - } - - private static void ToStringCore(IEnumerable nexts, StringBuilder sb, int depth) - { - foreach (AutomataNode item in nexts) - { - if (depth != 0) - { - sb.Append(' ', depth * 2); - } - - sb.Append("[" + item.Key + "]"); - if (item.Value != -1) - { - sb.Append("(" + item.OriginalKey + ")"); - sb.Append(" = "); - sb.Append(item.Value); - } - - sb.AppendLine(); - ToStringCore(item.YieldChildren(), sb, depth + 1); - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return this.GetEnumerator(); - } - - public IEnumerator> GetEnumerator() - { - return YieldCore(this.root.YieldChildren()).GetEnumerator(); - } - - private static IEnumerable> YieldCore(IEnumerable nexts) - { - foreach (AutomataNode item in nexts) - { - if (item.Value != -1) - { - yield return new KeyValuePair(item.OriginalKey, item.Value); - } - - foreach (KeyValuePair x in YieldCore(item.YieldChildren())) - { - yield return x; - } - } - } - - /* IL Emit */ - -#if !NET_STANDARD_2_0 - - public void EmitMatch(ILGenerator il, LocalBuilder bytesSpan, LocalBuilder key, Action> onFound, Action onNotFound) - { - this.root.EmitSearchNext(il, bytesSpan, key, onFound, onNotFound); - } - -#endif - - private class AutomataNode : IComparable - { - private static readonly AutomataNode[] EmptyNodes = new AutomataNode[0]; - private static readonly ulong[] EmptyKeys = new ulong[0]; - -#pragma warning disable SA1401 // Fields should be private - internal ulong Key; - internal int Value; - internal string OriginalKey; -#pragma warning restore SA1401 // Fields should be private - - private AutomataNode[] nexts; - private ulong[] nextKeys; - private int count; - - public bool HasChildren - { - get { return this.count != 0; } - } - - public AutomataNode(ulong key) - { - this.Key = key; - this.Value = -1; - this.nexts = EmptyNodes; - this.nextKeys = EmptyKeys; - this.count = 0; - this.OriginalKey = null; - } - - public AutomataNode Add(ulong key) - { - var index = Array.BinarySearch(this.nextKeys, 0, this.count, key); - if (index < 0) - { - if (this.nexts.Length == this.count) - { - Array.Resize(ref this.nexts, (this.count == 0) ? 4 : (this.count * 2)); - Array.Resize(ref this.nextKeys, (this.count == 0) ? 4 : (this.count * 2)); - } - - this.count++; - - var nextNode = new AutomataNode(key); - this.nexts[this.count - 1] = nextNode; - this.nextKeys[this.count - 1] = key; - Array.Sort(this.nexts, 0, this.count); - Array.Sort(this.nextKeys, 0, this.count); - return nextNode; - } - else - { - return this.nexts[index]; - } - } - - public AutomataNode Add(ulong key, int value, string originalKey) - { - AutomataNode v = this.Add(key); - v.Value = value; - v.OriginalKey = originalKey; - return v; - } - - public AutomataNode SearchNext(ref ReadOnlySpan value) - { - var key = AutomataKeyGen.GetKey(ref value); - if (this.count < 4) - { - // linear search - for (int i = 0; i < this.count; i++) - { - if (this.nextKeys[i] == key) - { - return this.nexts[i]; - } - } - } - else - { - // binary search - var index = BinarySearch(this.nextKeys, 0, this.count, key); - if (index >= 0) - { - return this.nexts[index]; - } - } - - return null; - } - - internal static int BinarySearch(ulong[] array, int index, int length, ulong value) - { - int lo = index; - int hi = index + length - 1; - while (lo <= hi) - { - int i = lo + ((hi - lo) >> 1); - - var arrayValue = array[i]; - int order; - if (arrayValue < value) - { - order = -1; - } - else if (arrayValue > value) - { - order = 1; - } - else - { - order = 0; - } - - if (order == 0) - { - return i; - } - - if (order < 0) - { - lo = i + 1; - } - else - { - hi = i - 1; - } - } - - return ~lo; - } - - public int CompareTo(AutomataNode other) - { - return this.Key.CompareTo(other.Key); - } - - public IEnumerable YieldChildren() - { - for (int i = 0; i < this.count; i++) - { - yield return this.nexts[i]; - } - } - -#if !NET_STANDARD_2_0 - - // SearchNext(ref ReadOnlySpan bytes) - public void EmitSearchNext(ILGenerator il, LocalBuilder bytesSpan, LocalBuilder key, Action> onFound, Action onNotFound) - { - // key = AutomataKeyGen.GetKey(ref bytesSpan); - il.EmitLdloca(bytesSpan); - il.EmitCall(AutomataKeyGen.GetKeyMethod); - il.EmitStloc(key); - - // match children. - EmitSearchNextCore(il, bytesSpan, key, onFound, onNotFound, this.nexts, this.count); - } - - private static void EmitSearchNextCore(ILGenerator il, LocalBuilder bytesSpan, LocalBuilder key, Action> onFound, Action onNotFound, AutomataNode[] nexts, int count) - { - if (count < 4) - { - // linear-search - AutomataNode[] valueExists = nexts.Take(count).Where(x => x.Value != -1).ToArray(); - AutomataNode[] childrenExists = nexts.Take(count).Where(x => x.HasChildren).ToArray(); - Label gotoSearchNext = il.DefineLabel(); - Label gotoNotFound = il.DefineLabel(); - - { - // bytesSpan.Length - il.EmitLdloca(bytesSpan); - il.EmitCall(typeof(ReadOnlySpan).GetRuntimeProperty(nameof(ReadOnlySpan.Length)).GetMethod); - if (childrenExists.Length != 0 && valueExists.Length == 0) - { - il.Emit(OpCodes.Brfalse, gotoNotFound); // if(bytesSpan.Length == 0) - } - else - { - il.Emit(OpCodes.Brtrue, gotoSearchNext); // if(bytesSpan.Length != 0) - } - } - - { - Label[] ifValueNexts = Enumerable.Range(0, Math.Max(valueExists.Length - 1, 0)).Select(_ => il.DefineLabel()).ToArray(); - for (int i = 0; i < valueExists.Length; i++) - { - Label notFoundLabel = il.DefineLabel(); - if (i != 0) - { - il.MarkLabel(ifValueNexts[i - 1]); - } - - il.EmitLdloc(key); - il.EmitULong(valueExists[i].Key); - il.Emit(OpCodes.Bne_Un, notFoundLabel); - - // found - onFound(new KeyValuePair(valueExists[i].OriginalKey, valueExists[i].Value)); - - // notfound - il.MarkLabel(notFoundLabel); - if (i != valueExists.Length - 1) - { - il.Emit(OpCodes.Br, ifValueNexts[i]); - } - else - { - onNotFound(); - } - } - } - - il.MarkLabel(gotoSearchNext); - Label[] ifRecNext = Enumerable.Range(0, Math.Max(childrenExists.Length - 1, 0)).Select(_ => il.DefineLabel()).ToArray(); - for (int i = 0; i < childrenExists.Length; i++) - { - Label notFoundLabel = il.DefineLabel(); - if (i != 0) - { - il.MarkLabel(ifRecNext[i - 1]); - } - - il.EmitLdloc(key); - il.EmitULong(childrenExists[i].Key); - il.Emit(OpCodes.Bne_Un, notFoundLabel); - - // found - childrenExists[i].EmitSearchNext(il, bytesSpan, key, onFound, onNotFound); - - // notfound - il.MarkLabel(notFoundLabel); - if (i != childrenExists.Length - 1) - { - il.Emit(OpCodes.Br, ifRecNext[i]); - } - else - { - onNotFound(); - } - } - - il.MarkLabel(gotoNotFound); - onNotFound(); - } - else - { - // binary-search - var midline = count / 2; - var mid = nexts[midline].Key; - AutomataNode[] l = nexts.Take(count).Take(midline).ToArray(); - AutomataNode[] r = nexts.Take(count).Skip(midline).ToArray(); - - Label gotoRight = il.DefineLabel(); - - // if(key < mid) - il.EmitLdloc(key); - il.EmitULong(mid); - il.Emit(OpCodes.Bge, gotoRight); - EmitSearchNextCore(il, bytesSpan, key, onFound, onNotFound, l, l.Length); - - // else - il.MarkLabel(gotoRight); - EmitSearchNextCore(il, bytesSpan, key, onFound, onNotFound, r, r.Length); - } - } - -#endif - } - } - - /// - /// This is used by dynamically generated code. It can be made internal after we enable our dynamic assemblies to access internals. - /// But that trick may require net46, so maybe we should leave this as public. - /// - public static class AutomataKeyGen - { - public static readonly MethodInfo GetKeyMethod = typeof(AutomataKeyGen).GetRuntimeMethod(nameof(GetKey), new[] { typeof(ReadOnlySpan).MakeByRefType() }); - - public static ulong GetKey(ref ReadOnlySpan span) - { - ulong key; - - unchecked - { - if (span.Length >= 8) - { - key = MemoryMarshal.Cast(span)[0]; - span = span.Slice(8); - } - else - { - switch (span.Length) - { - case 1: - { - key = span[0]; - span = span.Slice(1); - break; - } - - case 2: - { - key = MemoryMarshal.Cast(span)[0]; - span = span.Slice(2); - break; - } - - case 3: - { - var a = span[0]; - var b = MemoryMarshal.Cast(span.Slice(1))[0]; - key = a | (ulong)b << 8; - span = span.Slice(3); - break; - } - - case 4: - { - key = MemoryMarshal.Cast(span)[0]; - span = span.Slice(4); - break; - } - - case 5: - { - var a = span[0]; - var b = MemoryMarshal.Cast(span.Slice(1))[0]; - key = a | (ulong)b << 8; - span = span.Slice(5); - break; - } - - case 6: - { - ulong a = MemoryMarshal.Cast(span)[0]; - ulong b = MemoryMarshal.Cast(span.Slice(2))[0]; - key = a | (b << 16); - span = span.Slice(6); - break; - } - - case 7: - { - var a = span[0]; - var b = MemoryMarshal.Cast(span.Slice(1))[0]; - var c = MemoryMarshal.Cast(span.Slice(3))[0]; - key = a | (ulong)b << 8 | (ulong)c << 24; - span = span.Slice(7); - break; - } - - default: - throw new MessagePackSerializationException("Not Supported Length"); - } - } - - return key; - } - } - } -} diff --git a/Assets/Plugins/MessagePack/Internal/AutomataDictionary.cs.meta b/Assets/Plugins/MessagePack/Internal/AutomataDictionary.cs.meta deleted file mode 100644 index 10175d1c3..000000000 --- a/Assets/Plugins/MessagePack/Internal/AutomataDictionary.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: fc94f4e5525f7ba44b4e68f3cdcb1050 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Internal/ByteArrayStringHashTable.cs b/Assets/Plugins/MessagePack/Internal/ByteArrayStringHashTable.cs deleted file mode 100644 index dc1d4d409..000000000 --- a/Assets/Plugins/MessagePack/Internal/ByteArrayStringHashTable.cs +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections; -using System.Collections.Generic; -using System.Text; - -namespace MessagePack.Internal -{ - // like ArraySegment hashtable. - // Add is safe for construction phase only and requires capacity(does not do rehash) - // and specialized for internal use(nongenerics, TValue is int) - - // internal, but code generator requires this class - // or at least PerfBenchmarkDotNet - public class ByteArrayStringHashTable : IEnumerable> - { - private readonly Entry[][] buckets; // immutable array(faster than linkedlist) - private readonly ulong indexFor; - - public ByteArrayStringHashTable(int capacity) - : this(capacity, 0.42f) // default: 0.75f -> 0.42f - { - } - - public ByteArrayStringHashTable(int capacity, float loadFactor) - { - var tableSize = CalculateCapacity(capacity, loadFactor); - this.buckets = new Entry[tableSize][]; - this.indexFor = (ulong)this.buckets.Length - 1; - } - - public void Add(string key, int value) - { - if (!this.TryAddInternal(Encoding.UTF8.GetBytes(key), value)) - { - throw new ArgumentException("Key was already exists. Key:" + key); - } - } - - public void Add(byte[] key, int value) - { - if (!this.TryAddInternal(key, value)) - { - throw new ArgumentException("Key was already exists. Key:" + key); - } - } - - private bool TryAddInternal(byte[] key, int value) - { - var h = ByteArrayGetHashCode(key); - var entry = new Entry { Key = key, Value = value }; - - Entry[] array = this.buckets[h & this.indexFor]; - if (array == null) - { - this.buckets[h & this.indexFor] = new[] { entry }; - } - else - { - // check duplicate - for (int i = 0; i < array.Length; i++) - { - byte[] e = array[i].Key; - if (key.AsSpan().SequenceEqual(e)) - { - return false; - } - } - - var newArray = new Entry[array.Length + 1]; - Array.Copy(array, newArray, array.Length); - array = newArray; - array[array.Length - 1] = entry; - this.buckets[h & this.indexFor] = array; - } - - return true; - } - - public bool TryGetValue(in ReadOnlySequence key, out int value) => this.TryGetValue(CodeGenHelpers.GetSpanFromSequence(key), out value); - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryGetValue(ReadOnlySpan key, out int value) - { - Entry[][] table = this.buckets; - var hash = ByteArrayGetHashCode(key); - Entry[] entry = table[hash & this.indexFor]; - - if (entry == null) - { - value = default(int); - return false; - } - - ref Entry v = ref entry[0]; - if (key.SequenceEqual(v.Key)) - { - value = v.Value; - return true; - } - - return TryGetValueSlow(key, entry, out value); - } - - private bool TryGetValueSlow(ReadOnlySpan key, Entry[] entry, out int value) - { - for (int i = 1; i < entry.Length; i++) - { - ref Entry v = ref entry[i]; - if (key.SequenceEqual(v.Key)) - { - value = v.Value; - return true; - } - } - - value = default(int); - return false; - } - - private static readonly bool Is32Bit = IntPtr.Size == 4; - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - private static ulong ByteArrayGetHashCode(ReadOnlySpan x) - { - // FarmHash https://github.com/google/farmhash - if (Is32Bit) - { - return (ulong)FarmHash.Hash32(x); - } - else - { - return FarmHash.Hash64(x); - } - } - - private static int CalculateCapacity(int collectionSize, float loadFactor) - { - var initialCapacity = (int)(((float)collectionSize) / loadFactor); - var capacity = 1; - while (capacity < initialCapacity) - { - capacity <<= 1; - } - - if (capacity < 8) - { - return 8; - } - - return capacity; - } - - // only for Debug use - public IEnumerator> GetEnumerator() - { - Entry[][] b = this.buckets; - - foreach (Entry[] item in b) - { - if (item == null) - { - continue; - } - - foreach (Entry item2 in item) - { - yield return new KeyValuePair(Encoding.UTF8.GetString(item2.Key), item2.Value); - } - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return this.GetEnumerator(); - } - - private struct Entry - { - public byte[] Key; - public int Value; - - // for debugging - public override string ToString() - { - return "(" + Encoding.UTF8.GetString(this.Key) + ", " + this.Value + ")"; - } - } - } -} diff --git a/Assets/Plugins/MessagePack/Internal/ByteArrayStringHashTable.cs.meta b/Assets/Plugins/MessagePack/Internal/ByteArrayStringHashTable.cs.meta deleted file mode 100644 index 67659d82d..000000000 --- a/Assets/Plugins/MessagePack/Internal/ByteArrayStringHashTable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 28c84212e5b4fc4d7b4b66cdb741984d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Internal/CodeGenHelpers.cs b/Assets/Plugins/MessagePack/Internal/CodeGenHelpers.cs deleted file mode 100644 index 67880968b..000000000 --- a/Assets/Plugins/MessagePack/Internal/CodeGenHelpers.cs +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.ComponentModel; - -namespace MessagePack.Internal -{ - /// - /// Helpers for generated code. - /// - /// - /// This code is used by dynamically generated code as well as AOT generated code, - /// and thus must be public for the "C# generated and compiled into saved assembly" scenario. - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public static class CodeGenHelpers - { - public static byte[] GetEncodedStringBytes(string value) - { - var byteCount = StringEncoding.UTF8.GetByteCount(value); - if (byteCount <= MessagePackRange.MaxFixStringLength) - { - var bytes = new byte[byteCount + 1]; - bytes[0] = (byte)(MessagePackCode.MinFixStr | byteCount); - StringEncoding.UTF8.GetBytes(value, 0, value.Length, bytes, 1); - return bytes; - } - else if (byteCount <= byte.MaxValue) - { - var bytes = new byte[byteCount + 2]; - bytes[0] = MessagePackCode.Str8; - bytes[1] = unchecked((byte)byteCount); - StringEncoding.UTF8.GetBytes(value, 0, value.Length, bytes, 2); - return bytes; - } - else if (byteCount <= ushort.MaxValue) - { - var bytes = new byte[byteCount + 3]; - bytes[0] = MessagePackCode.Str16; - bytes[1] = unchecked((byte)(byteCount >> 8)); - bytes[2] = unchecked((byte)byteCount); - StringEncoding.UTF8.GetBytes(value, 0, value.Length, bytes, 3); - return bytes; - } - else - { - var bytes = new byte[byteCount + 5]; - bytes[0] = MessagePackCode.Str32; - bytes[1] = unchecked((byte)(byteCount >> 24)); - bytes[2] = unchecked((byte)(byteCount >> 16)); - bytes[3] = unchecked((byte)(byteCount >> 8)); - bytes[4] = unchecked((byte)byteCount); - StringEncoding.UTF8.GetBytes(value, 0, value.Length, bytes, 5); - return bytes; - } - } - - public static ReadOnlySpan GetSpanFromSequence(in ReadOnlySequence sequence) - { - if (sequence.IsSingleSegment) - { - return sequence.First.Span; - } - - return sequence.ToArray(); - } - - public static ReadOnlySpan ReadStringSpan(ref MessagePackReader reader) - { - if (!reader.TryReadStringSpan(out ReadOnlySpan result)) - { - return GetSpanFromSequence(reader.ReadStringSequence()); - } - - return result; - } - - public static byte[] GetArrayFromNullableSequence(in ReadOnlySequence? sequence) => sequence?.ToArray(); - - private static ReadOnlySpan GetSpanFromSequence(in ReadOnlySequence? sequence) - { - return sequence.HasValue ? GetSpanFromSequence(sequence.Value) : default; - } - } -} diff --git a/Assets/Plugins/MessagePack/Internal/CodeGenHelpers.cs.meta b/Assets/Plugins/MessagePack/Internal/CodeGenHelpers.cs.meta deleted file mode 100644 index 692460918..000000000 --- a/Assets/Plugins/MessagePack/Internal/CodeGenHelpers.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4f2dcc1d826e7ff7da02bd691c4dd6a0 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Internal/DateTimeConstants.cs b/Assets/Plugins/MessagePack/Internal/DateTimeConstants.cs deleted file mode 100644 index 84fbfe9a2..000000000 --- a/Assets/Plugins/MessagePack/Internal/DateTimeConstants.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; - -namespace MessagePack.Internal -{ - internal static class DateTimeConstants - { - internal const long BclSecondsAtUnixEpoch = 62135596800; - internal const int NanosecondsPerTick = 100; - internal static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - } -} diff --git a/Assets/Plugins/MessagePack/Internal/DateTimeConstants.cs.meta b/Assets/Plugins/MessagePack/Internal/DateTimeConstants.cs.meta deleted file mode 100644 index 58c92ac0c..000000000 --- a/Assets/Plugins/MessagePack/Internal/DateTimeConstants.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a0cf18db43b878d71a216123e3309b65 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Internal/DynamicAssembly.cs b/Assets/Plugins/MessagePack/Internal/DynamicAssembly.cs deleted file mode 100644 index 7b8daa38d..000000000 --- a/Assets/Plugins/MessagePack/Internal/DynamicAssembly.cs +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if !(UNITY_2018_3_OR_NEWER && NET_STANDARD_2_0) - -using System; -using System.Reflection; -using System.Reflection.Emit; - -namespace MessagePack.Internal -{ - internal class DynamicAssembly - { -#if NETFRAMEWORK // We don't ship a net472 target, but we might add one for debugging purposes - private readonly string moduleName; -#endif - private readonly AssemblyBuilder assemblyBuilder; - private readonly ModuleBuilder moduleBuilder; - - // don't expose ModuleBuilder - //// public ModuleBuilder ModuleBuilder { get { return moduleBuilder; } } - - private readonly object gate = new object(); - - public DynamicAssembly(string moduleName) - { -#if NETFRAMEWORK // We don't ship a net472 target, but we might add one for debugging purposes - AssemblyBuilderAccess builderAccess = AssemblyBuilderAccess.RunAndSave; - this.moduleName = moduleName; -#else - AssemblyBuilderAccess builderAccess = AssemblyBuilderAccess.Run; -#endif - this.assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(moduleName), builderAccess); - this.moduleBuilder = this.assemblyBuilder.DefineDynamicModule(moduleName + ".dll"); - } - - /* requires lock on mono environment. see: https://github.com/neuecc/MessagePack-CSharp/issues/161 */ - - public TypeBuilder DefineType(string name, TypeAttributes attr) - { - lock (this.gate) - { - return this.moduleBuilder.DefineType(name, attr); - } - } - - public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent) - { - lock (this.gate) - { - return this.moduleBuilder.DefineType(name, attr, parent); - } - } - - public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent, Type[] interfaces) - { - lock (this.gate) - { - return this.moduleBuilder.DefineType(name, attr, parent, interfaces); - } - } - -#if NETFRAMEWORK - - public AssemblyBuilder Save() - { - this.assemblyBuilder.Save(this.moduleName + ".dll"); - return this.assemblyBuilder; - } - -#endif - } -} - -#endif diff --git a/Assets/Plugins/MessagePack/Internal/DynamicAssembly.cs.meta b/Assets/Plugins/MessagePack/Internal/DynamicAssembly.cs.meta deleted file mode 100644 index 933588e12..000000000 --- a/Assets/Plugins/MessagePack/Internal/DynamicAssembly.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f44ca64eddd25f5a896a2f72b21fcc9b -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Internal/ExpressionUtility.cs b/Assets/Plugins/MessagePack/Internal/ExpressionUtility.cs deleted file mode 100644 index 3dbf46e99..000000000 --- a/Assets/Plugins/MessagePack/Internal/ExpressionUtility.cs +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Linq.Expressions; -using System.Reflection; - -namespace MessagePack.Internal -{ - internal static class ExpressionUtility - { - private static MethodInfo GetMethodInfoCore(LambdaExpression expression) - { - if (expression == null) - { - throw new ArgumentNullException("expression"); - } - - return (expression.Body as MethodCallExpression).Method; - } - - /// - /// Get MethodInfo from Expression for Static(with result) method. - /// - public static MethodInfo GetMethodInfo(Expression> expression) - { - return GetMethodInfoCore(expression); - } - - /// - /// Get MethodInfo from Expression for Static(void) method. - /// - public static MethodInfo GetMethodInfo(Expression expression) - { - return GetMethodInfoCore(expression); - } - - /// - /// Get MethodInfo from Expression for Instance(with result) method. - /// - public static MethodInfo GetMethodInfo(Expression> expression) - { - return GetMethodInfoCore(expression); - } - - /// - /// Get MethodInfo from Expression for Instance(void) method. - /// - public static MethodInfo GetMethodInfo(Expression> expression) - { - return GetMethodInfoCore(expression); - } - - // WithArgument(for ref, out) helper - - /// - /// Get MethodInfo from Expression for Instance(with result) method. - /// - public static MethodInfo GetMethodInfo(Expression> expression) - { - return GetMethodInfoCore(expression); - } - - private static MemberInfo GetMemberInfoCore(Expression source) - { - if (source == null) - { - throw new ArgumentNullException("source"); - } - - var memberExpression = source.Body as MemberExpression; - return memberExpression.Member; - } - - public static PropertyInfo GetPropertyInfo(Expression> expression) - { - return GetMemberInfoCore(expression) as PropertyInfo; - } - - public static FieldInfo GetFieldInfo(Expression> expression) - { - return GetMemberInfoCore(expression) as FieldInfo; - } - } -} diff --git a/Assets/Plugins/MessagePack/Internal/ExpressionUtility.cs.meta b/Assets/Plugins/MessagePack/Internal/ExpressionUtility.cs.meta deleted file mode 100644 index 790bc2483..000000000 --- a/Assets/Plugins/MessagePack/Internal/ExpressionUtility.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1e2163b0f9d41a70599e1d5bd231a4b6 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Internal/FarmHash.cs b/Assets/Plugins/MessagePack/Internal/FarmHash.cs deleted file mode 100644 index 36d4b8e4e..000000000 --- a/Assets/Plugins/MessagePack/Internal/FarmHash.cs +++ /dev/null @@ -1,601 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Runtime.CompilerServices; - -#pragma warning disable SA1300 // Element should begin with uppercase letter -#pragma warning disable SA1303 // Const field names should begin with uppercase letter -#pragma warning disable SA1307 // (public) field names should begin with uppercase letter - -namespace MessagePack.Internal -{ - internal static class FarmHash - { - #region Hash32 - - // entry point of 32bit - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe uint Hash32(ReadOnlySpan bytes) - { - if (bytes.Length <= 4) - { - return Hash32Len0to4(bytes); - } - - fixed (byte* p = bytes) - { - return Hash32(p, (uint)bytes.Length); - } - } - - // port of farmhash.cc, 32bit only - - // Magic numbers for 32-bit hashing. Copied from Murmur3. - private const uint c1 = 0xcc9e2d51; - private const uint c2 = 0x1b873593; - - private static unsafe uint Fetch32(byte* p) - { - return *(uint*)p; - } - - private static uint Rotate32(uint val, int shift) - { - return shift == 0 ? val : ((val >> shift) | (val << (32 - shift))); - } - - // A 32-bit to 32-bit integer hash copied from Murmur3. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static uint fmix(uint h) - { - unchecked - { - h ^= h >> 16; - h *= 0x85ebca6b; - h ^= h >> 13; - h *= 0xc2b2ae35; - h ^= h >> 16; - return h; - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static uint Mur(uint a, uint h) - { - unchecked - { - // Helper from Murmur3 for combining two 32-bit values. - a *= c1; - a = Rotate32(a, 17); - a *= c2; - h ^= a; - h = Rotate32(h, 19); - return (h * 5) + 0xe6546b64; - } - } - - // 0-4 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe uint Hash32Len0to4(ReadOnlySpan s) - { - unchecked - { - uint b = 0; - uint c = 9; - for (int i = 0; i < s.Length; i++) - { - b = (b * c1) + s[i]; - c ^= b; - } - - return fmix(Mur(b, Mur((uint)s.Length, c))); - } - } - - // 5-12 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe uint Hash32Len5to12(byte* s, uint len) - { - unchecked - { - uint a = len, b = len * 5, c = 9, d = b; - a += Fetch32(s); - b += Fetch32(s + len - 4); - c += Fetch32(s + ((len >> 1) & 4)); - return fmix(Mur(c, Mur(b, Mur(a, d)))); - } - } - - // 13-24 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe uint Hash32Len13to24(byte* s, uint len) - { - unchecked - { - uint a = Fetch32(s - 4 + (len >> 1)); - uint b = Fetch32(s + 4); - uint c = Fetch32(s + len - 8); - uint d = Fetch32(s + (len >> 1)); - uint e = Fetch32(s); - uint f = Fetch32(s + len - 4); - uint h = (d * c1) + len; - a = Rotate32(a, 12) + f; - h = Mur(c, h) + a; - a = Rotate32(a, 3) + c; - h = Mur(e, h) + a; - a = Rotate32(a + f, 12) + d; - h = Mur(b, h) + a; - return fmix(h); - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe uint Hash32(byte* s, uint len) - { - if (len <= 24) - { - return len <= 12 ? Hash32Len5to12(s, len) : Hash32Len13to24(s, len); - } - - unchecked - { - // len > 24 - uint h = len, g = c1 * len, f = g; - uint a0 = Rotate32(Fetch32(s + len - 4) * c1, 17) * c2; - uint a1 = Rotate32(Fetch32(s + len - 8) * c1, 17) * c2; - uint a2 = Rotate32(Fetch32(s + len - 16) * c1, 17) * c2; - uint a3 = Rotate32(Fetch32(s + len - 12) * c1, 17) * c2; - uint a4 = Rotate32(Fetch32(s + len - 20) * c1, 17) * c2; - h ^= a0; - h = Rotate32(h, 19); - h = (h * 5) + 0xe6546b64; - h ^= a2; - h = Rotate32(h, 19); - h = (h * 5) + 0xe6546b64; - g ^= a1; - g = Rotate32(g, 19); - g = (g * 5) + 0xe6546b64; - g ^= a3; - g = Rotate32(g, 19); - g = (g * 5) + 0xe6546b64; - f += a4; - f = Rotate32(f, 19) + 113; - uint iters = (len - 1) / 20; - do - { - uint a = Fetch32(s); - uint b = Fetch32(s + 4); - uint c = Fetch32(s + 8); - uint d = Fetch32(s + 12); - uint e = Fetch32(s + 16); - h += a; - g += b; - f += c; - h = Mur(d, h) + e; - g = Mur(c, g) + a; - f = Mur(b + (e * c1), f) + d; - f += g; - g += f; - s += 20; - } - while (--iters != 0); - g = Rotate32(g, 11) * c1; - g = Rotate32(g, 17) * c1; - f = Rotate32(f, 11) * c1; - f = Rotate32(f, 17) * c1; - h = Rotate32(h + g, 19); - h = (h * 5) + 0xe6546b64; - h = Rotate32(h, 17) * c1; - h = Rotate32(h + f, 19); - h = (h * 5) + 0xe6546b64; - h = Rotate32(h, 17) * c1; - return h; - } - } - - #endregion - - #region hash64 - - // entry point - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe ulong Hash64(ReadOnlySpan bytes) - { - fixed (byte* p = bytes) - { - return Hash64(p, (uint)bytes.Length); - } - } - - /* port from farmhash.cc */ - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void swap(ref ulong x, ref ulong z) - { - var temp = z; - z = x; - x = temp; - } - - // Some primes between 2^63 and 2^64 for various uses. - private const ulong k0 = 0xc3a5c85c97cb3127UL; - private const ulong k1 = 0xb492b66fbe98f273UL; - private const ulong k2 = 0x9ae16a3b2f90404fUL; - - private static unsafe ulong Fetch64(byte* p) - { - return *(ulong*)p; - } - - private static ulong Rotate64(ulong val, int shift) - { - return shift == 0 ? val : (val >> shift) | (val << (64 - shift)); - } - - // farmhashna.cc - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static ulong ShiftMix(ulong val) - { - return val ^ (val >> 47); - } - - // farmhashna.cc - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static ulong HashLen16(ulong u, ulong v, ulong mul) - { - unchecked - { - // Murmur-inspired hashing. - ulong a = (u ^ v) * mul; - a ^= a >> 47; - ulong b = (v ^ a) * mul; - b ^= b >> 47; - b *= mul; - return b; - } - } - - // farmhashxo.cc - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe ulong Hash64(byte* s, uint len) - { - if (len <= 16) - { - // farmhashna:: - return HashLen0to16(s, len); - } - - if (len <= 32) - { - // farmhashna:: - return HashLen17to32(s, len); - } - - if (len <= 64) - { - return HashLen33to64(s, len); - } - - if (len <= 96) - { - return HashLen65to96(s, len); - } - - if (len <= 256) - { - // farmhashna:: - return Hash64NA(s, len); - } - - // farmhashuo:: - return Hash64UO(s, len); - } - - // 0-16 farmhashna.cc - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe ulong HashLen0to16(byte* s, uint len) - { - unchecked - { - if (len >= 8) - { - ulong mul = k2 + (len * 2); - ulong a = Fetch64(s) + k2; - ulong b = Fetch64(s + len - 8); - ulong c = (Rotate64(b, 37) * mul) + a; - ulong d = (Rotate64(a, 25) + b) * mul; - return HashLen16(c, d, mul); - } - - if (len >= 4) - { - ulong mul = k2 + (len * 2); - ulong a = Fetch32(s); - return HashLen16(len + (a << 3), Fetch32(s + len - 4), mul); - } - - if (len > 0) - { - ushort a = s[0]; - ushort b = s[len >> 1]; - ushort c = s[len - 1]; - uint y = a + ((uint)b << 8); - uint z = len + ((uint)c << 2); - return ShiftMix(y * k2 ^ z * k0) * k2; - } - - return k2; - } - } - - // 17-32 farmhashna.cc - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe ulong HashLen17to32(byte* s, uint len) - { - unchecked - { - ulong mul = k2 + (len * 2); - ulong a = Fetch64(s) * k1; - ulong b = Fetch64(s + 8); - ulong c = Fetch64(s + len - 8) * mul; - ulong d = Fetch64(s + len - 16) * k2; - return HashLen16( - Rotate64(a + b, 43) + Rotate64(c, 30) + d, - a + Rotate64(b + k2, 18) + c, - mul); - } - } - - // farmhashxo.cc - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe ulong H32(byte* s, uint len, ulong mul, ulong seed0 = 0, ulong seed1 = 0) - { - unchecked - { - ulong a = Fetch64(s) * k1; - ulong b = Fetch64(s + 8); - ulong c = Fetch64(s + len - 8) * mul; - ulong d = Fetch64(s + len - 16) * k2; - ulong u = Rotate64(a + b, 43) + Rotate64(c, 30) + d + seed0; - ulong v = a + Rotate64(b + k2, 18) + c + seed1; - a = ShiftMix((u ^ v) * mul); - b = ShiftMix((v ^ a) * mul); - return b; - } - } - - // 33-64 farmhashxo.cc - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe ulong HashLen33to64(byte* s, uint len) - { - const ulong mul0 = k2 - 30; - - unchecked - { - ulong mul1 = k2 - 30 + (2 * len); - ulong h0 = H32(s, 32, mul0); - ulong h1 = H32(s + len - 32, 32, mul1); - return ((h1 * mul1) + h0) * mul1; - } - } - - // 65-96 farmhashxo.cc - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe ulong HashLen65to96(byte* s, uint len) - { - const ulong mul0 = k2 - 114; - - unchecked - { - ulong mul1 = k2 - 114 + (2 * len); - ulong h0 = H32(s, 32, mul0); - ulong h1 = H32(s + 32, 32, mul1); - ulong h2 = H32(s + len - 32, 32, mul1, h0, h1); - return ((h2 * 9) + (h0 >> 17) + (h1 >> 21)) * mul1; - } - } - - // farmhashna.cc - // Return a 16-byte hash for 48 bytes. Quick and dirty. - // Callers do best to use "random-looking" values for a and b. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe void WeakHashLen32WithSeeds(ulong w, ulong x, ulong y, ulong z, ulong a, ulong b, out ulong first, out ulong second) - { - unchecked - { - a += w; - b = Rotate64(b + a + z, 21); - ulong c = a; - a += x; - a += y; - b += Rotate64(a, 44); - first = a + z; - second = b + c; - } - } - - // farmhashna.cc - // Return a 16-byte hash for s[0] ... s[31], a, and b. Quick and dirty. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe void WeakHashLen32WithSeeds(byte* s, ulong a, ulong b, out ulong first, out ulong second) - { - WeakHashLen32WithSeeds( - Fetch64(s), - Fetch64(s + 8), - Fetch64(s + 16), - Fetch64(s + 24), - a, - b, - out first, - out second); - } - - // na(97-256) farmhashna.cc - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe ulong Hash64NA(byte* s, uint len) - { - const ulong seed = 81; - - unchecked - { - // For strings over 64 bytes we loop. Internal state consists of - // 56 bytes: v, w, x, y, and z. - ulong x = seed; - ulong y = (seed * k1) + 113; - ulong z = ShiftMix((y * k2) + 113) * k2; - ulong v_first = 0; - ulong v_second = 0; - ulong w_first = 0; - ulong w_second = 0; - x = (x * k2) + Fetch64(s); - - // Set end so that after the loop we have 1 to 64 bytes left to process. - byte* end = s + ((len - 1) / 64 * 64); - byte* last64 = end + ((len - 1) & 63) - 63; - - do - { - x = Rotate64(x + y + v_first + Fetch64(s + 8), 37) * k1; - y = Rotate64(y + v_second + Fetch64(s + 48), 42) * k1; - x ^= w_second; - y += v_first + Fetch64(s + 40); - z = Rotate64(z + w_first, 33) * k1; - WeakHashLen32WithSeeds(s, v_second * k1, x + w_first, out v_first, out v_second); - WeakHashLen32WithSeeds(s + 32, z + w_second, y + Fetch64(s + 16), out w_first, out w_second); - swap(ref z, ref x); - s += 64; - } - while (s != end); - ulong mul = k1 + ((z & 0xff) << 1); - - // Make s point to the last 64 bytes of input. - s = last64; - w_first += (len - 1) & 63; - v_first += w_first; - w_first += v_first; - x = Rotate64(x + y + v_first + Fetch64(s + 8), 37) * mul; - y = Rotate64(y + v_second + Fetch64(s + 48), 42) * mul; - x ^= w_second * 9; - y += (v_first * 9) + Fetch64(s + 40); - z = Rotate64(z + w_first, 33) * mul; - WeakHashLen32WithSeeds(s, v_second * mul, x + w_first, out v_first, out v_second); - WeakHashLen32WithSeeds(s + 32, z + w_second, y + Fetch64(s + 16), out w_first, out w_second); - swap(ref z, ref x); - return HashLen16(HashLen16(v_first, w_first, mul) + (ShiftMix(y) * k0) + z, HashLen16(v_second, w_second, mul) + x, mul); - } - } - - // farmhashuo.cc - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static ulong H(ulong x, ulong y, ulong mul, int r) - { - unchecked - { - ulong a = (x ^ y) * mul; - a ^= a >> 47; - ulong b = (y ^ a) * mul; - return Rotate64(b, r) * mul; - } - } - - // uo(257-) farmhashuo.cc, Hash64WithSeeds - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe ulong Hash64UO(byte* s, uint len) - { - const ulong seed0 = 81; - const ulong seed1 = 0; - - unchecked - { - // For strings over 64 bytes we loop. Internal state consists of - // 64 bytes: u, v, w, x, y, and z. - ulong x = seed0; - ulong y = (seed1 * k2) + 113; - ulong z = ShiftMix(y * k2) * k2; - ulong v_first = seed0; - ulong v_second = seed1; - ulong w_first = 0; - ulong w_second = 0; - ulong u = x - z; - x *= k2; - ulong mul = k2 + (u & 0x82); - - // Set end so that after the loop we have 1 to 64 bytes left to process. - byte* end = s + ((len - 1) / 64 * 64); - byte* last64 = end + ((len - 1) & 63) - 63; - - do - { - ulong a0 = Fetch64(s); - ulong a1 = Fetch64(s + 8); - ulong a2 = Fetch64(s + 16); - ulong a3 = Fetch64(s + 24); - ulong a4 = Fetch64(s + 32); - ulong a5 = Fetch64(s + 40); - ulong a6 = Fetch64(s + 48); - ulong a7 = Fetch64(s + 56); - x += a0 + a1; - y += a2; - z += a3; - v_first += a4; - v_second += a5 + a1; - w_first += a6; - w_second += a7; - - x = Rotate64(x, 26); - x *= 9; - y = Rotate64(y, 29); - z *= mul; - v_first = Rotate64(v_first, 33); - v_second = Rotate64(v_second, 30); - w_first ^= x; - w_first *= 9; - z = Rotate64(z, 32); - z += w_second; - w_second += z; - z *= 9; - swap(ref u, ref y); - - z += a0 + a6; - v_first += a2; - v_second += a3; - w_first += a4; - w_second += a5 + a6; - x += a1; - y += a7; - - y += v_first; - v_first += x - y; - v_second += w_first; - w_first += v_second; - w_second += x - y; - x += w_second; - w_second = Rotate64(w_second, 34); - swap(ref u, ref z); - s += 64; - } - while (s != end); - - // Make s point to the last 64 bytes of input. - s = last64; - u *= 9; - v_second = Rotate64(v_second, 28); - v_first = Rotate64(v_first, 20); - w_first += (len - 1) & 63; - u += y; - y += u; - x = Rotate64(y - x + v_first + Fetch64(s + 8), 37) * mul; - y = Rotate64(y ^ v_second ^ Fetch64(s + 48), 42) * mul; - x ^= w_second * 9; - y += v_first + Fetch64(s + 40); - z = Rotate64(z + w_first, 33) * mul; - WeakHashLen32WithSeeds(s, v_second * mul, x + w_first, out v_first, out v_second); - WeakHashLen32WithSeeds(s + 32, z + w_second, y + Fetch64(s + 16), out w_first, out w_second); - return H(HashLen16(v_first + x, w_first ^ y, mul) + z - u, H(v_second + y, w_second + z, k2, 30) ^ x, k2, 31); - } - } - - #endregion - } -} diff --git a/Assets/Plugins/MessagePack/Internal/FarmHash.cs.meta b/Assets/Plugins/MessagePack/Internal/FarmHash.cs.meta deleted file mode 100644 index bba8ec765..000000000 --- a/Assets/Plugins/MessagePack/Internal/FarmHash.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: fb5a050df97c09dd9b40337e9c0bbdcd -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Internal/GuidBits.cs b/Assets/Plugins/MessagePack/Internal/GuidBits.cs deleted file mode 100644 index c8b12de23..000000000 --- a/Assets/Plugins/MessagePack/Internal/GuidBits.cs +++ /dev/null @@ -1,391 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Runtime.InteropServices; - -namespace MessagePack.Internal -{ - [StructLayout(LayoutKind.Explicit, Pack = 1)] - internal struct GuidBits - { - [FieldOffset(0)] - public readonly Guid Value; - - [FieldOffset(0)] - public readonly byte Byte0; - [FieldOffset(1)] - public readonly byte Byte1; - [FieldOffset(2)] - public readonly byte Byte2; - [FieldOffset(3)] - public readonly byte Byte3; - [FieldOffset(4)] - public readonly byte Byte4; - [FieldOffset(5)] - public readonly byte Byte5; - [FieldOffset(6)] - public readonly byte Byte6; - [FieldOffset(7)] - public readonly byte Byte7; - [FieldOffset(8)] - public readonly byte Byte8; - [FieldOffset(9)] - public readonly byte Byte9; - [FieldOffset(10)] - public readonly byte Byte10; - [FieldOffset(11)] - public readonly byte Byte11; - [FieldOffset(12)] - public readonly byte Byte12; - [FieldOffset(13)] - public readonly byte Byte13; - [FieldOffset(14)] - public readonly byte Byte14; - [FieldOffset(15)] - public readonly byte Byte15; - - // string.Join(", ", Enumerable.Range(0, 256).Select(x => (int)BitConverter.ToString(new byte[] { (byte)x }).ToLower()[0])) - private static byte[] byteToHexStringHigh = new byte[256] { 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102 }; - - // string.Join(", ", Enumerable.Range(0, 256).Select(x => (int)BitConverter.ToString(new byte[] { (byte)x }).ToLower()[1])) - private static byte[] byteToHexStringLow = new byte[256] { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102 }; - - public GuidBits(ref Guid value) - { - this = default(GuidBits); - this.Value = value; - } - - // 4-pattern, lower/upper and '-' or no - public GuidBits(ReadOnlySpan utf8string) - { - this = default(GuidBits); - - // 32 - if (utf8string.Length == 32) - { - if (BitConverter.IsLittleEndian) - { - this.Byte0 = Parse(utf8string, 6); - this.Byte1 = Parse(utf8string, 4); - this.Byte2 = Parse(utf8string, 2); - this.Byte3 = Parse(utf8string, 0); - - this.Byte4 = Parse(utf8string, 10); - this.Byte5 = Parse(utf8string, 8); - - this.Byte6 = Parse(utf8string, 14); - this.Byte7 = Parse(utf8string, 12); - } - else - { - this.Byte0 = Parse(utf8string, 0); - this.Byte1 = Parse(utf8string, 2); - this.Byte2 = Parse(utf8string, 4); - this.Byte3 = Parse(utf8string, 6); - - this.Byte4 = Parse(utf8string, 8); - this.Byte5 = Parse(utf8string, 10); - - this.Byte6 = Parse(utf8string, 12); - this.Byte7 = Parse(utf8string, 14); - } - - this.Byte8 = Parse(utf8string, 16); - this.Byte9 = Parse(utf8string, 18); - - this.Byte10 = Parse(utf8string, 20); - this.Byte11 = Parse(utf8string, 22); - this.Byte12 = Parse(utf8string, 24); - this.Byte13 = Parse(utf8string, 26); - this.Byte14 = Parse(utf8string, 28); - this.Byte15 = Parse(utf8string, 30); - return; - } - else if (utf8string.Length == 36) - { - // '-' => 45 - if (BitConverter.IsLittleEndian) - { - this.Byte0 = Parse(utf8string, 6); - this.Byte1 = Parse(utf8string, 4); - this.Byte2 = Parse(utf8string, 2); - this.Byte3 = Parse(utf8string, 0); - - if (utf8string[8] != '-') - { - goto ERROR; - } - - this.Byte4 = Parse(utf8string, 11); - this.Byte5 = Parse(utf8string, 9); - - if (utf8string[13] != '-') - { - goto ERROR; - } - - this.Byte6 = Parse(utf8string, 16); - this.Byte7 = Parse(utf8string, 14); - } - else - { - this.Byte0 = Parse(utf8string, 0); - this.Byte1 = Parse(utf8string, 2); - this.Byte2 = Parse(utf8string, 4); - this.Byte3 = Parse(utf8string, 6); - - if (utf8string[8] != '-') - { - goto ERROR; - } - - this.Byte4 = Parse(utf8string, 9); - this.Byte5 = Parse(utf8string, 11); - - if (utf8string[13] != '-') - { - goto ERROR; - } - - this.Byte6 = Parse(utf8string, 14); - this.Byte7 = Parse(utf8string, 16); - } - - if (utf8string[18] != '-') - { - goto ERROR; - } - - this.Byte8 = Parse(utf8string, 19); - this.Byte9 = Parse(utf8string, 21); - - if (utf8string[23] != '-') - { - goto ERROR; - } - - this.Byte10 = Parse(utf8string, 24); - this.Byte11 = Parse(utf8string, 26); - this.Byte12 = Parse(utf8string, 28); - this.Byte13 = Parse(utf8string, 30); - this.Byte14 = Parse(utf8string, 32); - this.Byte15 = Parse(utf8string, 34); - return; - } - -ERROR: - throw new MessagePackSerializationException("Invalid Guid Pattern."); - } - -#if !UNITY_2018_3_OR_NEWER - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] -#endif - private static byte Parse(ReadOnlySpan bytes, int highOffset) - { - return unchecked((byte)((SwitchParse(bytes[highOffset]) * 16) + SwitchParse(bytes[highOffset + 1]))); - } - -#if !UNITY_2018_3_OR_NEWER - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] -#endif - private static byte SwitchParse(byte b) - { - // '0'(48) ~ '9'(57) => -48 - // 'A'(65) ~ 'F'(70) => -55 - // 'a'(97) ~ 'f'(102) => -87 - switch (b) - { - case 48: - case 49: - case 50: - case 51: - case 52: - case 53: - case 54: - case 55: - case 56: - case 57: - return unchecked((byte)(b - 48)); - case 65: - case 66: - case 67: - case 68: - case 69: - case 70: - return unchecked((byte)(b - 55)); - case 97: - case 98: - case 99: - case 100: - case 101: - case 102: - return unchecked((byte)(b - 87)); - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - case 8: - case 9: - case 10: - case 11: - case 12: - case 13: - case 14: - case 15: - case 16: - case 17: - case 18: - case 19: - case 20: - case 21: - case 22: - case 23: - case 24: - case 25: - case 26: - case 27: - case 28: - case 29: - case 30: - case 31: - case 32: - case 33: - case 34: - case 35: - case 36: - case 37: - case 38: - case 39: - case 40: - case 41: - case 42: - case 43: - case 44: - case 45: - case 46: - case 47: - case 58: - case 59: - case 60: - case 61: - case 62: - case 63: - case 64: - case 71: - case 72: - case 73: - case 74: - case 75: - case 76: - case 77: - case 78: - case 79: - case 80: - case 81: - case 82: - case 83: - case 84: - case 85: - case 86: - case 87: - case 88: - case 89: - case 90: - case 91: - case 92: - case 93: - case 94: - case 95: - case 96: - default: - throw new MessagePackSerializationException("Invalid Guid Pattern."); - } - } - - // 4(x2) - 2(x2) - 2(x2) - 2(x2) - 6(x2) - public void Write(Span buffer) - { - if (BitConverter.IsLittleEndian) - { - // int(_a) - buffer[6] = byteToHexStringHigh[this.Byte0]; - buffer[7] = byteToHexStringLow[this.Byte0]; - buffer[4] = byteToHexStringHigh[this.Byte1]; - buffer[5] = byteToHexStringLow[this.Byte1]; - buffer[2] = byteToHexStringHigh[this.Byte2]; - buffer[3] = byteToHexStringLow[this.Byte2]; - buffer[0] = byteToHexStringHigh[this.Byte3]; - buffer[1] = byteToHexStringLow[this.Byte3]; - - buffer[8] = (byte)'-'; - - // short(_b) - buffer[11] = byteToHexStringHigh[this.Byte4]; - buffer[12] = byteToHexStringLow[this.Byte4]; - buffer[9] = byteToHexStringHigh[this.Byte5]; - buffer[10] = byteToHexStringLow[this.Byte5]; - - buffer[13] = (byte)'-'; - - // short(_c) - buffer[16] = byteToHexStringHigh[this.Byte6]; - buffer[17] = byteToHexStringLow[this.Byte6]; - buffer[14] = byteToHexStringHigh[this.Byte7]; - buffer[15] = byteToHexStringLow[this.Byte7]; - } - else - { - buffer[0] = byteToHexStringHigh[this.Byte0]; - buffer[1] = byteToHexStringLow[this.Byte0]; - buffer[2] = byteToHexStringHigh[this.Byte1]; - buffer[3] = byteToHexStringLow[this.Byte1]; - buffer[4] = byteToHexStringHigh[this.Byte2]; - buffer[5] = byteToHexStringLow[this.Byte2]; - buffer[6] = byteToHexStringHigh[this.Byte3]; - buffer[7] = byteToHexStringLow[this.Byte3]; - - buffer[8] = (byte)'-'; - - buffer[9] = byteToHexStringHigh[this.Byte4]; - buffer[10] = byteToHexStringLow[this.Byte4]; - buffer[11] = byteToHexStringHigh[this.Byte5]; - buffer[12] = byteToHexStringLow[this.Byte5]; - - buffer[13] = (byte)'-'; - - buffer[14] = byteToHexStringHigh[this.Byte6]; - buffer[15] = byteToHexStringLow[this.Byte6]; - buffer[16] = byteToHexStringHigh[this.Byte7]; - buffer[17] = byteToHexStringLow[this.Byte7]; - } - - buffer[18] = (byte)'-'; - - buffer[19] = byteToHexStringHigh[this.Byte8]; - buffer[20] = byteToHexStringLow[this.Byte8]; - buffer[21] = byteToHexStringHigh[this.Byte9]; - buffer[22] = byteToHexStringLow[this.Byte9]; - - buffer[23] = (byte)'-'; - - buffer[24] = byteToHexStringHigh[this.Byte10]; - buffer[25] = byteToHexStringLow[this.Byte10]; - buffer[26] = byteToHexStringHigh[this.Byte11]; - buffer[27] = byteToHexStringLow[this.Byte11]; - buffer[28] = byteToHexStringHigh[this.Byte12]; - buffer[29] = byteToHexStringLow[this.Byte12]; - buffer[30] = byteToHexStringHigh[this.Byte13]; - buffer[31] = byteToHexStringLow[this.Byte13]; - buffer[32] = byteToHexStringHigh[this.Byte14]; - buffer[33] = byteToHexStringLow[this.Byte14]; - buffer[34] = byteToHexStringHigh[this.Byte15]; - buffer[35] = byteToHexStringLow[this.Byte15]; - } - } -} diff --git a/Assets/Plugins/MessagePack/Internal/GuidBits.cs.meta b/Assets/Plugins/MessagePack/Internal/GuidBits.cs.meta deleted file mode 100644 index dbebe57a6..000000000 --- a/Assets/Plugins/MessagePack/Internal/GuidBits.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 0bb83f98e290402db9fcb6da74f773ca -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Internal/ILGeneratorExtensions.cs b/Assets/Plugins/MessagePack/Internal/ILGeneratorExtensions.cs deleted file mode 100644 index aabada186..000000000 --- a/Assets/Plugins/MessagePack/Internal/ILGeneratorExtensions.cs +++ /dev/null @@ -1,401 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if !(UNITY_2018_3_OR_NEWER && NET_STANDARD_2_0) - -using System; -using System.Linq; -using System.Reflection; -using System.Reflection.Emit; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Internal -{ - internal struct ArgumentField - { - private readonly int i; - private readonly bool @ref; - private readonly ILGenerator il; - - public ArgumentField(ILGenerator il, int i, bool @ref = false) - { - this.il = il; - this.i = i; - this.@ref = @ref; - } - - public ArgumentField(ILGenerator il, int i, Type type) - { - this.il = il; - this.i = i; - TypeInfo ti = type.GetTypeInfo(); - this.@ref = (ti.IsClass || ti.IsInterface || ti.IsAbstract) ? false : true; - } - - public void EmitLoad() - { - if (this.@ref) - { - this.il.EmitLdarga(this.i); - } - else - { - this.il.EmitLdarg(this.i); - } - } - - public void EmitLdarg() - { - this.il.EmitLdarg(this.i); - } - - public void EmitLdarga() - { - this.il.EmitLdarga(this.i); - } - - public void EmitStore() - { - this.il.EmitStarg(this.i); - } - } - - /// - /// Provides optimized generation code and helpers. - /// - internal static class ILGeneratorExtensions - { - /// - /// Loads the local variable at a specific index onto the evaluation stack. - /// - public static void EmitLdloc(this ILGenerator il, int index) - { - switch (index) - { - case 0: - il.Emit(OpCodes.Ldloc_0); - break; - case 1: - il.Emit(OpCodes.Ldloc_1); - break; - case 2: - il.Emit(OpCodes.Ldloc_2); - break; - case 3: - il.Emit(OpCodes.Ldloc_3); - break; - default: - if (index <= 255) - { - il.Emit(OpCodes.Ldloc_S, (byte)index); - } - else - { - il.Emit(OpCodes.Ldloc, (short)index); - } - - break; - } - } - - public static void EmitLdloc(this ILGenerator il, LocalBuilder local) - { - EmitLdloc(il, local.LocalIndex); - } - - /// - /// Pops the current value from the top of the evaluation stack and stores it in a the local variable list at a specified index. - /// - public static void EmitStloc(this ILGenerator il, int index) - { - switch (index) - { - case 0: - il.Emit(OpCodes.Stloc_0); - break; - case 1: - il.Emit(OpCodes.Stloc_1); - break; - case 2: - il.Emit(OpCodes.Stloc_2); - break; - case 3: - il.Emit(OpCodes.Stloc_3); - break; - default: - if (index <= 255) - { - il.Emit(OpCodes.Stloc_S, (byte)index); - } - else - { - il.Emit(OpCodes.Stloc, (short)index); - } - - break; - } - } - - public static void EmitStloc(this ILGenerator il, LocalBuilder local) - { - EmitStloc(il, local.LocalIndex); - } - - /// - /// Loads the address of the local variable at a specific index onto the evaluation statck. - /// - public static void EmitLdloca(this ILGenerator il, int index) - { - if (index <= 255) - { - il.Emit(OpCodes.Ldloca_S, (byte)index); - } - else - { - il.Emit(OpCodes.Ldloca, (short)index); - } - } - - public static void EmitLdloca(this ILGenerator il, LocalBuilder local) - { - EmitLdloca(il, local.LocalIndex); - } - - public static void EmitTrue(this ILGenerator il) - { - EmitBoolean(il, true); - } - - public static void EmitFalse(this ILGenerator il) - { - EmitBoolean(il, false); - } - - public static void EmitBoolean(this ILGenerator il, bool value) - { - EmitLdc_I4(il, value ? 1 : 0); - } - - /// - /// Pushes a supplied value of type int32 onto the evaluation stack as an int32. - /// - public static void EmitLdc_I4(this ILGenerator il, int value) - { - switch (value) - { - case -1: - il.Emit(OpCodes.Ldc_I4_M1); - break; - case 0: - il.Emit(OpCodes.Ldc_I4_0); - break; - case 1: - il.Emit(OpCodes.Ldc_I4_1); - break; - case 2: - il.Emit(OpCodes.Ldc_I4_2); - break; - case 3: - il.Emit(OpCodes.Ldc_I4_3); - break; - case 4: - il.Emit(OpCodes.Ldc_I4_4); - break; - case 5: - il.Emit(OpCodes.Ldc_I4_5); - break; - case 6: - il.Emit(OpCodes.Ldc_I4_6); - break; - case 7: - il.Emit(OpCodes.Ldc_I4_7); - break; - case 8: - il.Emit(OpCodes.Ldc_I4_8); - break; - default: - if (value >= -128 && value <= 127) - { - il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); - } - else - { - il.Emit(OpCodes.Ldc_I4, value); - } - - break; - } - } - - public static void EmitUnboxOrCast(this ILGenerator il, Type type) - { - if (type.GetTypeInfo().IsValueType) - { - il.Emit(OpCodes.Unbox_Any, type); - } - else - { - il.Emit(OpCodes.Castclass, type); - } - } - - public static void EmitBoxOrDoNothing(this ILGenerator il, Type type) - { - if (type.GetTypeInfo().IsValueType) - { - il.Emit(OpCodes.Box, type); - } - } - - public static void EmitLdarg(this ILGenerator il, int index) - { - switch (index) - { - case 0: - il.Emit(OpCodes.Ldarg_0); - break; - case 1: - il.Emit(OpCodes.Ldarg_1); - break; - case 2: - il.Emit(OpCodes.Ldarg_2); - break; - case 3: - il.Emit(OpCodes.Ldarg_3); - break; - default: - if (index <= 255) - { - il.Emit(OpCodes.Ldarg_S, (byte)index); - } - else - { - il.Emit(OpCodes.Ldarg, index); - } - - break; - } - } - - public static void EmitLoadThis(this ILGenerator il) - { - EmitLdarg(il, 0); - } - - public static void EmitLdarga(this ILGenerator il, int index) - { - if (index <= 255) - { - il.Emit(OpCodes.Ldarga_S, (byte)index); - } - else - { - il.Emit(OpCodes.Ldarga, index); - } - } - - public static void EmitStarg(this ILGenerator il, int index) - { - if (index <= 255) - { - il.Emit(OpCodes.Starg_S, (byte)index); - } - else - { - il.Emit(OpCodes.Starg, index); - } - } - - /// - /// Helper for Pop op. - /// - public static void EmitPop(this ILGenerator il, int count) - { - for (int i = 0; i < count; i++) - { - il.Emit(OpCodes.Pop); - } - } - - public static void EmitCall(this ILGenerator il, MethodInfo methodInfo) - { - if (methodInfo.IsFinal || !methodInfo.IsVirtual) - { - il.Emit(OpCodes.Call, methodInfo); - } - else - { - il.Emit(OpCodes.Callvirt, methodInfo); - } - } - - public static void EmitLdfld(this ILGenerator il, FieldInfo fieldInfo) - { - il.Emit(OpCodes.Ldfld, fieldInfo); - } - - public static void EmitLdsfld(this ILGenerator il, FieldInfo fieldInfo) - { - il.Emit(OpCodes.Ldsfld, fieldInfo); - } - - public static void EmitRet(this ILGenerator il) - { - il.Emit(OpCodes.Ret); - } - - public static void EmitIntZeroReturn(this ILGenerator il) - { - il.EmitLdc_I4(0); - il.Emit(OpCodes.Ret); - } - - public static void EmitNullReturn(this ILGenerator il) - { - il.Emit(OpCodes.Ldnull); - il.Emit(OpCodes.Ret); - } - - public static void EmitULong(this ILGenerator il, ulong value) - { - il.Emit(OpCodes.Ldc_I8, unchecked((long)value)); - } - - public static void EmitThrowNotimplemented(this ILGenerator il) - { - il.Emit(OpCodes.Newobj, typeof(System.NotImplementedException).GetTypeInfo().DeclaredConstructors.First(x => x.GetParameters().Length == 0)); - il.Emit(OpCodes.Throw); - } - - /// for var i = 0, i ..., i++. - public static void EmitIncrementFor(this ILGenerator il, LocalBuilder conditionGreater, Action emitBody) - { - Label loopBegin = il.DefineLabel(); - Label condtionLabel = il.DefineLabel(); - - // var i = 0 - LocalBuilder forI = il.DeclareLocal(typeof(int)); - il.EmitLdc_I4(0); - il.EmitStloc(forI); - il.Emit(OpCodes.Br, condtionLabel); - - il.MarkLabel(loopBegin); - emitBody(forI); - - // i++ - il.EmitLdloc(forI); - il.EmitLdc_I4(1); - il.Emit(OpCodes.Add); - il.EmitStloc(forI); - - //// i < *** - il.MarkLabel(condtionLabel); - il.EmitLdloc(forI); - il.EmitLdloc(conditionGreater); - il.Emit(OpCodes.Blt, loopBegin); - } - } -} - -#endif diff --git a/Assets/Plugins/MessagePack/Internal/ILGeneratorExtensions.cs.meta b/Assets/Plugins/MessagePack/Internal/ILGeneratorExtensions.cs.meta deleted file mode 100644 index f8017439d..000000000 --- a/Assets/Plugins/MessagePack/Internal/ILGeneratorExtensions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a7fcc89bc1ce33b46b7e5d8bcaa7f0fa -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Internal/ReflectionExtensions.cs b/Assets/Plugins/MessagePack/Internal/ReflectionExtensions.cs deleted file mode 100644 index 33052b096..000000000 --- a/Assets/Plugins/MessagePack/Internal/ReflectionExtensions.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace MessagePack.Internal -{ - internal static class ReflectionExtensions - { - public static bool IsNullable(this System.Reflection.TypeInfo type) - { - return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Nullable<>); - } - - public static bool IsPublic(this System.Reflection.TypeInfo type) - { - return type.IsPublic; - } - - public static bool IsAnonymous(this System.Reflection.TypeInfo type) - { - return type.GetCustomAttribute() != null - && type.IsGenericType && type.Name.Contains("AnonymousType") - && (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$")) - && (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic; - } - - public static bool IsIndexer(this System.Reflection.PropertyInfo propertyInfo) - { - return propertyInfo.GetIndexParameters().Length > 0; - } - - public static bool IsConstructedGenericType(this System.Reflection.TypeInfo type) - { - return type.AsType().IsConstructedGenericType; - } - - public static MethodInfo GetGetMethod(this PropertyInfo propInfo) - { - return propInfo.GetMethod; - } - - public static MethodInfo GetSetMethod(this PropertyInfo propInfo) - { - return propInfo.SetMethod; - } - } -} diff --git a/Assets/Plugins/MessagePack/Internal/ReflectionExtensions.cs.meta b/Assets/Plugins/MessagePack/Internal/ReflectionExtensions.cs.meta deleted file mode 100644 index b8c951777..000000000 --- a/Assets/Plugins/MessagePack/Internal/ReflectionExtensions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 82787207c36d0a4a98d7f53b49ba1576 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Internal/Sequence`1.cs b/Assets/Plugins/MessagePack/Internal/Sequence`1.cs deleted file mode 100644 index 62232e48b..000000000 --- a/Assets/Plugins/MessagePack/Internal/Sequence`1.cs +++ /dev/null @@ -1,573 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -/* Original license and copyright from file copied from https://github.com/AArnott/Nerdbank.Streams/blob/d656899be26d4d7c72c11c9232b4952c64a89bcb/src/Nerdbank.Streams/Sequence%601.cs - * Copyright (c) Andrew Arnott. All rights reserved. - * Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. -*/ - -using System; -using System.Buffers; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace Nerdbank.Streams -{ - /// - /// Manages a sequence of elements, readily castable as a . - /// - /// The type of element stored by the sequence. - /// - /// Instance members are not thread-safe. - /// - [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] - internal class Sequence : IBufferWriter, IDisposable - { - private static readonly int DefaultLengthFromArrayPool = 1 + (4095 / Marshal.SizeOf()); - - private readonly Stack segmentPool = new Stack(); - - private readonly MemoryPool memoryPool; - - private readonly ArrayPool arrayPool; - - private SequenceSegment first; - - private SequenceSegment last; - - /// - /// Initializes a new instance of the class - /// that uses a private for recycling arrays. - /// - public Sequence() - : this(ArrayPool.Create()) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The pool to use for recycling backing arrays. - public Sequence(MemoryPool memoryPool) - { - Requires.NotNull(memoryPool, nameof(memoryPool)); - this.memoryPool = memoryPool; - } - - /// - /// Initializes a new instance of the class. - /// - /// The pool to use for recycling backing arrays. - public Sequence(ArrayPool arrayPool) - { - Requires.NotNull(arrayPool, nameof(arrayPool)); - this.arrayPool = arrayPool; - } - - /// - /// Gets or sets the minimum length for any array allocated as a segment in the sequence. - /// Any non-positive value allows the pool to determine the length of the array. - /// - /// The default value is 0. - /// - /// - /// Each time or is called, - /// previously allocated memory is used if it is large enough to satisfy the length demand. - /// If new memory must be allocated, the argument to one of these methods typically dictate - /// the length of array to allocate. When the caller uses very small values (just enough for its immediate need) - /// but the high level scenario can predict that a large amount of memory will be ultimately required, - /// it can be advisable to set this property to a value such that just a few larger arrays are allocated - /// instead of many small ones. - /// - /// - /// The in use may itself have a minimum array length as well, - /// in which case the higher of the two minimums dictate the minimum array size that will be allocated. - /// - /// - public int MinimumSpanLength { get; set; } = 0; - - /// - /// Gets this sequence expressed as a . - /// - /// A read only sequence representing the data in this object. - public ReadOnlySequence AsReadOnlySequence => this; - - /// - /// Gets the length of the sequence. - /// - public long Length => this.AsReadOnlySequence.Length; - - /// - /// Gets the value to display in a debugger datatip. - /// - private string DebuggerDisplay => $"Length: {this.AsReadOnlySequence.Length}"; - - /// - /// Expresses this sequence as a . - /// - /// The sequence to convert. - public static implicit operator ReadOnlySequence(Sequence sequence) - { - return sequence.first != null - ? new ReadOnlySequence(sequence.first, sequence.first.Start, sequence.last, sequence.last.End) - : ReadOnlySequence.Empty; - } - - /// - /// Removes all elements from the sequence from its beginning to the specified position, - /// considering that data to have been fully processed. - /// - /// - /// The position of the first element that has not yet been processed. - /// This is typically after reading all elements from that instance. - /// - public void AdvanceTo(SequencePosition position) - { - var firstSegment = (SequenceSegment)position.GetObject(); - int firstIndex = position.GetInteger(); - - // Before making any mutations, confirm that the block specified belongs to this sequence. - var current = this.first; - while (current != firstSegment && current != null) - { - current = current.Next; - } - - Requires.Argument(current != null, nameof(position), "Position does not represent a valid position in this sequence."); - - // Also confirm that the position is not a prior position in the block. - Requires.Argument(firstIndex >= current.Start, nameof(position), "Position must not be earlier than current position."); - - // Now repeat the loop, performing the mutations. - current = this.first; - while (current != firstSegment) - { - current = this.RecycleAndGetNext(current); - } - - firstSegment.AdvanceTo(firstIndex); - - if (firstSegment.Length == 0) - { - firstSegment = this.RecycleAndGetNext(firstSegment); - } - - this.first = firstSegment; - - if (this.first == null) - { - this.last = null; - } - } - - /// - /// Advances the sequence to include the specified number of elements initialized into memory - /// returned by a prior call to . - /// - /// The number of elements written into memory. - public void Advance(int count) - { - SequenceSegment last = this.last; - Verify.Operation(last != null, "Cannot advance before acquiring memory."); - last.Advance(count); - } - - /// - /// Gets writable memory that can be initialized and added to the sequence via a subsequent call to . - /// - /// The size of the memory required, or 0 to just get a convenient (non-empty) buffer. - /// The requested memory. - public Memory GetMemory(int sizeHint) => this.GetSegment(sizeHint).RemainingMemory; - - /// - /// Gets writable memory that can be initialized and added to the sequence via a subsequent call to . - /// - /// The size of the memory required, or 0 to just get a convenient (non-empty) buffer. - /// The requested memory. - public Span GetSpan(int sizeHint) => this.GetSegment(sizeHint).RemainingSpan; - - /// - /// Clears the entire sequence, recycles associated memory into pools, - /// and resets this instance for reuse. - /// This invalidates any previously produced by this instance. - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public void Dispose() => this.Reset(); - - /// - /// Clears the entire sequence and recycles associated memory into pools. - /// This invalidates any previously produced by this instance. - /// - public void Reset() - { - var current = this.first; - while (current != null) - { - current = this.RecycleAndGetNext(current); - } - - this.first = this.last = null; - } - - private SequenceSegment GetSegment(int sizeHint) - { - Requires.Range(sizeHint >= 0, nameof(sizeHint)); - int? minBufferSize = null; - if (sizeHint == 0) - { - if (this.last == null || this.last.WritableBytes == 0) - { - // We're going to need more memory. Take whatever size the pool wants to give us. - minBufferSize = -1; - } - } - else - { - sizeHint = Math.Max(this.MinimumSpanLength, sizeHint); - if (this.last == null || this.last.WritableBytes < sizeHint) - { - minBufferSize = sizeHint; - } - } - - if (minBufferSize.HasValue) - { - var segment = this.segmentPool.Count > 0 ? this.segmentPool.Pop() : new SequenceSegment(); - if (this.arrayPool != null) - { - segment.Assign(this.arrayPool.Rent(minBufferSize.Value == -1 ? DefaultLengthFromArrayPool : minBufferSize.Value)); - } - else - { - segment.Assign(this.memoryPool.Rent(minBufferSize.Value)); - } - - this.Append(segment); - } - - return this.last; - } - - private void Append(SequenceSegment segment) - { - if (this.last == null) - { - this.first = this.last = segment; - } - else - { - if (this.last.Length > 0) - { - // Add a new block. - this.last.SetNext(segment); - } - else - { - // The last block is completely unused. Replace it instead of appending to it. - var current = this.first; - if (this.first != this.last) - { - while (current.Next != this.last) - { - current = current.Next; - } - } - else - { - this.first = segment; - } - - current.SetNext(segment); - this.RecycleAndGetNext(this.last); - } - - this.last = segment; - } - } - - private SequenceSegment RecycleAndGetNext(SequenceSegment segment) - { - var recycledSegment = segment; - segment = segment.Next; - recycledSegment.ResetMemory(this.arrayPool); - this.segmentPool.Push(recycledSegment); - return segment; - } - - private class SequenceSegment : ReadOnlySequenceSegment - { - /// - /// A value indicating whether the element is a value type. - /// - private static readonly bool IsValueTypeElement = typeof(T).GetTypeInfo().IsValueType; - - /// - /// Gets the backing array, when using an instead of a . - /// - private T[] array; - - /// - /// Gets the position within where the data starts. - /// - /// This may be nonzero as a result of calling . - internal int Start { get; private set; } - - /// - /// Gets the position within where the data ends. - /// - internal int End { get; private set; } - - /// - /// Gets the tail of memory that has not yet been committed. - /// - internal Memory RemainingMemory => this.AvailableMemory.Slice(this.End); - - /// - /// Gets the tail of memory that has not yet been committed. - /// - internal Span RemainingSpan => this.AvailableMemory.Span.Slice(this.End); - - /// - /// Gets the tracker for the underlying array for this segment, which can be used to recycle the array when we're disposed of. - /// Will be null if using an array pool, in which case the memory is held by . - /// - internal IMemoryOwner MemoryOwner { get; private set; } - - /// - /// Gets the full memory owned by the . - /// - internal Memory AvailableMemory => this.array ?? this.MemoryOwner?.Memory ?? default; - - /// - /// Gets the number of elements that are committed in this segment. - /// - internal int Length => this.End - this.Start; - - /// - /// Gets the amount of writable bytes in this segment. - /// It is the amount of bytes between and . - /// - internal int WritableBytes => this.AvailableMemory.Length - this.End; - - /// - /// Gets or sets the next segment in the singly linked list of segments. - /// - internal new SequenceSegment Next - { - get => (SequenceSegment)base.Next; - set => base.Next = value; - } - - /// - /// Assigns this (recyclable) segment a new area in memory. - /// - /// The memory and a means to recycle it. - internal void Assign(IMemoryOwner memoryOwner) - { - this.MemoryOwner = memoryOwner; - this.Memory = memoryOwner.Memory; - } - - /// - /// Assigns this (recyclable) segment a new area in memory. - /// - /// An array drawn from an . - internal void Assign(T[] array) - { - this.array = array; - this.Memory = array; - } - - /// - /// Clears all fields in preparation to recycle this instance. - /// - internal void ResetMemory(ArrayPool arrayPool) - { - this.ClearReferences(this.Start, this.End); - this.Memory = default; - this.Next = null; - this.RunningIndex = 0; - this.Start = 0; - this.End = 0; - if (this.array != null) - { - arrayPool.Return(this.array); - this.array = null; - } - else - { - this.MemoryOwner?.Dispose(); - this.MemoryOwner = null; - } - } - - /// - /// Adds a new segment after this one. - /// - /// The next segment in the linked list. - internal void SetNext(SequenceSegment segment) - { - Debug.Assert(segment != null, "Null not allowed."); - this.Next = segment; - segment.RunningIndex = this.RunningIndex + this.Start + this.Length; - - // When setting Memory, we start with index 0 instead of this.Start because - // the first segment has an explicit index set anyway, - // and we don't want to double-count it here. - this.Memory = this.AvailableMemory.Slice(0, this.Start + this.Length); - } - - /// - /// Commits more elements as written in this segment. - /// - /// The number of elements written. - internal void Advance(int count) - { - Requires.Range(count >= 0 && this.End + count <= this.Memory.Length, nameof(count)); - this.End += count; - } - - /// - /// Removes some elements from the start of this segment. - /// - /// The number of elements to ignore from the start of the underlying array. - internal void AdvanceTo(int offset) - { - Debug.Assert(offset >= this.Start, "Trying to rewind."); - this.ClearReferences(this.Start, offset - this.Start); - this.Start = offset; - } - - private void ClearReferences(int startIndex, int length) - { - // If we store references, clear them to allow the objects to be GC'd. - if (!IsValueTypeElement) - { - this.AvailableMemory.Span.Slice(startIndex, length).Fill(default); - } - } - } - } - - internal static class Requires - { - /// - /// Throws an if a condition does not evaluate to true. - /// - [DebuggerStepThrough] - public static void Range(bool condition, string parameterName, string message = null) - { - if (!condition) - { - FailRange(parameterName, message); - } - } - - /// - /// Throws an if a condition does not evaluate to true. - /// - /// Nothing. This method always throws. - [DebuggerStepThrough] - public static Exception FailRange(string parameterName, string message = null) - { - if (string.IsNullOrEmpty(message)) - { - throw new ArgumentOutOfRangeException(parameterName); - } - else - { - throw new ArgumentOutOfRangeException(parameterName, message); - } - } - - /// - /// Throws an exception if the specified parameter's value is null. - /// - /// The type of the parameter. - /// The value of the argument. - /// The name of the parameter to include in any thrown exception. - /// The value of the parameter. - /// Thrown if is null. - [DebuggerStepThrough] - public static T NotNull(T value, string parameterName) - where T : class // ensures value-types aren't passed to a null checking method - { - if (value == null) - { - throw new ArgumentNullException(parameterName); - } - - return value; - } - - /// - /// Throws an ArgumentException if a condition does not evaluate to true. - /// - [DebuggerStepThrough] - public static void Argument(bool condition, string parameterName, string message) - { - if (!condition) - { - throw new ArgumentException(message, parameterName); - } - } - - /// - /// Throws an ArgumentException if a condition does not evaluate to true. - /// - [DebuggerStepThrough] - public static void Argument(bool condition, string parameterName, string message, object arg1) - { - if (!condition) - { - throw new ArgumentException(String.Format(message, arg1), parameterName); - } - } - - /// - /// Throws an ArgumentException if a condition does not evaluate to true. - /// - [DebuggerStepThrough] - public static void Argument(bool condition, string parameterName, string message, object arg1, object arg2) - { - if (!condition) - { - throw new ArgumentException(String.Format(message, arg1, arg2), parameterName); - } - } - - /// - /// Throws an ArgumentException if a condition does not evaluate to true. - /// - [DebuggerStepThrough] - public static void Argument(bool condition, string parameterName, string message, params object[] args) - { - if (!condition) - { - throw new ArgumentException(String.Format(message, args), parameterName); - } - } - } - - /// - /// Common runtime checks that throw exceptions upon failure. - /// - internal static partial class Verify - { - /// - /// Throws an if a condition is false. - /// - [DebuggerStepThrough] - internal static void Operation(bool condition, string message) - { - if (!condition) - { - throw new InvalidOperationException(message); - } - } - } -} diff --git a/Assets/Plugins/MessagePack/Internal/Sequence`1.cs.meta b/Assets/Plugins/MessagePack/Internal/Sequence`1.cs.meta deleted file mode 100644 index 3ce445047..000000000 --- a/Assets/Plugins/MessagePack/Internal/Sequence`1.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 19e730b2bfc50b981bdcd41c703daab2 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Internal/ThreadsafeTypeKeyHashTable.cs b/Assets/Plugins/MessagePack/Internal/ThreadsafeTypeKeyHashTable.cs deleted file mode 100644 index 74d954630..000000000 --- a/Assets/Plugins/MessagePack/Internal/ThreadsafeTypeKeyHashTable.cs +++ /dev/null @@ -1,246 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Runtime.CompilerServices; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Internal -{ - /// - /// A dictionary where is the key, and a configurable type - /// that is thread-safe to read and write, allowing concurrent reads and exclusive writes. - /// - /// The type of value stored in the dictionary. - internal class ThreadsafeTypeKeyHashTable - { - private Entry[] buckets; - private int size; // only use in writer lock - - private readonly object writerLock = new object(); - private readonly float loadFactor; - - // IEqualityComparer.Equals is overhead if key only Type, don't use it. - //// readonly IEqualityComparer comparer; - - public ThreadsafeTypeKeyHashTable(int capacity = 4, float loadFactor = 0.75f) - { - var tableSize = CalculateCapacity(capacity, loadFactor); - this.buckets = new Entry[tableSize]; - this.loadFactor = loadFactor; - } - - public bool TryAdd(Type key, TValue value) - { - return this.TryAdd(key, _ => value); // create lambda capture - } - - public bool TryAdd(Type key, Func valueFactory) - { - return this.TryAddInternal(key, valueFactory, out TValue _); - } - - private bool TryAddInternal(Type key, Func valueFactory, out TValue resultingValue) - { - lock (this.writerLock) - { - var nextCapacity = CalculateCapacity(this.size + 1, this.loadFactor); - - if (this.buckets.Length < nextCapacity) - { - // rehash - var nextBucket = new Entry[nextCapacity]; - for (int i = 0; i < this.buckets.Length; i++) - { - Entry e = this.buckets[i]; - while (e != null) - { - var newEntry = new Entry { Key = e.Key, Value = e.Value, Hash = e.Hash }; - this.AddToBuckets(nextBucket, key, newEntry, null, out resultingValue); - e = e.Next; - } - } - - // add entry(if failed to add, only do resize) - var successAdd = this.AddToBuckets(nextBucket, key, null, valueFactory, out resultingValue); - - // replace field(threadsafe for read) - VolatileWrite(ref this.buckets, nextBucket); - - if (successAdd) - { - this.size++; - } - - return successAdd; - } - else - { - // add entry(insert last is thread safe for read) - var successAdd = this.AddToBuckets(this.buckets, key, null, valueFactory, out resultingValue); - if (successAdd) - { - this.size++; - } - - return successAdd; - } - } - } - - private bool AddToBuckets(Entry[] buckets, Type newKey, Entry newEntryOrNull, Func valueFactory, out TValue resultingValue) - { - var h = (newEntryOrNull != null) ? newEntryOrNull.Hash : newKey.GetHashCode(); - if (buckets[h & (buckets.Length - 1)] == null) - { - if (newEntryOrNull != null) - { - resultingValue = newEntryOrNull.Value; - VolatileWrite(ref buckets[h & (buckets.Length - 1)], newEntryOrNull); - } - else - { - resultingValue = valueFactory(newKey); - VolatileWrite(ref buckets[h & (buckets.Length - 1)], new Entry { Key = newKey, Value = resultingValue, Hash = h }); - } - } - else - { - Entry searchLastEntry = buckets[h & (buckets.Length - 1)]; - while (true) - { - if (searchLastEntry.Key == newKey) - { - resultingValue = searchLastEntry.Value; - return false; - } - - if (searchLastEntry.Next == null) - { - if (newEntryOrNull != null) - { - resultingValue = newEntryOrNull.Value; - VolatileWrite(ref searchLastEntry.Next, newEntryOrNull); - } - else - { - resultingValue = valueFactory(newKey); - VolatileWrite(ref searchLastEntry.Next, new Entry { Key = newKey, Value = resultingValue, Hash = h }); - } - - break; - } - - searchLastEntry = searchLastEntry.Next; - } - } - - return true; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool TryGetValue(Type key, out TValue value) - { - Entry[] table = this.buckets; - var hash = key.GetHashCode(); - Entry entry = table[hash & table.Length - 1]; - - while (entry != null) - { - if (entry.Key == key) - { - value = entry.Value; - return true; - } - - entry = entry.Next; - } - - value = default(TValue); - return false; - } - - public TValue GetOrAdd(Type key, Func valueFactory) - { - TValue v; - if (this.TryGetValue(key, out v)) - { - return v; - } - - this.TryAddInternal(key, valueFactory, out v); - return v; - } - - private static int CalculateCapacity(int collectionSize, float loadFactor) - { - var initialCapacity = (int)(((float)collectionSize) / loadFactor); - var capacity = 1; - while (capacity < initialCapacity) - { - capacity <<= 1; - } - - if (capacity < 8) - { - return 8; - } - - return capacity; - } - - private static void VolatileWrite(ref Entry location, Entry value) - { -#if !UNITY_2018_3_OR_NEWER - System.Threading.Volatile.Write(ref location, value); -#elif UNITY_2018_3_OR_NEWER || NET_4_6 - System.Threading.Volatile.Write(ref location, value); -#else - System.Threading.Thread.MemoryBarrier(); - location = value; -#endif - } - - private static void VolatileWrite(ref Entry[] location, Entry[] value) - { -#if !UNITY_2018_3_OR_NEWER - System.Threading.Volatile.Write(ref location, value); -#elif UNITY_2018_3_OR_NEWER || NET_4_6 - System.Threading.Volatile.Write(ref location, value); -#else - System.Threading.Thread.MemoryBarrier(); - location = value; -#endif - } - - private class Entry - { -#pragma warning disable SA1401 // Fields should be private - internal Type Key; - internal TValue Value; - internal int Hash; - internal Entry Next; -#pragma warning restore SA1401 // Fields should be private - - // debug only - public override string ToString() - { - return this.Key + "(" + this.Count() + ")"; - } - - private int Count() - { - var count = 1; - Entry n = this; - while (n.Next != null) - { - count++; - n = n.Next; - } - - return count; - } - } - } -} diff --git a/Assets/Plugins/MessagePack/Internal/ThreadsafeTypeKeyHashTable.cs.meta b/Assets/Plugins/MessagePack/Internal/ThreadsafeTypeKeyHashTable.cs.meta deleted file mode 100644 index 7b29cc78f..000000000 --- a/Assets/Plugins/MessagePack/Internal/ThreadsafeTypeKeyHashTable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 517dd6b1707013015b06ebfbeeea1f2c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Internal/TinyJsonReader.cs b/Assets/Plugins/MessagePack/Internal/TinyJsonReader.cs deleted file mode 100644 index 87263061a..000000000 --- a/Assets/Plugins/MessagePack/Internal/TinyJsonReader.cs +++ /dev/null @@ -1,430 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Globalization; -using System.IO; -using System.Text; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack -{ - /* simple, tiny JSON reader for MessagePackSerializer.FromJson. - * this is simple, compact and enough fast but not optimized extremely. */ - - internal enum TinyJsonToken - { - None, - StartObject, // { - EndObject, // } - StartArray, // [ - EndArray, // ] - Number, // -0~9 - String, // "___" - True, // true - False, // false - Null, // null - } - - internal enum ValueType : byte - { - Null, - True, - False, - Double, - Long, - ULong, - Decimal, - String, - } - - public class TinyJsonException : MessagePackSerializationException - { - public TinyJsonException(string message) - : base(message) - { - } - } - - internal class TinyJsonReader : IDisposable - { - private readonly TextReader reader; - private readonly bool disposeInnerReader; - private StringBuilder reusableBuilder; - - public TinyJsonToken TokenType { get; private set; } - - public ValueType ValueType { get; private set; } - - public double DoubleValue { get; private set; } - - public long LongValue { get; private set; } - - public ulong ULongValue { get; private set; } - - public decimal DecimalValue { get; private set; } - - public string StringValue { get; private set; } - - public TinyJsonReader(TextReader reader, bool disposeInnerReader = true) - { - this.reader = reader; - this.disposeInnerReader = disposeInnerReader; - } - - public bool Read() - { - this.ReadNextToken(); - this.ReadValue(); - return this.TokenType != TinyJsonToken.None; - } - - public void Dispose() - { - if (this.reader != null && this.disposeInnerReader) - { - this.reader.Dispose(); - } - - this.TokenType = TinyJsonToken.None; - this.ValueType = ValueType.Null; - } - - private void SkipWhiteSpace() - { - var c = this.reader.Peek(); - while (c != -1 && Char.IsWhiteSpace((char)c)) - { - this.reader.Read(); - c = this.reader.Peek(); - } - } - - private char ReadChar() - { - return (char)this.reader.Read(); - } - - private static bool IsWordBreak(char c) - { - switch (c) - { - case ' ': - case '{': - case '}': - case '[': - case ']': - case ',': - case ':': - case '\"': - return true; - default: - return false; - } - } - - private void ReadNextToken() - { - this.SkipWhiteSpace(); - - var intChar = this.reader.Peek(); - if (intChar == -1) - { - this.TokenType = TinyJsonToken.None; - return; - } - - var c = (char)intChar; - switch (c) - { - case '{': - this.TokenType = TinyJsonToken.StartObject; - return; - case '}': - this.TokenType = TinyJsonToken.EndObject; - return; - case '[': - this.TokenType = TinyJsonToken.StartArray; - return; - case ']': - this.TokenType = TinyJsonToken.EndArray; - return; - case '"': - this.TokenType = TinyJsonToken.String; - return; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - case '-': - this.TokenType = TinyJsonToken.Number; - return; - case 't': - this.TokenType = TinyJsonToken.True; - return; - case 'f': - this.TokenType = TinyJsonToken.False; - return; - case 'n': - this.TokenType = TinyJsonToken.Null; - return; - case ',': - case ':': - this.reader.Read(); - this.ReadNextToken(); - return; - default: - throw new TinyJsonException("Invalid String:" + c); - } - } - - private void ReadValue() - { - this.ValueType = ValueType.Null; - - switch (this.TokenType) - { - case TinyJsonToken.None: - break; - case TinyJsonToken.StartObject: - case TinyJsonToken.EndObject: - case TinyJsonToken.StartArray: - case TinyJsonToken.EndArray: - this.reader.Read(); - break; - case TinyJsonToken.Number: - this.ReadNumber(); - break; - case TinyJsonToken.String: - this.ReadString(); - break; - case TinyJsonToken.True: - if (this.ReadChar() != 't') - { - throw new TinyJsonException("Invalid Token"); - } - - if (this.ReadChar() != 'r') - { - throw new TinyJsonException("Invalid Token"); - } - - if (this.ReadChar() != 'u') - { - throw new TinyJsonException("Invalid Token"); - } - - if (this.ReadChar() != 'e') - { - throw new TinyJsonException("Invalid Token"); - } - - this.ValueType = ValueType.True; - break; - case TinyJsonToken.False: - if (this.ReadChar() != 'f') - { - throw new TinyJsonException("Invalid Token"); - } - - if (this.ReadChar() != 'a') - { - throw new TinyJsonException("Invalid Token"); - } - - if (this.ReadChar() != 'l') - { - throw new TinyJsonException("Invalid Token"); - } - - if (this.ReadChar() != 's') - { - throw new TinyJsonException("Invalid Token"); - } - - if (this.ReadChar() != 'e') - { - throw new TinyJsonException("Invalid Token"); - } - - this.ValueType = ValueType.False; - break; - case TinyJsonToken.Null: - if (this.ReadChar() != 'n') - { - throw new TinyJsonException("Invalid Token"); - } - - if (this.ReadChar() != 'u') - { - throw new TinyJsonException("Invalid Token"); - } - - if (this.ReadChar() != 'l') - { - throw new TinyJsonException("Invalid Token"); - } - - if (this.ReadChar() != 'l') - { - throw new TinyJsonException("Invalid Token"); - } - - this.ValueType = ValueType.Null; - break; - default: - throw new MessagePackSerializationException("InvalidTokenState:" + this.TokenType); - } - } - - private void ReadNumber() - { - StringBuilder numberWord; - if (this.reusableBuilder == null) - { - this.reusableBuilder = new StringBuilder(); - numberWord = this.reusableBuilder; - } - else - { - numberWord = this.reusableBuilder; - numberWord.Length = 0; // Clear - } - - var isDouble = false; - var intChar = this.reader.Peek(); - while (intChar != -1 && !IsWordBreak((char)intChar)) - { - var c = this.ReadChar(); - numberWord.Append(c); - if (c == '.' || c == 'e' || c == 'E') - { - isDouble = true; - } - - intChar = this.reader.Peek(); - } - - var number = numberWord.ToString(); - if (isDouble) - { - double parsedDouble; - Double.TryParse(number, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowExponent, System.Globalization.CultureInfo.InvariantCulture, out parsedDouble); - this.ValueType = ValueType.Double; - this.DoubleValue = parsedDouble; - } - else - { - long parsedInt; - if (Int64.TryParse(number, NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out parsedInt)) - { - this.ValueType = ValueType.Long; - this.LongValue = parsedInt; - return; - } - - ulong parsedULong; - if (ulong.TryParse(number, NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out parsedULong)) - { - this.ValueType = ValueType.ULong; - this.ULongValue = parsedULong; - return; - } - - Decimal parsedDecimal; - if (decimal.TryParse(number, NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out parsedDecimal)) - { - this.ValueType = ValueType.Decimal; - this.DecimalValue = parsedDecimal; - return; - } - } - } - - private void ReadString() - { - this.reader.Read(); // skip ["] - - StringBuilder sb; - if (this.reusableBuilder == null) - { - this.reusableBuilder = new StringBuilder(); - sb = this.reusableBuilder; - } - else - { - sb = this.reusableBuilder; - sb.Length = 0; // Clear - } - - while (true) - { - if (this.reader.Peek() == -1) - { - throw new TinyJsonException("Invalid Json String"); - } - - var c = this.ReadChar(); - switch (c) - { - case '"': // endtoken - goto END; - case '\\': // escape character - if (this.reader.Peek() == -1) - { - throw new TinyJsonException("Invalid Json String"); - } - - c = this.ReadChar(); - switch (c) - { - case '"': - case '\\': - case '/': - sb.Append(c); - break; - case 'b': - sb.Append('\b'); - break; - case 'f': - sb.Append('\f'); - break; - case 'n': - sb.Append('\n'); - break; - case 'r': - sb.Append('\r'); - break; - case 't': - sb.Append('\t'); - break; - case 'u': - var hex = new char[4]; - hex[0] = this.ReadChar(); - hex[1] = this.ReadChar(); - hex[2] = this.ReadChar(); - hex[3] = this.ReadChar(); - sb.Append((char)Convert.ToInt32(new string(hex), 16)); - break; - } - - break; - default: // string - sb.Append(c); - break; - } - } - -END: - this.ValueType = ValueType.String; - this.StringValue = sb.ToString(); - } - } -} diff --git a/Assets/Plugins/MessagePack/Internal/TinyJsonReader.cs.meta b/Assets/Plugins/MessagePack/Internal/TinyJsonReader.cs.meta deleted file mode 100644 index 60e432a72..000000000 --- a/Assets/Plugins/MessagePack/Internal/TinyJsonReader.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: adc1157b80c30cf2d8845336b9c1cfc2 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Internal/UnsafeMemory.Low.cs b/Assets/Plugins/MessagePack/Internal/UnsafeMemory.Low.cs deleted file mode 100644 index 39e1f5c16..000000000 --- a/Assets/Plugins/MessagePack/Internal/UnsafeMemory.Low.cs +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if !UNITY_2018_3_OR_NEWER - -using System; -using System.Runtime.CompilerServices; - -namespace MessagePack.Internal -{ - /* for string key property name write optimization. */ - - public static class UnsafeMemory - { - public static readonly bool Is32Bit = IntPtr.Size == 4; - } - - public static partial class UnsafeMemory32 - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw1(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(byte*)pDst = *(byte*)pSrc; - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw2(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(short*)pDst = *(short*)pSrc; - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw3(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(byte*)pDst = *(byte*)pSrc; - *(short*)(pDst + 1) = *(short*)(pSrc + 1); - } - - writer.Advance(src.Length); - } - } - - public static partial class UnsafeMemory64 - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw1(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(byte*)pDst = *(byte*)pSrc; - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw2(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(short*)pDst = *(short*)pSrc; - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw3(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(byte*)pDst = *(byte*)pSrc; - *(short*)(pDst + 1) = *(short*)(pSrc + 1); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw4(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw5(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 1) = *(int*)(pSrc + 1); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw6(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 2) = *(int*)(pSrc + 2); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw7(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 3) = *(int*)(pSrc + 3); - } - - writer.Advance(src.Length); - } - } -} - -#endif diff --git a/Assets/Plugins/MessagePack/Internal/UnsafeMemory.Low.cs.meta b/Assets/Plugins/MessagePack/Internal/UnsafeMemory.Low.cs.meta deleted file mode 100644 index 0d94cbdbe..000000000 --- a/Assets/Plugins/MessagePack/Internal/UnsafeMemory.Low.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2126473180c3a7d3a8860c4fd8aa4183 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/LZ4.meta b/Assets/Plugins/MessagePack/LZ4.meta deleted file mode 100644 index 655ac4352..000000000 --- a/Assets/Plugins/MessagePack/LZ4.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: c633d9a494df48a45b82671c008a72a1 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Helper.cs b/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Helper.cs deleted file mode 100644 index 5c2004331..000000000 --- a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Helper.cs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; - -namespace MessagePack.LZ4 -{ - internal partial class LZ4Codec - { -#if UNITY_2018_3_OR_NEWER - - // use 'Safe' code for Unity because in IL2CPP gots strange behaviour. - - public static int Encode(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int outputLength) - { - if (IntPtr.Size == 4) - { - return LZ4Codec.Encode32Safe(input, inputOffset, inputLength, output, outputOffset, outputLength); - } - else - { - return LZ4Codec.Encode64Safe(input, inputOffset, inputLength, output, outputOffset, outputLength); - } - } - - public static int Decode(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int outputLength) - { - if (IntPtr.Size == 4) - { - return LZ4Codec.Decode32Safe(input, inputOffset, inputLength, output, outputOffset, outputLength); - } - else - { - return LZ4Codec.Decode64Safe(input, inputOffset, inputLength, output, outputOffset, outputLength); - } - } - -#endif - - internal static class HashTablePool - { - [ThreadStatic] - private static ushort[] ushortPool; - - [ThreadStatic] - private static uint[] uintPool; - - [ThreadStatic] - private static int[] intPool; - - public static ushort[] GetUShortHashTablePool() - { - if (ushortPool == null) - { - ushortPool = new ushort[HASH64K_TABLESIZE]; - } - else - { - Array.Clear(ushortPool, 0, ushortPool.Length); - } - - return ushortPool; - } - - public static uint[] GetUIntHashTablePool() - { - if (uintPool == null) - { - uintPool = new uint[HASH_TABLESIZE]; - } - else - { - Array.Clear(uintPool, 0, uintPool.Length); - } - - return uintPool; - } - - public static int[] GetIntHashTablePool() - { - if (intPool == null) - { - intPool = new int[HASH_TABLESIZE]; - } - else - { - Array.Clear(intPool, 0, intPool.Length); - } - - return intPool; - } - } - } -} diff --git a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Helper.cs.meta b/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Helper.cs.meta deleted file mode 100644 index 84913cb4f..000000000 --- a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Helper.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f33bc878911a8855d8df41dd514c5a42 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Safe.cs b/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Safe.cs deleted file mode 100644 index 18e423a7d..000000000 --- a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Safe.cs +++ /dev/null @@ -1,467 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if UNITY_2018_3_OR_NEWER - -#region license - -/* -Copyright (c) 2013, Milosz Krajewski -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided -that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this list of conditions - and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this list of conditions - and the following disclaimer in the documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#endregion - -using System; -using System.Diagnostics; - -namespace MessagePack.LZ4 -{ - /// Safe LZ4 codec. - internal partial class LZ4Codec - { -#region Helper - - [Conditional("DEBUG")] - private static void Assert(bool condition, string errorMessage) - { - if (!condition) - { - throw new ArgumentException(errorMessage); - } - - Debug.Assert(condition, errorMessage); - } - -#endregion - -#region Byte manipulation - - internal static void Poke2(byte[] buffer, int offset, ushort value) - { - buffer[offset] = (byte)value; - buffer[offset + 1] = (byte)(value >> 8); - } - - internal static ushort Peek2(byte[] buffer, int offset) - { - // NOTE: It's faster than BitConverter.ToUInt16 (suprised? me too) - return (ushort)(((uint)buffer[offset]) | ((uint)buffer[offset + 1] << 8)); - } - - internal static uint Peek4(byte[] buffer, int offset) - { - // NOTE: It's faster than BitConverter.ToUInt32 (suprised? me too) - return - ((uint)buffer[offset]) | - ((uint)buffer[offset + 1] << 8) | - ((uint)buffer[offset + 2] << 16) | - ((uint)buffer[offset + 3] << 24); - } - - private static uint Xor4(byte[] buffer, int offset1, int offset2) - { - // return Peek4(buffer, offset1) ^ Peek4(buffer, offset2); - var value1 = - ((uint)buffer[offset1]) | - ((uint)buffer[offset1 + 1] << 8) | - ((uint)buffer[offset1 + 2] << 16) | - ((uint)buffer[offset1 + 3] << 24); - var value2 = - ((uint)buffer[offset2]) | - ((uint)buffer[offset2 + 1] << 8) | - ((uint)buffer[offset2 + 2] << 16) | - ((uint)buffer[offset2 + 3] << 24); - return value1 ^ value2; - } - - private static ulong Xor8(byte[] buffer, int offset1, int offset2) - { - // return Peek8(buffer, offset1) ^ Peek8(buffer, offset2); - var value1 = - ((ulong)buffer[offset1]) | - ((ulong)buffer[offset1 + 1] << 8) | - ((ulong)buffer[offset1 + 2] << 16) | - ((ulong)buffer[offset1 + 3] << 24) | - ((ulong)buffer[offset1 + 4] << 32) | - ((ulong)buffer[offset1 + 5] << 40) | - ((ulong)buffer[offset1 + 6] << 48) | - ((ulong)buffer[offset1 + 7] << 56); - var value2 = - ((ulong)buffer[offset2]) | - ((ulong)buffer[offset2 + 1] << 8) | - ((ulong)buffer[offset2 + 2] << 16) | - ((ulong)buffer[offset2 + 3] << 24) | - ((ulong)buffer[offset2 + 4] << 32) | - ((ulong)buffer[offset2 + 5] << 40) | - ((ulong)buffer[offset2 + 6] << 48) | - ((ulong)buffer[offset2 + 7] << 56); - return value1 ^ value2; - } - - private static bool Equal2(byte[] buffer, int offset1, int offset2) - { - // return Peek2(buffer, offset1) == Peek2(buffer, offset2); - if (buffer[offset1] != buffer[offset2]) - { - return false; - } - - return buffer[offset1 + 1] == buffer[offset2 + 1]; - } - - private static bool Equal4(byte[] buffer, int offset1, int offset2) - { - // return Peek4(buffer, offset1) == Peek4(buffer, offset2); - if (buffer[offset1] != buffer[offset2]) - { - return false; - } - - if (buffer[offset1 + 1] != buffer[offset2 + 1]) - { - return false; - } - - if (buffer[offset1 + 2] != buffer[offset2 + 2]) - { - return false; - } - - return buffer[offset1 + 3] == buffer[offset2 + 3]; - } - -#endregion - -#region Byte block copy - - private static void Copy4(byte[] buf, int src, int dst) - { - Assert(dst > src, "Copying backwards is not implemented"); - buf[dst + 3] = buf[src + 3]; - buf[dst + 2] = buf[src + 2]; - buf[dst + 1] = buf[src + 1]; - buf[dst] = buf[src]; - } - - private static void Copy8(byte[] buf, int src, int dst) - { - Assert(dst > src, "Copying backwards is not implemented"); - buf[dst + 7] = buf[src + 7]; - buf[dst + 6] = buf[src + 6]; - buf[dst + 5] = buf[src + 5]; - buf[dst + 4] = buf[src + 4]; - buf[dst + 3] = buf[src + 3]; - buf[dst + 2] = buf[src + 2]; - buf[dst + 1] = buf[src + 1]; - buf[dst] = buf[src]; - } - - private static void BlockCopy(byte[] src, int src_0, byte[] dst, int dst_0, int len) - { - Assert(src != dst, "BlockCopy does not handle copying to the same buffer"); - - if (len >= BLOCK_COPY_LIMIT) - { - Buffer.BlockCopy(src, src_0, dst, dst_0, len); - } - else - { - while (len >= 8) - { - dst[dst_0] = src[src_0]; - dst[dst_0 + 1] = src[src_0 + 1]; - dst[dst_0 + 2] = src[src_0 + 2]; - dst[dst_0 + 3] = src[src_0 + 3]; - dst[dst_0 + 4] = src[src_0 + 4]; - dst[dst_0 + 5] = src[src_0 + 5]; - dst[dst_0 + 6] = src[src_0 + 6]; - dst[dst_0 + 7] = src[src_0 + 7]; - len -= 8; - src_0 += 8; - dst_0 += 8; - } - - while (len >= 4) - { - dst[dst_0] = src[src_0]; - dst[dst_0 + 1] = src[src_0 + 1]; - dst[dst_0 + 2] = src[src_0 + 2]; - dst[dst_0 + 3] = src[src_0 + 3]; - len -= 4; - src_0 += 4; - dst_0 += 4; - } - - while (len-- > 0) - { - dst[dst_0++] = src[src_0++]; - } - } - } - - private static int WildCopy(byte[] src, int src_0, byte[] dst, int dst_0, int dst_end) - { - var len = dst_end - dst_0; - - Assert(src != dst, "BlockCopy does not handle copying to the same buffer"); - Assert(len > 0, "Length have to be greater than 0"); - - if (len >= BLOCK_COPY_LIMIT) - { - Buffer.BlockCopy(src, src_0, dst, dst_0, len); - } - else - { - // apparently (tested) this is an overkill - // it seems to be faster without this 8-byte loop - ////while (len >= 8) - ////{ - //// dst[dst_0] = src[src_0]; - //// dst[dst_0 + 1] = src[src_0 + 1]; - //// dst[dst_0 + 2] = src[src_0 + 2]; - //// dst[dst_0 + 3] = src[src_0 + 3]; - //// dst[dst_0 + 4] = src[src_0 + 4]; - //// dst[dst_0 + 5] = src[src_0 + 5]; - //// dst[dst_0 + 6] = src[src_0 + 6]; - //// dst[dst_0 + 7] = src[src_0 + 7]; - //// len -= 8; src_0 += 8; dst_0 += 8; - ////} - - while (len >= 4) - { - dst[dst_0] = src[src_0]; - dst[dst_0 + 1] = src[src_0 + 1]; - dst[dst_0 + 2] = src[src_0 + 2]; - dst[dst_0 + 3] = src[src_0 + 3]; - len -= 4; - src_0 += 4; - dst_0 += 4; - } - - while (len-- > 0) - { - dst[dst_0++] = src[src_0++]; - } - } - - return len; - } - - private static int SecureCopy(byte[] buffer, int src, int dst, int dst_end) - { - var diff = dst - src; - var length = dst_end - dst; - var len = length; - - Assert(diff >= 4, "Target must be at least 4 bytes further than source"); - Assert(BLOCK_COPY_LIMIT > 4, "This method requires BLOCK_COPY_LIMIT > 4"); - Assert(len > 0, "Length have to be greater than 0"); - - if (diff >= BLOCK_COPY_LIMIT) - { - if (diff >= length) - { - Buffer.BlockCopy(buffer, src, buffer, dst, length); - return length; // done - } - - do - { - Buffer.BlockCopy(buffer, src, buffer, dst, diff); - src += diff; - dst += diff; - len -= diff; - } - while (len >= diff); - } - - // apparently (tested) this is an overkill - // it seems to be faster without this 8-byte loop - ////while (len >= 8) - ////{ - //// buffer[dst] = buffer[src]; - //// buffer[dst + 1] = buffer[src + 1]; - //// buffer[dst + 2] = buffer[src + 2]; - //// buffer[dst + 3] = buffer[src + 3]; - //// buffer[dst + 4] = buffer[src + 4]; - //// buffer[dst + 5] = buffer[src + 5]; - //// buffer[dst + 6] = buffer[src + 6]; - //// buffer[dst + 7] = buffer[src + 7]; - //// dst += 8; src += 8; len -= 8; - ////} - - while (len >= 4) - { - buffer[dst] = buffer[src]; - buffer[dst + 1] = buffer[src + 1]; - buffer[dst + 2] = buffer[src + 2]; - buffer[dst + 3] = buffer[src + 3]; - dst += 4; - src += 4; - len -= 4; - } - - while (len-- > 0) - { - buffer[dst++] = buffer[src++]; - } - - return length; // done - } - -#endregion - - /// Encodes the specified input. - /// The input. - /// The input offset. - /// Length of the input. - /// The output. - /// The output offset. - /// Length of the output. - /// Number of bytes written. - public static int Encode32Safe( - byte[] input, - int inputOffset, - int inputLength, - byte[] output, - int outputOffset, - int outputLength) - { - CheckArguments(input, inputOffset, inputLength, output, outputOffset, outputLength); - if (outputLength == 0) - { - return 0; - } - - if (inputLength < LZ4_64KLIMIT) - { - var hashTable = HashTablePool.GetUShortHashTablePool(); - return LZ4_compress64kCtx_safe32(hashTable, input, output, inputOffset, outputOffset, inputLength, outputLength); - } - else - { - var hashTable = HashTablePool.GetIntHashTablePool(); - return LZ4_compressCtx_safe32(hashTable, input, output, inputOffset, outputOffset, inputLength, outputLength); - } - } - - /// Encodes the specified input. - /// The input. - /// The input offset. - /// Length of the input. - /// The output. - /// The output offset. - /// Length of the output. - /// Number of bytes written. - public static int Encode64Safe( - byte[] input, - int inputOffset, - int inputLength, - byte[] output, - int outputOffset, - int outputLength) - { - CheckArguments(input, inputOffset, inputLength, output, outputOffset, outputLength); - if (outputLength == 0) - { - return 0; - } - - if (inputLength < LZ4_64KLIMIT) - { - var hashTable = HashTablePool.GetUShortHashTablePool(); - return LZ4_compress64kCtx_safe64(hashTable, input, output, inputOffset, outputOffset, inputLength, outputLength); - } - else - { - var hashTable = HashTablePool.GetIntHashTablePool(); - return LZ4_compressCtx_safe64(hashTable, input, output, inputOffset, outputOffset, inputLength, outputLength); - } - } - - /// Decodes the specified input. - /// The input. - /// The input offset. - /// Length of the input. - /// The output. - /// The output offset. - /// Length of the output. - /// Number of bytes written. - public static int Decode32Safe( - byte[] input, - int inputOffset, - int inputLength, - byte[] output, - int outputOffset, - int outputLength) - { - CheckArguments(input, inputOffset, inputLength, output, outputOffset, outputLength); - - if (outputLength == 0) - { - return 0; - } - - var length = LZ4_uncompress_safe32(input, output, inputOffset, outputOffset, outputLength); - if (length != inputLength) - { - throw new MessagePackSerializationException("LZ4 block is corrupted, or invalid length has been given."); - } - - return outputLength; - } - - /// Decodes the specified input. - /// The input. - /// The input offset. - /// Length of the input. - /// The output. - /// The output offset. - /// Length of the output. - /// Number of bytes written. - public static int Decode64Safe( - byte[] input, - int inputOffset, - int inputLength, - byte[] output, - int outputOffset, - int outputLength) - { - CheckArguments(input, inputOffset, inputLength, output, outputOffset, outputLength); - - if (outputLength == 0) - { - return 0; - } - - var length = LZ4_uncompress_safe64(input, output, inputOffset, outputOffset, outputLength); - if (length != inputLength) - { - throw new MessagePackSerializationException("LZ4 block is corrupted, or invalid length has been given."); - } - - return outputLength; - } - } -} - -#endif diff --git a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Safe.cs.meta b/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Safe.cs.meta deleted file mode 100644 index 8db917c6c..000000000 --- a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Safe.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 5fe9256cf4f62c6df8c144caef0ebc6a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Safe32.Dirty.cs b/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Safe32.Dirty.cs deleted file mode 100644 index 054721368..000000000 --- a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Safe32.Dirty.cs +++ /dev/null @@ -1,753 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if UNITY_2018_3_OR_NEWER - -#region LZ4 original - -/* - LZ4 - Fast LZ compression algorithm - Copyright (C) 2011-2012, Yann Collet. - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html - - LZ4 source repository : http://code.google.com/p/lz4/ -*/ - -#endregion - -#region LZ4 port - -/* -Copyright (c) 2013, Milosz Krajewski -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided -that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this list of conditions - and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this list of conditions - and the following disclaimer in the documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#endregion - -#pragma warning disable SA1312 // Variable names should begin with lower-case letter - -namespace MessagePack.LZ4 -{ - internal partial class LZ4Codec - { -#region LZ4_compressCtx - - private static int LZ4_compressCtx_safe32( - int[] hash_table, - byte[] src, - byte[] dst, - int src_0, - int dst_0, - int src_len, - int dst_maxlen) - { - unchecked - { - var debruijn32 = DEBRUIJN_TABLE_32; - int _i; - - // ---- preprocessed source start here ---- - // r93 - var src_p = src_0; - var src_base = src_0; - var src_anchor = src_p; - var src_end = src_p + src_len; - var src_mflimit = src_end - MFLIMIT; - - var dst_p = dst_0; - var dst_end = dst_p + dst_maxlen; - - var src_LASTLITERALS = src_end - LASTLITERALS; - var src_LASTLITERALS_1 = src_LASTLITERALS - 1; - - var src_LASTLITERALS_STEPSIZE_1 = src_LASTLITERALS - (STEPSIZE_32 - 1); - var dst_LASTLITERALS_1 = dst_end - (1 + LASTLITERALS); - var dst_LASTLITERALS_3 = dst_end - (2 + 1 + LASTLITERALS); - - int length; - - uint h, h_fwd; - - // Init - if (src_len < MINLENGTH) - { - goto _last_literals; - } - - // First Byte - hash_table[(Peek4(src, src_p) * 2654435761u) >> HASH_ADJUST] = src_p - src_base; - src_p++; - h_fwd = (Peek4(src, src_p) * 2654435761u) >> HASH_ADJUST; - - // Main Loop - while (true) - { - var findMatchAttempts = (1 << SKIPSTRENGTH) + 3; - var src_p_fwd = src_p; - int src_ref; - int dst_token; - - // Find a match - do - { - h = h_fwd; - var step = findMatchAttempts++ >> SKIPSTRENGTH; - src_p = src_p_fwd; - src_p_fwd = src_p + step; - - if (src_p_fwd > src_mflimit) - { - goto _last_literals; - } - - h_fwd = (Peek4(src, src_p_fwd) * 2654435761u) >> HASH_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = src_p - src_base; - } - while ((src_ref < src_p - MAX_DISTANCE) || (!Equal4(src, src_ref, src_p))); - - // Catch up - while ((src_p > src_anchor) && (src_ref > src_0) && (src[src_p - 1] == src[src_ref - 1])) - { - src_p--; - src_ref--; - } - - // Encode Literal length - length = src_p - src_anchor; - dst_token = dst_p++; - - if (dst_p + length + (length >> 8) > dst_LASTLITERALS_3) - { - return 0; // Check output limit - } - - if (length >= RUN_MASK) - { - var len = length - RUN_MASK; - dst[dst_token] = RUN_MASK << ML_BITS; - if (len > 254) - { - do - { - dst[dst_p++] = 255; - len -= 255; - } - while (len > 254); - dst[dst_p++] = (byte)len; - BlockCopy(src, src_anchor, dst, dst_p, length); - dst_p += length; - goto _next_match; - } - else - { - dst[dst_p++] = (byte)len; - } - } - else - { - dst[dst_token] = (byte)(length << ML_BITS); - } - - // Copy Literals - if (length > 0) - { - _i = dst_p + length; - WildCopy(src, src_anchor, dst, dst_p, _i); - dst_p = _i; - } - -_next_match: - -// Encode Offset - Poke2(dst, dst_p, (ushort)(src_p - src_ref)); - dst_p += 2; - - // Start Counting - src_p += MINMATCH; - src_ref += MINMATCH; // MinMatch already verified - src_anchor = src_p; - - while (src_p < src_LASTLITERALS_STEPSIZE_1) - { - var diff = (int)Xor4(src, src_ref, src_p); - if (diff == 0) - { - src_p += STEPSIZE_32; - src_ref += STEPSIZE_32; - continue; - } - - src_p += debruijn32[((uint)(diff & -diff) * 0x077CB531u) >> 27]; - goto _endCount; - } - - if ((src_p < src_LASTLITERALS_1) && Equal2(src, src_ref, src_p)) - { - src_p += 2; - src_ref += 2; - } - - if ((src_p < src_LASTLITERALS) && (src[src_ref] == src[src_p])) - { - src_p++; - } - -_endCount: - -// Encode MatchLength - length = src_p - src_anchor; - - if (dst_p + (length >> 8) > dst_LASTLITERALS_1) - { - return 0; // Check output limit - } - - if (length >= ML_MASK) - { - dst[dst_token] += ML_MASK; - length -= ML_MASK; - for (; length > 509; length -= 510) - { - dst[dst_p++] = 255; - dst[dst_p++] = 255; - } - - if (length > 254) - { - length -= 255; - dst[dst_p++] = 255; - } - - dst[dst_p++] = (byte)length; - } - else - { - dst[dst_token] += (byte)length; - } - - // Test end of chunk - if (src_p > src_mflimit) - { - src_anchor = src_p; - break; - } - - // Fill table - hash_table[(Peek4(src, src_p - 2) * 2654435761u) >> HASH_ADJUST] = src_p - 2 - src_base; - - // Test next position - h = (Peek4(src, src_p) * 2654435761u) >> HASH_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = src_p - src_base; - - if ((src_ref > src_p - (MAX_DISTANCE + 1)) && Equal4(src, src_ref, src_p)) - { - dst_token = dst_p++; - dst[dst_token] = 0; - goto _next_match; - } - - // Prepare next loop - src_anchor = src_p++; - h_fwd = (Peek4(src, src_p) * 2654435761u) >> HASH_ADJUST; - } - -_last_literals: - -// Encode Last Literals - { - var lastRun = src_end - src_anchor; - - if (dst_p + lastRun + 1 + ((lastRun + 255 - RUN_MASK) / 255) > dst_end) - { - return 0; - } - - if (lastRun >= RUN_MASK) - { - dst[dst_p++] = RUN_MASK << ML_BITS; - lastRun -= RUN_MASK; - for (; lastRun > 254; lastRun -= 255) - { - dst[dst_p++] = 255; - } - - dst[dst_p++] = (byte)lastRun; - } - else - { - dst[dst_p++] = (byte)(lastRun << ML_BITS); - } - - BlockCopy(src, src_anchor, dst, dst_p, src_end - src_anchor); - dst_p += src_end - src_anchor; - } - - // End - return dst_p - dst_0; - } - } - -#endregion - -#region LZ4_compress64kCtx - - private static int LZ4_compress64kCtx_safe32( - ushort[] hash_table, - byte[] src, - byte[] dst, - int src_0, - int dst_0, - int src_len, - int dst_maxlen) - { - unchecked - { - var debruijn32 = DEBRUIJN_TABLE_32; - int _i; - - // ---- preprocessed source start here ---- - // r93 - var src_p = src_0; - var src_anchor = src_p; - var src_base = src_p; - var src_end = src_p + src_len; - var src_mflimit = src_end - MFLIMIT; - - var dst_p = dst_0; - var dst_end = dst_p + dst_maxlen; - - var src_LASTLITERALS = src_end - LASTLITERALS; - var src_LASTLITERALS_1 = src_LASTLITERALS - 1; - - var src_LASTLITERALS_STEPSIZE_1 = src_LASTLITERALS - (STEPSIZE_32 - 1); - var dst_LASTLITERALS_1 = dst_end - (1 + LASTLITERALS); - var dst_LASTLITERALS_3 = dst_end - (2 + 1 + LASTLITERALS); - - int len, length; - - uint h, h_fwd; - - // Init - if (src_len < MINLENGTH) - { - goto _last_literals; - } - - // First Byte - src_p++; - h_fwd = (Peek4(src, src_p) * 2654435761u) >> HASH64K_ADJUST; - - // Main Loop - while (true) - { - var findMatchAttempts = (1 << SKIPSTRENGTH) + 3; - var src_p_fwd = src_p; - int src_ref; - int dst_token; - - // Find a match - do - { - h = h_fwd; - var step = findMatchAttempts++ >> SKIPSTRENGTH; - src_p = src_p_fwd; - src_p_fwd = src_p + step; - - if (src_p_fwd > src_mflimit) - { - goto _last_literals; - } - - h_fwd = (Peek4(src, src_p_fwd) * 2654435761u) >> HASH64K_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = (ushort)(src_p - src_base); - } - while (!Equal4(src, src_ref, src_p)); - - // Catch up - while ((src_p > src_anchor) && (src_ref > src_0) && (src[src_p - 1] == src[src_ref - 1])) - { - src_p--; - src_ref--; - } - - // Encode Literal length - length = src_p - src_anchor; - dst_token = dst_p++; - - if (dst_p + length + (length >> 8) > dst_LASTLITERALS_3) - { - return 0; // Check output limit - } - - if (length >= RUN_MASK) - { - len = length - RUN_MASK; - dst[dst_token] = RUN_MASK << ML_BITS; - if (len > 254) - { - do - { - dst[dst_p++] = 255; - len -= 255; - } - while (len > 254); - dst[dst_p++] = (byte)len; - BlockCopy(src, src_anchor, dst, dst_p, length); - dst_p += length; - goto _next_match; - } - else - { - dst[dst_p++] = (byte)len; - } - } - else - { - dst[dst_token] = (byte)(length << ML_BITS); - } - - // Copy Literals - if (length > 0) - { - _i = dst_p + length; - WildCopy(src, src_anchor, dst, dst_p, _i); - dst_p = _i; - } - -_next_match: - -// Encode Offset - Poke2(dst, dst_p, (ushort)(src_p - src_ref)); - dst_p += 2; - - // Start Counting - src_p += MINMATCH; - src_ref += MINMATCH; // MinMatch verified - src_anchor = src_p; - - while (src_p < src_LASTLITERALS_STEPSIZE_1) - { - var diff = (int)Xor4(src, src_ref, src_p); - if (diff == 0) - { - src_p += STEPSIZE_32; - src_ref += STEPSIZE_32; - continue; - } - - src_p += debruijn32[((uint)(diff & -diff) * 0x077CB531u) >> 27]; - goto _endCount; - } - - if ((src_p < src_LASTLITERALS_1) && Equal2(src, src_ref, src_p)) - { - src_p += 2; - src_ref += 2; - } - - if ((src_p < src_LASTLITERALS) && (src[src_ref] == src[src_p])) - { - src_p++; - } - -_endCount: - -// Encode MatchLength - len = src_p - src_anchor; - - if (dst_p + (len >> 8) > dst_LASTLITERALS_1) - { - return 0; // Check output limit - } - - if (len >= ML_MASK) - { - dst[dst_token] += ML_MASK; - len -= ML_MASK; - for (; len > 509; len -= 510) - { - dst[dst_p++] = 255; - dst[dst_p++] = 255; - } - - if (len > 254) - { - len -= 255; - dst[dst_p++] = 255; - } - - dst[dst_p++] = (byte)len; - } - else - { - dst[dst_token] += (byte)len; - } - - // Test end of chunk - if (src_p > src_mflimit) - { - src_anchor = src_p; - break; - } - - // Fill table - hash_table[(Peek4(src, src_p - 2) * 2654435761u) >> HASH64K_ADJUST] = (ushort)(src_p - 2 - src_base); - - // Test next position - h = (Peek4(src, src_p) * 2654435761u) >> HASH64K_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = (ushort)(src_p - src_base); - - if (Equal4(src, src_ref, src_p)) - { - dst_token = dst_p++; - dst[dst_token] = 0; - goto _next_match; - } - - // Prepare next loop - src_anchor = src_p++; - h_fwd = (Peek4(src, src_p) * 2654435761u) >> HASH64K_ADJUST; - } - -_last_literals: - -// Encode Last Literals - var lastRun = src_end - src_anchor; - if (dst_p + lastRun + 1 + ((lastRun - RUN_MASK + 255) / 255) > dst_end) - { - return 0; - } - - if (lastRun >= RUN_MASK) - { - dst[dst_p++] = RUN_MASK << ML_BITS; - lastRun -= RUN_MASK; - for (; lastRun > 254; lastRun -= 255) - { - dst[dst_p++] = 255; - } - - dst[dst_p++] = (byte)lastRun; - } - else - { - dst[dst_p++] = (byte)(lastRun << ML_BITS); - } - - BlockCopy(src, src_anchor, dst, dst_p, src_end - src_anchor); - dst_p += src_end - src_anchor; - - // End - return dst_p - dst_0; - } - } - -#endregion - -#region LZ4_uncompress - - private static int LZ4_uncompress_safe32( - byte[] src, - byte[] dst, - int src_0, - int dst_0, - int dst_len) - { - unchecked - { - var dec32table = DECODER_TABLE_32; - int _i; - - // ---- preprocessed source start here ---- - // r93 - var src_p = src_0; - int dst_ref; - - var dst_p = dst_0; - var dst_end = dst_p + dst_len; - int dst_cpy; - - var dst_LASTLITERALS = dst_end - LASTLITERALS; - var dst_COPYLENGTH = dst_end - COPYLENGTH; - var dst_COPYLENGTH_STEPSIZE_4 = dst_end - COPYLENGTH - (STEPSIZE_32 - 4); - - byte token; - - // Main Loop - while (true) - { - int length; - - // get runlength - token = src[src_p++]; - if ((length = token >> ML_BITS) == RUN_MASK) - { - int len; - for (; (len = src[src_p++]) == 255; length += 255) - { - /* do nothing */ - } - - length += len; - } - - // copy literals - dst_cpy = dst_p + length; - - if (dst_cpy > dst_COPYLENGTH) - { - if (dst_cpy != dst_end) - { - goto _output_error; // Error : not enough place for another match (min 4) + 5 literals - } - - BlockCopy(src, src_p, dst, dst_p, length); - src_p += length; - break; // EOF - } - - if (dst_p < dst_cpy) - { - _i = WildCopy(src, src_p, dst, dst_p, dst_cpy); - src_p += _i; - dst_p += _i; - } - - src_p -= dst_p - dst_cpy; - dst_p = dst_cpy; - - // get offset - dst_ref = dst_cpy - Peek2(src, src_p); - src_p += 2; - if (dst_ref < dst_0) - { - goto _output_error; // Error : offset outside destination buffer - } - - // get matchlength - if ((length = token & ML_MASK) == ML_MASK) - { - for (; src[src_p] == 255; length += 255) - { - src_p++; - } - - length += src[src_p++]; - } - - // copy repeated sequence - if ((dst_p - dst_ref) < STEPSIZE_32) - { - const int dec64 = 0; - dst[dst_p + 0] = dst[dst_ref + 0]; - dst[dst_p + 1] = dst[dst_ref + 1]; - dst[dst_p + 2] = dst[dst_ref + 2]; - dst[dst_p + 3] = dst[dst_ref + 3]; - dst_p += 4; - dst_ref += 4; - dst_ref -= dec32table[dst_p - dst_ref]; - Copy4(dst, dst_ref, dst_p); - dst_p += STEPSIZE_32 - 4; - dst_ref -= dec64; - } - else - { - Copy4(dst, dst_ref, dst_p); - dst_p += 4; - dst_ref += 4; - } - - dst_cpy = dst_p + length - (STEPSIZE_32 - 4); - - if (dst_cpy > dst_COPYLENGTH_STEPSIZE_4) - { - if (dst_cpy > dst_LASTLITERALS) - { - goto _output_error; // Error : last 5 bytes must be literals - } - - if (dst_p < dst_COPYLENGTH) - { - _i = SecureCopy(dst, dst_ref, dst_p, dst_COPYLENGTH); - dst_ref += _i; - dst_p += _i; - } - - while (dst_p < dst_cpy) - { - dst[dst_p++] = dst[dst_ref++]; - } - - dst_p = dst_cpy; - continue; - } - - if (dst_p < dst_cpy) - { - SecureCopy(dst, dst_ref, dst_p, dst_cpy); - } - - dst_p = dst_cpy; // correction - } - - // end of decoding - return src_p - src_0; - -// write overflow error detected -_output_error: - return -(src_p - src_0); - } - } - -#endregion - } -} - -#endif diff --git a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Safe32.Dirty.cs.meta b/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Safe32.Dirty.cs.meta deleted file mode 100644 index 607e7f063..000000000 --- a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Safe32.Dirty.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4e76c34fb36d14138b0196dbb3bdc544 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Safe64.Dirty.cs b/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Safe64.Dirty.cs deleted file mode 100644 index f8215f842..000000000 --- a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Safe64.Dirty.cs +++ /dev/null @@ -1,774 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if UNITY_2018_3_OR_NEWER - -#region LZ4 original - -/* - LZ4 - Fast LZ compression algorithm - Copyright (C) 2011-2012, Yann Collet. - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html - - LZ4 source repository : http://code.google.com/p/lz4/ -*/ - -#endregion - -#region LZ4 port - -/* -Copyright (c) 2013, Milosz Krajewski -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided -that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this list of conditions - and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this list of conditions - and the following disclaimer in the documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#endregion - -#pragma warning disable SA1312 // Variable names should begin with lower-case letter - -namespace MessagePack.LZ4 -{ - internal partial class LZ4Codec - { -#region LZ4_compressCtx - - private static int LZ4_compressCtx_safe64( - int[] hash_table, - byte[] src, - byte[] dst, - int src_0, - int dst_0, - int src_len, - int dst_maxlen) - { - unchecked - { - var debruijn64 = DEBRUIJN_TABLE_64; - int _i; - - // ---- preprocessed source start here ---- - // r93 - var src_p = src_0; - var src_base = src_0; - var src_anchor = src_p; - var src_end = src_p + src_len; - var src_mflimit = src_end - MFLIMIT; - - var dst_p = dst_0; - var dst_end = dst_p + dst_maxlen; - - var src_LASTLITERALS = src_end - LASTLITERALS; - var src_LASTLITERALS_1 = src_LASTLITERALS - 1; - - var src_LASTLITERALS_3 = src_LASTLITERALS - 3; - - var src_LASTLITERALS_STEPSIZE_1 = src_LASTLITERALS - (STEPSIZE_64 - 1); - var dst_LASTLITERALS_1 = dst_end - (1 + LASTLITERALS); - var dst_LASTLITERALS_3 = dst_end - (2 + 1 + LASTLITERALS); - - int length; - - uint h, h_fwd; - - // Init - if (src_len < MINLENGTH) - { - goto _last_literals; - } - - // First Byte - hash_table[(Peek4(src, src_p) * 2654435761u) >> HASH_ADJUST] = src_p - src_base; - src_p++; - h_fwd = (Peek4(src, src_p) * 2654435761u) >> HASH_ADJUST; - - // Main Loop - while (true) - { - var findMatchAttempts = (1 << SKIPSTRENGTH) + 3; - var src_p_fwd = src_p; - int src_ref; - int dst_token; - - // Find a match - do - { - h = h_fwd; - var step = findMatchAttempts++ >> SKIPSTRENGTH; - src_p = src_p_fwd; - src_p_fwd = src_p + step; - - if (src_p_fwd > src_mflimit) - { - goto _last_literals; - } - - h_fwd = (Peek4(src, src_p_fwd) * 2654435761u) >> HASH_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = src_p - src_base; - } - while ((src_ref < src_p - MAX_DISTANCE) || (!Equal4(src, src_ref, src_p))); - - // Catch up - while ((src_p > src_anchor) && (src_ref > src_0) && (src[src_p - 1] == src[src_ref - 1])) - { - src_p--; - src_ref--; - } - - // Encode Literal length - length = src_p - src_anchor; - dst_token = dst_p++; - - if (dst_p + length + (length >> 8) > dst_LASTLITERALS_3) - { - return 0; // Check output limit - } - - if (length >= RUN_MASK) - { - var len = length - RUN_MASK; - dst[dst_token] = RUN_MASK << ML_BITS; - if (len > 254) - { - do - { - dst[dst_p++] = 255; - len -= 255; - } - while (len > 254); - dst[dst_p++] = (byte)len; - BlockCopy(src, src_anchor, dst, dst_p, length); - dst_p += length; - goto _next_match; - } - else - { - dst[dst_p++] = (byte)len; - } - } - else - { - dst[dst_token] = (byte)(length << ML_BITS); - } - - // Copy Literals - if (length > 0) - { - _i = dst_p + length; - WildCopy(src, src_anchor, dst, dst_p, _i); - dst_p = _i; - } - -_next_match: - -// Encode Offset - Poke2(dst, dst_p, (ushort)(src_p - src_ref)); - dst_p += 2; - - // Start Counting - src_p += MINMATCH; - src_ref += MINMATCH; // MinMatch already verified - src_anchor = src_p; - - while (src_p < src_LASTLITERALS_STEPSIZE_1) - { - var diff = (long)Xor8(src, src_ref, src_p); - if (diff == 0) - { - src_p += STEPSIZE_64; - src_ref += STEPSIZE_64; - continue; - } - - src_p += debruijn64[((ulong)(diff & -diff) * 0x0218A392CDABBD3FL) >> 58]; - goto _endCount; - } - - if ((src_p < src_LASTLITERALS_3) && Equal4(src, src_ref, src_p)) - { - src_p += 4; - src_ref += 4; - } - - if ((src_p < src_LASTLITERALS_1) && Equal2(src, src_ref, src_p)) - { - src_p += 2; - src_ref += 2; - } - - if ((src_p < src_LASTLITERALS) && (src[src_ref] == src[src_p])) - { - src_p++; - } - -_endCount: - -// Encode MatchLength - length = src_p - src_anchor; - - if (dst_p + (length >> 8) > dst_LASTLITERALS_1) - { - return 0; // Check output limit - } - - if (length >= ML_MASK) - { - dst[dst_token] += ML_MASK; - length -= ML_MASK; - for (; length > 509; length -= 510) - { - dst[dst_p++] = 255; - dst[dst_p++] = 255; - } - - if (length > 254) - { - length -= 255; - dst[dst_p++] = 255; - } - - dst[dst_p++] = (byte)length; - } - else - { - dst[dst_token] += (byte)length; - } - - // Test end of chunk - if (src_p > src_mflimit) - { - src_anchor = src_p; - break; - } - - // Fill table - hash_table[(Peek4(src, src_p - 2) * 2654435761u) >> HASH_ADJUST] = src_p - 2 - src_base; - - // Test next position - h = (Peek4(src, src_p) * 2654435761u) >> HASH_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = src_p - src_base; - - if ((src_ref > src_p - (MAX_DISTANCE + 1)) && Equal4(src, src_ref, src_p)) - { - dst_token = dst_p++; - dst[dst_token] = 0; - goto _next_match; - } - - // Prepare next loop - src_anchor = src_p++; - h_fwd = (Peek4(src, src_p) * 2654435761u) >> HASH_ADJUST; - } - -_last_literals: - -// Encode Last Literals - { - var lastRun = src_end - src_anchor; - - if (dst_p + lastRun + 1 + ((lastRun + 255 - RUN_MASK) / 255) > dst_end) - { - return 0; - } - - if (lastRun >= RUN_MASK) - { - dst[dst_p++] = RUN_MASK << ML_BITS; - lastRun -= RUN_MASK; - for (; lastRun > 254; lastRun -= 255) - { - dst[dst_p++] = 255; - } - - dst[dst_p++] = (byte)lastRun; - } - else - { - dst[dst_p++] = (byte)(lastRun << ML_BITS); - } - - BlockCopy(src, src_anchor, dst, dst_p, src_end - src_anchor); - dst_p += src_end - src_anchor; - } - - // End - return dst_p - dst_0; - } - } - -#endregion - -#region LZ4_compress64kCtx - - private static int LZ4_compress64kCtx_safe64( - ushort[] hash_table, - byte[] src, - byte[] dst, - int src_0, - int dst_0, - int src_len, - int dst_maxlen) - { - unchecked - { - var debruijn64 = DEBRUIJN_TABLE_64; - int _i; - - // ---- preprocessed source start here ---- - // r93 - var src_p = src_0; - var src_anchor = src_p; - var src_base = src_p; - var src_end = src_p + src_len; - var src_mflimit = src_end - MFLIMIT; - - var dst_p = dst_0; - var dst_end = dst_p + dst_maxlen; - - var src_LASTLITERALS = src_end - LASTLITERALS; - var src_LASTLITERALS_1 = src_LASTLITERALS - 1; - - var src_LASTLITERALS_3 = src_LASTLITERALS - 3; - - var src_LASTLITERALS_STEPSIZE_1 = src_LASTLITERALS - (STEPSIZE_64 - 1); - var dst_LASTLITERALS_1 = dst_end - (1 + LASTLITERALS); - var dst_LASTLITERALS_3 = dst_end - (2 + 1 + LASTLITERALS); - - int len, length; - - uint h, h_fwd; - - // Init - if (src_len < MINLENGTH) - { - goto _last_literals; - } - - // First Byte - src_p++; - h_fwd = (Peek4(src, src_p) * 2654435761u) >> HASH64K_ADJUST; - - // Main Loop - while (true) - { - var findMatchAttempts = (1 << SKIPSTRENGTH) + 3; - var src_p_fwd = src_p; - int src_ref; - int dst_token; - - // Find a match - do - { - h = h_fwd; - var step = findMatchAttempts++ >> SKIPSTRENGTH; - src_p = src_p_fwd; - src_p_fwd = src_p + step; - - if (src_p_fwd > src_mflimit) - { - goto _last_literals; - } - - h_fwd = (Peek4(src, src_p_fwd) * 2654435761u) >> HASH64K_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = (ushort)(src_p - src_base); - } - while (!Equal4(src, src_ref, src_p)); - - // Catch up - while ((src_p > src_anchor) && (src_ref > src_0) && (src[src_p - 1] == src[src_ref - 1])) - { - src_p--; - src_ref--; - } - - // Encode Literal length - length = src_p - src_anchor; - dst_token = dst_p++; - - if (dst_p + length + (length >> 8) > dst_LASTLITERALS_3) - { - return 0; // Check output limit - } - - if (length >= RUN_MASK) - { - len = length - RUN_MASK; - dst[dst_token] = RUN_MASK << ML_BITS; - if (len > 254) - { - do - { - dst[dst_p++] = 255; - len -= 255; - } - while (len > 254); - dst[dst_p++] = (byte)len; - BlockCopy(src, src_anchor, dst, dst_p, length); - dst_p += length; - goto _next_match; - } - else - { - dst[dst_p++] = (byte)len; - } - } - else - { - dst[dst_token] = (byte)(length << ML_BITS); - } - - // Copy Literals - if (length > 0) - { - _i = dst_p + length; - WildCopy(src, src_anchor, dst, dst_p, _i); - dst_p = _i; - } - -_next_match: - -// Encode Offset - Poke2(dst, dst_p, (ushort)(src_p - src_ref)); - dst_p += 2; - - // Start Counting - src_p += MINMATCH; - src_ref += MINMATCH; // MinMatch verified - src_anchor = src_p; - - while (src_p < src_LASTLITERALS_STEPSIZE_1) - { - var diff = (long)Xor8(src, src_ref, src_p); - if (diff == 0) - { - src_p += STEPSIZE_64; - src_ref += STEPSIZE_64; - continue; - } - - src_p += debruijn64[((ulong)(diff & -diff) * 0x0218A392CDABBD3FL) >> 58]; - goto _endCount; - } - - if ((src_p < src_LASTLITERALS_3) && Equal4(src, src_ref, src_p)) - { - src_p += 4; - src_ref += 4; - } - - if ((src_p < src_LASTLITERALS_1) && Equal2(src, src_ref, src_p)) - { - src_p += 2; - src_ref += 2; - } - - if ((src_p < src_LASTLITERALS) && (src[src_ref] == src[src_p])) - { - src_p++; - } - -_endCount: - -// Encode MatchLength - len = src_p - src_anchor; - - if (dst_p + (len >> 8) > dst_LASTLITERALS_1) - { - return 0; // Check output limit - } - - if (len >= ML_MASK) - { - dst[dst_token] += ML_MASK; - len -= ML_MASK; - for (; len > 509; len -= 510) - { - dst[dst_p++] = 255; - dst[dst_p++] = 255; - } - - if (len > 254) - { - len -= 255; - dst[dst_p++] = 255; - } - - dst[dst_p++] = (byte)len; - } - else - { - dst[dst_token] += (byte)len; - } - - // Test end of chunk - if (src_p > src_mflimit) - { - src_anchor = src_p; - break; - } - - // Fill table - hash_table[(Peek4(src, src_p - 2) * 2654435761u) >> HASH64K_ADJUST] = (ushort)(src_p - 2 - src_base); - - // Test next position - h = (Peek4(src, src_p) * 2654435761u) >> HASH64K_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = (ushort)(src_p - src_base); - - if (Equal4(src, src_ref, src_p)) - { - dst_token = dst_p++; - dst[dst_token] = 0; - goto _next_match; - } - - // Prepare next loop - src_anchor = src_p++; - h_fwd = (Peek4(src, src_p) * 2654435761u) >> HASH64K_ADJUST; - } - -_last_literals: - -// Encode Last Literals - { - var lastRun = src_end - src_anchor; - if (dst_p + lastRun + 1 + ((lastRun - RUN_MASK + 255) / 255) > dst_end) - { - return 0; - } - - if (lastRun >= RUN_MASK) - { - dst[dst_p++] = RUN_MASK << ML_BITS; - lastRun -= RUN_MASK; - for (; lastRun > 254; lastRun -= 255) - { - dst[dst_p++] = 255; - } - - dst[dst_p++] = (byte)lastRun; - } - else - { - dst[dst_p++] = (byte)(lastRun << ML_BITS); - } - - BlockCopy(src, src_anchor, dst, dst_p, src_end - src_anchor); - dst_p += src_end - src_anchor; - } - - // End - return dst_p - dst_0; - } - } - -#endregion - -#region LZ4_uncompress - - private static int LZ4_uncompress_safe64( - byte[] src, - byte[] dst, - int src_0, - int dst_0, - int dst_len) - { - unchecked - { - var dec32table = DECODER_TABLE_32; - var dec64table = DECODER_TABLE_64; - int _i; - - // ---- preprocessed source start here ---- - // r93 - var src_p = src_0; - int dst_ref; - - var dst_p = dst_0; - var dst_end = dst_p + dst_len; - int dst_cpy; - - var dst_LASTLITERALS = dst_end - LASTLITERALS; - var dst_COPYLENGTH = dst_end - COPYLENGTH; - var dst_COPYLENGTH_STEPSIZE_4 = dst_end - COPYLENGTH - (STEPSIZE_64 - 4); - - uint token; - - // Main Loop - while (true) - { - int length; - - // get runlength - token = src[src_p++]; - if ((length = (byte)(token >> ML_BITS)) == RUN_MASK) - { - int len; - for (; (len = src[src_p++]) == 255; length += 255) - { - /* do nothing */ - } - - length += len; - } - - // copy literals - dst_cpy = dst_p + length; - - if (dst_cpy > dst_COPYLENGTH) - { - if (dst_cpy != dst_end) - { - goto _output_error; // Error : not enough place for another match (min 4) + 5 literals - } - - BlockCopy(src, src_p, dst, dst_p, length); - src_p += length; - break; // EOF - } - - if (dst_p < dst_cpy) - { - _i = WildCopy(src, src_p, dst, dst_p, dst_cpy); - src_p += _i; - dst_p += _i; - } - - src_p -= dst_p - dst_cpy; - dst_p = dst_cpy; - - // get offset - dst_ref = dst_cpy - Peek2(src, src_p); - src_p += 2; - if (dst_ref < dst_0) - { - goto _output_error; // Error : offset outside destination buffer - } - - // get matchlength - if ((length = (byte)(token & ML_MASK)) == ML_MASK) - { - for (; src[src_p] == 255; length += 255) - { - src_p++; - } - - length += src[src_p++]; - } - - // copy repeated sequence - if ((dst_p - dst_ref) < STEPSIZE_64) - { - var dec64 = dec64table[dst_p - dst_ref]; - - dst[dst_p + 0] = dst[dst_ref + 0]; - dst[dst_p + 1] = dst[dst_ref + 1]; - dst[dst_p + 2] = dst[dst_ref + 2]; - dst[dst_p + 3] = dst[dst_ref + 3]; - dst_p += 4; - dst_ref += 4; - dst_ref -= dec32table[dst_p - dst_ref]; - Copy4(dst, dst_ref, dst_p); - dst_p += STEPSIZE_64 - 4; - dst_ref -= dec64; - } - else - { - Copy8(dst, dst_ref, dst_p); - dst_p += 8; - dst_ref += 8; - } - - dst_cpy = dst_p + length - (STEPSIZE_64 - 4); - - if (dst_cpy > dst_COPYLENGTH_STEPSIZE_4) - { - if (dst_cpy > dst_LASTLITERALS) - { - goto _output_error; // Error : last 5 bytes must be literals - } - - if (dst_p < dst_COPYLENGTH) - { - _i = SecureCopy(dst, dst_ref, dst_p, dst_COPYLENGTH); - dst_ref += _i; - dst_p += _i; - } - - while (dst_p < dst_cpy) - { - dst[dst_p++] = dst[dst_ref++]; - } - - dst_p = dst_cpy; - continue; - } - - if (dst_p < dst_cpy) - { - SecureCopy(dst, dst_ref, dst_p, dst_cpy); - } - - dst_p = dst_cpy; // correction - } - - // end of decoding - return src_p - src_0; - -_output_error: - -// write overflow error detected - return -(src_p - src_0); - } - } - -#endregion - } -} - -#endif diff --git a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Safe64.Dirty.cs.meta b/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Safe64.Dirty.cs.meta deleted file mode 100644 index dc5db1fb8..000000000 --- a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Safe64.Dirty.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 31798435f43678c67b458999c71cfbb3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Unsafe.cs b/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Unsafe.cs deleted file mode 100644 index ec9a28bc9..000000000 --- a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Unsafe.cs +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#region license - -/* -Copyright (c) 2013, Milosz Krajewski -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided -that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this list of conditions - and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this list of conditions - and the following disclaimer in the documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#endregion - -using System; - -namespace MessagePack.LZ4 -{ - /// Unsafe LZ4 codec. - internal partial class LZ4Codec - { - /// Encodes the specified input. - /// The input. - /// The output. - /// Number of bytes written. - public static unsafe int Encode(ReadOnlySpan input, Span output) - { - if (output.Length == 0) - { - throw new MessagePackSerializationException("Output is empty."); - } - - fixed (byte* inputPtr = input) - fixed (byte* outputPtr = output) - { - if (input.Length < LZ4_64KLIMIT) - { - var uHashTable = HashTablePool.GetUShortHashTablePool(); - fixed (ushort* hash1 = &uHashTable[0]) - { - if (IntPtr.Size == 4) - { - return LZ4_compress64kCtx_32(hash1, inputPtr, outputPtr, input.Length, output.Length); - } - else - { - return LZ4_compress64kCtx_64(hash1, inputPtr, outputPtr, input.Length, output.Length); - } - } - } - else - { - var bHashTable = HashTablePool.GetUIntHashTablePool(); - fixed (uint* hash2 = &bHashTable[0]) - { - if (IntPtr.Size == 4) - { - return LZ4_compressCtx_32(hash2, inputPtr, outputPtr, input.Length, output.Length); - } - else - { - return LZ4_compressCtx_64(hash2, inputPtr, outputPtr, input.Length, output.Length); - } - } - } - } - } - - /// Decodes the specified input. - /// The input. - /// The output. - /// Number of bytes written. - public static unsafe int Decode(ReadOnlySpan input, Span output) - { - if (output.Length == 0) - { - throw new MessagePackSerializationException("Output is empty."); - } - - fixed (byte* inputPtr = input) - fixed (byte* outputPtr = output) - { - int length; - if (IntPtr.Size == 4) - { - length = LZ4_uncompress_32(inputPtr, outputPtr, output.Length); - } - else - { - length = LZ4_uncompress_64(inputPtr, outputPtr, output.Length); - } - - if (length != input.Length) - { - throw new MessagePackSerializationException("LZ4 block is corrupted, or invalid length has been given."); - } - - return output.Length; - } - } - } -} diff --git a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Unsafe.cs.meta b/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Unsafe.cs.meta deleted file mode 100644 index 5a7ca605a..000000000 --- a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Unsafe.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 719385c28cab29b71a262f02263f385e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Unsafe32.Dirty.cs b/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Unsafe32.Dirty.cs deleted file mode 100644 index 22d39b25d..000000000 --- a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Unsafe32.Dirty.cs +++ /dev/null @@ -1,796 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#region LZ4 original - -/* - LZ4 - Fast LZ compression algorithm - Copyright (C) 2011-2012, Yann Collet. - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html - - LZ4 source repository : http://code.google.com/p/lz4/ -*/ - -#endregion - -#region LZ4 port - -/* -Copyright (c) 2013, Milosz Krajewski -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided -that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this list of conditions - and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this list of conditions - and the following disclaimer in the documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#endregion - -#pragma warning disable SA1312 // Variable names should begin with lower-case letter - -namespace MessagePack.LZ4 -{ - internal partial class LZ4Codec - { - #region LZ4_compressCtx_32 - - private static unsafe int LZ4_compressCtx_32( - uint* hash_table, - byte* src, - byte* dst, - int src_len, - int dst_maxlen) - { - unchecked - { - byte* _p; - - fixed (int* debruijn32 = &DEBRUIJN_TABLE_32[0]) - { - // r93 - var src_p = src; - var src_base = src_p; - var src_anchor = src_p; - var src_end = src_p + src_len; - var src_mflimit = src_end - MFLIMIT; - - var dst_p = dst; - var dst_end = dst_p + dst_maxlen; - - var src_LASTLITERALS = src_end - LASTLITERALS; - var src_LASTLITERALS_1 = src_LASTLITERALS - 1; - - var src_LASTLITERALS_STEPSIZE_1 = src_LASTLITERALS - (STEPSIZE_32 - 1); - var dst_LASTLITERALS_1 = dst_end - (1 + LASTLITERALS); - var dst_LASTLITERALS_3 = dst_end - (2 + 1 + LASTLITERALS); - - int length; - - uint h, h_fwd; - - // Init - if (src_len < MINLENGTH) - { - goto _last_literals; - } - - // First Byte - hash_table[(*(uint*)src_p * 2654435761u) >> HASH_ADJUST] = (uint)(src_p - src_base); - src_p++; - h_fwd = (*(uint*)src_p * 2654435761u) >> HASH_ADJUST; - - // Main Loop - while (true) - { - var findMatchAttempts = (1 << SKIPSTRENGTH) + 3; - var src_p_fwd = src_p; - byte* xxx_ref; - byte* xxx_token; - - // Find a match - do - { - h = h_fwd; - var step = findMatchAttempts++ >> SKIPSTRENGTH; - src_p = src_p_fwd; - src_p_fwd = src_p + step; - - if (src_p_fwd > src_mflimit) - { - goto _last_literals; - } - - h_fwd = (*(uint*)src_p_fwd * 2654435761u) >> HASH_ADJUST; - xxx_ref = src_base + hash_table[h]; - hash_table[h] = (uint)(src_p - src_base); - } - while ((xxx_ref < src_p - MAX_DISTANCE) || ((*(uint*)xxx_ref) != (*(uint*)src_p))); - - // Catch up - while ((src_p > src_anchor) && (xxx_ref > src) && (src_p[-1] == xxx_ref[-1])) - { - src_p--; - xxx_ref--; - } - - // Encode Literal length - length = (int)(src_p - src_anchor); - xxx_token = dst_p++; - - if (dst_p + length + (length >> 8) > dst_LASTLITERALS_3) - { - return 0; // Check output limit - } - - if (length >= RUN_MASK) - { - var len = length - RUN_MASK; - *xxx_token = RUN_MASK << ML_BITS; - if (len > 254) - { - do - { - *dst_p++ = 255; - len -= 255; - } - while (len > 254); - *dst_p++ = (byte)len; - BlockCopy32(src_anchor, dst_p, length); - dst_p += length; - goto _next_match; - } - - *dst_p++ = (byte)len; - } - else - { - *xxx_token = (byte)(length << ML_BITS); - } - - // Copy Literals - _p = dst_p + length; - do - { - *(uint*)dst_p = *(uint*)src_anchor; - dst_p += 4; - src_anchor += 4; - *(uint*)dst_p = *(uint*)src_anchor; - dst_p += 4; - src_anchor += 4; - } - while (dst_p < _p); - dst_p = _p; - -_next_match: - -// Encode Offset - *(ushort*)dst_p = (ushort)(src_p - xxx_ref); - dst_p += 2; - - // Start Counting - src_p += MINMATCH; - xxx_ref += MINMATCH; // MinMatch already verified - src_anchor = src_p; - - while (src_p < src_LASTLITERALS_STEPSIZE_1) - { - var diff = (*(int*)xxx_ref) ^ (*(int*)src_p); - if (diff == 0) - { - src_p += STEPSIZE_32; - xxx_ref += STEPSIZE_32; - continue; - } - - src_p += debruijn32[((uint)(diff & -diff) * 0x077CB531u) >> 27]; - goto _endCount; - } - - if ((src_p < src_LASTLITERALS_1) && ((*(ushort*)xxx_ref) == (*(ushort*)src_p))) - { - src_p += 2; - xxx_ref += 2; - } - - if ((src_p < src_LASTLITERALS) && (*xxx_ref == *src_p)) - { - src_p++; - } - -_endCount: - -// Encode MatchLength - length = (int)(src_p - src_anchor); - - if (dst_p + (length >> 8) > dst_LASTLITERALS_1) - { - return 0; // Check output limit - } - - if (length >= ML_MASK) - { - *xxx_token += ML_MASK; - length -= ML_MASK; - for (; length > 509; length -= 510) - { - *dst_p++ = 255; - *dst_p++ = 255; - } - - if (length > 254) - { - length -= 255; - *dst_p++ = 255; - } - - *dst_p++ = (byte)length; - } - else - { - *xxx_token += (byte)length; - } - - // Test end of chunk - if (src_p > src_mflimit) - { - src_anchor = src_p; - break; - } - - // Fill table - hash_table[(*(uint*)(src_p - 2) * 2654435761u) >> HASH_ADJUST] = (uint)(src_p - 2 - src_base); - - // Test next position - h = (*(uint*)src_p * 2654435761u) >> HASH_ADJUST; - xxx_ref = src_base + hash_table[h]; - hash_table[h] = (uint)(src_p - src_base); - - if ((xxx_ref > src_p - (MAX_DISTANCE + 1)) && ((*(uint*)xxx_ref) == (*(uint*)src_p))) - { - xxx_token = dst_p++; - *xxx_token = 0; - goto _next_match; - } - - // Prepare next loop - src_anchor = src_p++; - h_fwd = (*(uint*)src_p * 2654435761u) >> HASH_ADJUST; - } - -_last_literals: - -// Encode Last Literals - { - var lastRun = (int)(src_end - src_anchor); - - if (dst_p + lastRun + 1 + ((lastRun + 255 - RUN_MASK) / 255) > dst_end) - { - return 0; - } - - if (lastRun >= RUN_MASK) - { - *dst_p++ = RUN_MASK << ML_BITS; - lastRun -= RUN_MASK; - for (; lastRun > 254; lastRun -= 255) - { - *dst_p++ = 255; - } - - *dst_p++ = (byte)lastRun; - } - else - { - *dst_p++ = (byte)(lastRun << ML_BITS); - } - - BlockCopy32(src_anchor, dst_p, (int)(src_end - src_anchor)); - dst_p += src_end - src_anchor; - } - - // End - return (int)(dst_p - dst); - } - } - } - - #endregion - - #region LZ4_compress64kCtx_32 - - private static unsafe int LZ4_compress64kCtx_32( - ushort* hash_table, - byte* src, - byte* dst, - int src_len, - int dst_maxlen) - { - unchecked - { - byte* _p; - fixed (int* debruijn32 = &DEBRUIJN_TABLE_32[0]) - { - // r93 - var src_p = src; - var src_anchor = src_p; - var src_base = src_p; - var src_end = src_p + src_len; - var src_mflimit = src_end - MFLIMIT; - - var dst_p = dst; - var dst_end = dst_p + dst_maxlen; - - var src_LASTLITERALS = src_end - LASTLITERALS; - var src_LASTLITERALS_1 = src_LASTLITERALS - 1; - - var src_LASTLITERALS_STEPSIZE_1 = src_LASTLITERALS - (STEPSIZE_32 - 1); - var dst_LASTLITERALS_1 = dst_end - (1 + LASTLITERALS); - var dst_LASTLITERALS_3 = dst_end - (2 + 1 + LASTLITERALS); - - int len, length; - - uint h, h_fwd; - - // Init - if (src_len < MINLENGTH) - { - goto _last_literals; - } - - // First Byte - src_p++; - h_fwd = (*(uint*)src_p * 2654435761u) >> HASH64K_ADJUST; - - // Main Loop - while (true) - { - var findMatchAttempts = (1 << SKIPSTRENGTH) + 3; - var src_p_fwd = src_p; - byte* xxx_ref; - byte* xxx_token; - - // Find a match - do - { - h = h_fwd; - var step = findMatchAttempts++ >> SKIPSTRENGTH; - src_p = src_p_fwd; - src_p_fwd = src_p + step; - - if (src_p_fwd > src_mflimit) - { - goto _last_literals; - } - - h_fwd = (*(uint*)src_p_fwd * 2654435761u) >> HASH64K_ADJUST; - xxx_ref = src_base + hash_table[h]; - hash_table[h] = (ushort)(src_p - src_base); - } - while ((*(uint*)xxx_ref) != (*(uint*)src_p)); - - // Catch up - while ((src_p > src_anchor) && (xxx_ref > src) && (src_p[-1] == xxx_ref[-1])) - { - src_p--; - xxx_ref--; - } - - // Encode Literal length - length = (int)(src_p - src_anchor); - xxx_token = dst_p++; - - if (dst_p + length + (length >> 8) > dst_LASTLITERALS_3) - { - return 0; // Check output limit - } - - if (length >= RUN_MASK) - { - len = length - RUN_MASK; - *xxx_token = RUN_MASK << ML_BITS; - if (len > 254) - { - do - { - *dst_p++ = 255; - len -= 255; - } - while (len > 254); - *dst_p++ = (byte)len; - BlockCopy32(src_anchor, dst_p, length); - dst_p += length; - goto _next_match; - } - - *dst_p++ = (byte)len; - } - else - { - *xxx_token = (byte)(length << ML_BITS); - } - - // Copy Literals - _p = dst_p + length; - do - { - *(uint*)dst_p = *(uint*)src_anchor; - dst_p += 4; - src_anchor += 4; - *(uint*)dst_p = *(uint*)src_anchor; - dst_p += 4; - src_anchor += 4; - } - while (dst_p < _p); - dst_p = _p; - -_next_match: - -// Encode Offset - *(ushort*)dst_p = (ushort)(src_p - xxx_ref); - dst_p += 2; - - // Start Counting - src_p += MINMATCH; - xxx_ref += MINMATCH; // MinMatch verified - src_anchor = src_p; - - while (src_p < src_LASTLITERALS_STEPSIZE_1) - { - var diff = (*(int*)xxx_ref) ^ (*(int*)src_p); - if (diff == 0) - { - src_p += STEPSIZE_32; - xxx_ref += STEPSIZE_32; - continue; - } - - src_p += debruijn32[((uint)(diff & -diff) * 0x077CB531u) >> 27]; - goto _endCount; - } - - if ((src_p < src_LASTLITERALS_1) && ((*(ushort*)xxx_ref) == (*(ushort*)src_p))) - { - src_p += 2; - xxx_ref += 2; - } - - if ((src_p < src_LASTLITERALS) && (*xxx_ref == *src_p)) - { - src_p++; - } - -_endCount: - -// Encode MatchLength - len = (int)(src_p - src_anchor); - - if (dst_p + (len >> 8) > dst_LASTLITERALS_1) - { - return 0; // Check output limit - } - - if (len >= ML_MASK) - { - *xxx_token += ML_MASK; - len -= ML_MASK; - for (; len > 509; len -= 510) - { - *dst_p++ = 255; - *dst_p++ = 255; - } - - if (len > 254) - { - len -= 255; - *dst_p++ = 255; - } - - *dst_p++ = (byte)len; - } - else - { - *xxx_token += (byte)len; - } - - // Test end of chunk - if (src_p > src_mflimit) - { - src_anchor = src_p; - break; - } - - // Fill table - hash_table[(*(uint*)(src_p - 2) * 2654435761u) >> HASH64K_ADJUST] = (ushort)(src_p - 2 - src_base); - - // Test next position - h = (*(uint*)src_p * 2654435761u) >> HASH64K_ADJUST; - xxx_ref = src_base + hash_table[h]; - hash_table[h] = (ushort)(src_p - src_base); - - if ((*(uint*)xxx_ref) == (*(uint*)src_p)) - { - xxx_token = dst_p++; - *xxx_token = 0; - goto _next_match; - } - - // Prepare next loop - src_anchor = src_p++; - h_fwd = (*(uint*)src_p * 2654435761u) >> HASH64K_ADJUST; - } - -_last_literals: - -// Encode Last Literals - { - var lastRun = (int)(src_end - src_anchor); - if (dst_p + lastRun + 1 + ((lastRun - RUN_MASK + 255) / 255) > dst_end) - { - return 0; - } - - if (lastRun >= RUN_MASK) - { - *dst_p++ = RUN_MASK << ML_BITS; - lastRun -= RUN_MASK; - for (; lastRun > 254; lastRun -= 255) - { - *dst_p++ = 255; - } - - *dst_p++ = (byte)lastRun; - } - else - { - *dst_p++ = (byte)(lastRun << ML_BITS); - } - - BlockCopy32(src_anchor, dst_p, (int)(src_end - src_anchor)); - dst_p += src_end - src_anchor; - } - - // End - return (int)(dst_p - dst); - } - } - } - - #endregion - - #region LZ4_uncompress_32 - - private static unsafe int LZ4_uncompress_32( - byte* src, - byte* dst, - int dst_len) - { - unchecked - { - fixed (int* dec32table = &DECODER_TABLE_32[0]) - { - // r93 - var src_p = src; - byte* xxx_ref; - - var dst_p = dst; - var dst_end = dst_p + dst_len; - byte* dst_cpy; - - var dst_LASTLITERALS = dst_end - LASTLITERALS; - var dst_COPYLENGTH = dst_end - COPYLENGTH; - var dst_COPYLENGTH_STEPSIZE_4 = dst_end - COPYLENGTH - (STEPSIZE_32 - 4); - - uint xxx_token; - - // Main Loop - while (true) - { - int length; - - // get runlength - xxx_token = *src_p++; - if ((length = (int)(xxx_token >> ML_BITS)) == RUN_MASK) - { - int len; - for (; (len = *src_p++) == 255; length += 255) - { - /* do nothing */ - } - - length += len; - } - - // copy literals - dst_cpy = dst_p + length; - - if (dst_cpy > dst_COPYLENGTH) - { - if (dst_cpy != dst_end) - { - goto _output_error; // Error : not enough place for another match (min 4) + 5 literals - } - - BlockCopy32(src_p, dst_p, length); - src_p += length; - break; // EOF - } - - do - { - *(uint*)dst_p = *(uint*)src_p; - dst_p += 4; - src_p += 4; - *(uint*)dst_p = *(uint*)src_p; - dst_p += 4; - src_p += 4; - } - while (dst_p < dst_cpy); - src_p -= dst_p - dst_cpy; - dst_p = dst_cpy; - - // get offset - xxx_ref = dst_cpy - (*(ushort*)src_p); - src_p += 2; - if (xxx_ref < dst) - { - goto _output_error; // Error : offset outside destination buffer - } - - // get matchlength - if ((length = (int)(xxx_token & ML_MASK)) == ML_MASK) - { - for (; *src_p == 255; length += 255) - { - src_p++; - } - - length += *src_p++; - } - - // copy repeated sequence - if ((dst_p - xxx_ref) < STEPSIZE_32) - { - const int dec64 = 0; - - dst_p[0] = xxx_ref[0]; - dst_p[1] = xxx_ref[1]; - dst_p[2] = xxx_ref[2]; - dst_p[3] = xxx_ref[3]; - dst_p += 4; - xxx_ref += 4; - xxx_ref -= dec32table[dst_p - xxx_ref]; - *(uint*)dst_p = *(uint*)xxx_ref; - dst_p += STEPSIZE_32 - 4; - xxx_ref -= dec64; - } - else - { - *(uint*)dst_p = *(uint*)xxx_ref; - dst_p += 4; - xxx_ref += 4; - } - - dst_cpy = dst_p + length - (STEPSIZE_32 - 4); - - if (dst_cpy > dst_COPYLENGTH_STEPSIZE_4) - { - if (dst_cpy > dst_LASTLITERALS) - { - goto _output_error; // Error : last 5 bytes must be literals - } - - { - do - { - *(uint*)dst_p = *(uint*)xxx_ref; - dst_p += 4; - xxx_ref += 4; - *(uint*)dst_p = *(uint*)xxx_ref; - dst_p += 4; - xxx_ref += 4; - } - while (dst_p < dst_COPYLENGTH); - } - - while (dst_p < dst_cpy) - { - *dst_p++ = *xxx_ref++; - } - - dst_p = dst_cpy; - continue; - } - - do - { - *(uint*)dst_p = *(uint*)xxx_ref; - dst_p += 4; - xxx_ref += 4; - *(uint*)dst_p = *(uint*)xxx_ref; - dst_p += 4; - xxx_ref += 4; - } - while (dst_p < dst_cpy); - dst_p = dst_cpy; // correction - } - - // end of decoding - return (int)(src_p - src); - -// write overflow error detected -_output_error: - return (int)-(src_p - src); - } - } - } - - #endregion - - /// Copies block of memory. - /// The source. - /// The destination. - /// The length (in bytes). - private static unsafe void BlockCopy32(byte* src, byte* dst, int len) - { - while (len >= 4) - { - *(uint*)dst = *(uint*)src; - dst += 4; - src += 4; - len -= 4; - } - - if (len >= 2) - { - *(ushort*)dst = *(ushort*)src; - dst += 2; - src += 2; - len -= 2; - } - - if (len >= 1) - { - *dst = *src; /* d++; s++; l--; */ - } - } - } -} diff --git a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Unsafe32.Dirty.cs.meta b/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Unsafe32.Dirty.cs.meta deleted file mode 100644 index 5222cd47d..000000000 --- a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Unsafe32.Dirty.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 44efef809614456e8a4d40559c526efa -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Unsafe64.Dirty.cs b/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Unsafe64.Dirty.cs deleted file mode 100644 index ba10e68d2..000000000 --- a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Unsafe64.Dirty.cs +++ /dev/null @@ -1,808 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#region LZ4 original - -/* - LZ4 - Fast LZ compression algorithm - Copyright (C) 2011-2012, Yann Collet. - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html - - LZ4 source repository : http://code.google.com/p/lz4/ -*/ - -#endregion - -#region LZ4 port - -/* -Copyright (c) 2013, Milosz Krajewski -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided -that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this list of conditions - and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this list of conditions - and the following disclaimer in the documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#endregion - -#pragma warning disable SA1312 // Variable names should begin with lower-case letter - -namespace MessagePack.LZ4 -{ - internal partial class LZ4Codec - { - #region LZ4_compressCtx_64 - - private static unsafe int LZ4_compressCtx_64( - uint* hash_table, - byte* src, - byte* dst, - int src_len, - int dst_maxlen) - { - unchecked - { - byte* _p; - - fixed (int* debruijn64 = &DEBRUIJN_TABLE_64[0]) - { - // r93 - var src_p = src; - var src_base = src_p; - var src_anchor = src_p; - var src_end = src_p + src_len; - var src_mflimit = src_end - MFLIMIT; - - var dst_p = dst; - var dst_end = dst_p + dst_maxlen; - - var src_LASTLITERALS = src_end - LASTLITERALS; - var src_LASTLITERALS_1 = src_LASTLITERALS - 1; - - var src_LASTLITERALS_3 = src_LASTLITERALS - 3; - var src_LASTLITERALS_STEPSIZE_1 = src_LASTLITERALS - (STEPSIZE_64 - 1); - var dst_LASTLITERALS_1 = dst_end - (1 + LASTLITERALS); - var dst_LASTLITERALS_3 = dst_end - (2 + 1 + LASTLITERALS); - - int length; - uint h, h_fwd; - - // Init - if (src_len < MINLENGTH) - { - goto _last_literals; - } - - // First Byte - hash_table[(*(uint*)src_p * 2654435761u) >> HASH_ADJUST] = (uint)(src_p - src_base); - src_p++; - h_fwd = (*(uint*)src_p * 2654435761u) >> HASH_ADJUST; - - // Main Loop - while (true) - { - var findMatchAttempts = (1 << SKIPSTRENGTH) + 3; - var src_p_fwd = src_p; - byte* src_ref; - byte* dst_token; - - // Find a match - do - { - h = h_fwd; - var step = findMatchAttempts++ >> SKIPSTRENGTH; - src_p = src_p_fwd; - src_p_fwd = src_p + step; - - if (src_p_fwd > src_mflimit) - { - goto _last_literals; - } - - h_fwd = (*(uint*)src_p_fwd * 2654435761u) >> HASH_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = (uint)(src_p - src_base); - } - while ((src_ref < src_p - MAX_DISTANCE) || ((*(uint*)src_ref) != (*(uint*)src_p))); - - // Catch up - while ((src_p > src_anchor) && (src_ref > src) && (src_p[-1] == src_ref[-1])) - { - src_p--; - src_ref--; - } - - // Encode Literal length - length = (int)(src_p - src_anchor); - dst_token = dst_p++; - - if (dst_p + length + (length >> 8) > dst_LASTLITERALS_3) - { - return 0; // Check output limit - } - - if (length >= RUN_MASK) - { - var len = length - RUN_MASK; - *dst_token = RUN_MASK << ML_BITS; - if (len > 254) - { - do - { - *dst_p++ = 255; - len -= 255; - } - while (len > 254); - *dst_p++ = (byte)len; - BlockCopy64(src_anchor, dst_p, length); - dst_p += length; - goto _next_match; - } - - *dst_p++ = (byte)len; - } - else - { - *dst_token = (byte)(length << ML_BITS); - } - - // Copy Literals - _p = dst_p + length; - { - do - { - *(ulong*)dst_p = *(ulong*)src_anchor; - dst_p += 8; - src_anchor += 8; - } - while (dst_p < _p); - } - - dst_p = _p; - -_next_match: - -// Encode Offset - *(ushort*)dst_p = (ushort)(src_p - src_ref); - dst_p += 2; - - // Start Counting - src_p += MINMATCH; - src_ref += MINMATCH; // MinMatch already verified - src_anchor = src_p; - - while (src_p < src_LASTLITERALS_STEPSIZE_1) - { - var diff = (*(long*)src_ref) ^ (*(long*)src_p); - if (diff == 0) - { - src_p += STEPSIZE_64; - src_ref += STEPSIZE_64; - continue; - } - - src_p += debruijn64[((ulong)(diff & -diff) * 0x0218A392CDABBD3FL) >> 58]; - goto _endCount; - } - - if ((src_p < src_LASTLITERALS_3) && ((*(uint*)src_ref) == (*(uint*)src_p))) - { - src_p += 4; - src_ref += 4; - } - - if ((src_p < src_LASTLITERALS_1) && ((*(ushort*)src_ref) == (*(ushort*)src_p))) - { - src_p += 2; - src_ref += 2; - } - - if ((src_p < src_LASTLITERALS) && (*src_ref == *src_p)) - { - src_p++; - } - -_endCount: - -// Encode MatchLength - length = (int)(src_p - src_anchor); - - if (dst_p + (length >> 8) > dst_LASTLITERALS_1) - { - return 0; // Check output limit - } - - if (length >= ML_MASK) - { - *dst_token += ML_MASK; - length -= ML_MASK; - for (; length > 509; length -= 510) - { - *dst_p++ = 255; - *dst_p++ = 255; - } - - if (length > 254) - { - length -= 255; - *dst_p++ = 255; - } - - *dst_p++ = (byte)length; - } - else - { - *dst_token += (byte)length; - } - - // Test end of chunk - if (src_p > src_mflimit) - { - src_anchor = src_p; - break; - } - - // Fill table - hash_table[(*(uint*)(src_p - 2) * 2654435761u) >> HASH_ADJUST] = (uint)(src_p - 2 - src_base); - - // Test next position - h = (*(uint*)src_p * 2654435761u) >> HASH_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = (uint)(src_p - src_base); - - if ((src_ref > src_p - (MAX_DISTANCE + 1)) && ((*(uint*)src_ref) == (*(uint*)src_p))) - { - dst_token = dst_p++; - *dst_token = 0; - goto _next_match; - } - - // Prepare next loop - src_anchor = src_p++; - h_fwd = (*(uint*)src_p * 2654435761u) >> HASH_ADJUST; - } - -_last_literals: - -// Encode Last Literals - var lastRun = (int)(src_end - src_anchor); - if (dst_p + lastRun + 1 + ((lastRun + 255 - RUN_MASK) / 255) > dst_end) - { - return 0; - } - - if (lastRun >= RUN_MASK) - { - *dst_p++ = RUN_MASK << ML_BITS; - lastRun -= RUN_MASK; - for (; lastRun > 254; lastRun -= 255) - { - *dst_p++ = 255; - } - - *dst_p++ = (byte)lastRun; - } - else - { - *dst_p++ = (byte)(lastRun << ML_BITS); - } - - BlockCopy64(src_anchor, dst_p, (int)(src_end - src_anchor)); - dst_p += src_end - src_anchor; - - // End - return (int)(dst_p - dst); - } - } - } - - #endregion - - #region LZ4_compress64kCtx_64 - - private static unsafe int LZ4_compress64kCtx_64( - ushort* hash_table, - byte* src, - byte* dst, - int src_len, - int dst_maxlen) - { - unchecked - { - byte* _p; - - fixed (int* debruijn64 = &DEBRUIJN_TABLE_64[0]) - { - // r93 - var src_p = src; - var src_anchor = src_p; - var src_base = src_p; - var src_end = src_p + src_len; - var src_mflimit = src_end - MFLIMIT; - - var dst_p = dst; - var dst_end = dst_p + dst_maxlen; - - var src_LASTLITERALS = src_end - LASTLITERALS; - var src_LASTLITERALS_1 = src_LASTLITERALS - 1; - - var src_LASTLITERALS_3 = src_LASTLITERALS - 3; - - var src_LASTLITERALS_STEPSIZE_1 = src_LASTLITERALS - (STEPSIZE_64 - 1); - var dst_LASTLITERALS_1 = dst_end - (1 + LASTLITERALS); - var dst_LASTLITERALS_3 = dst_end - (2 + 1 + LASTLITERALS); - - int len, length; - - uint h, h_fwd; - - // Init - if (src_len < MINLENGTH) - { - goto _last_literals; - } - - // First Byte - src_p++; - h_fwd = (*(uint*)src_p * 2654435761u) >> HASH64K_ADJUST; - - // Main Loop - while (true) - { - var findMatchAttempts = (1 << SKIPSTRENGTH) + 3; - var src_p_fwd = src_p; - byte* src_ref; - byte* dst_token; - - // Find a match - do - { - h = h_fwd; - var step = findMatchAttempts++ >> SKIPSTRENGTH; - src_p = src_p_fwd; - src_p_fwd = src_p + step; - - if (src_p_fwd > src_mflimit) - { - goto _last_literals; - } - - h_fwd = (*(uint*)src_p_fwd * 2654435761u) >> HASH64K_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = (ushort)(src_p - src_base); - } - while ((*(uint*)src_ref) != (*(uint*)src_p)); - - // Catch up - while ((src_p > src_anchor) && (src_ref > src) && (src_p[-1] == src_ref[-1])) - { - src_p--; - src_ref--; - } - - // Encode Literal length - length = (int)(src_p - src_anchor); - dst_token = dst_p++; - - if (dst_p + length + (length >> 8) > dst_LASTLITERALS_3) - { - return 0; // Check output limit - } - - if (length >= RUN_MASK) - { - len = length - RUN_MASK; - *dst_token = RUN_MASK << ML_BITS; - if (len > 254) - { - do - { - *dst_p++ = 255; - len -= 255; - } - while (len > 254); - *dst_p++ = (byte)len; - BlockCopy64(src_anchor, dst_p, length); - dst_p += length; - goto _next_match; - } - - *dst_p++ = (byte)len; - } - else - { - *dst_token = (byte)(length << ML_BITS); - } - - // Copy Literals - { - _p = dst_p + length; - { - do - { - *(ulong*)dst_p = *(ulong*)src_anchor; - dst_p += 8; - src_anchor += 8; - } - while (dst_p < _p); - } - - dst_p = _p; - } - -_next_match: - -// Encode Offset - *(ushort*)dst_p = (ushort)(src_p - src_ref); - dst_p += 2; - - // Start Counting - src_p += MINMATCH; - src_ref += MINMATCH; // MinMatch verified - src_anchor = src_p; - - while (src_p < src_LASTLITERALS_STEPSIZE_1) - { - var diff = (*(long*)src_ref) ^ (*(long*)src_p); - if (diff == 0) - { - src_p += STEPSIZE_64; - src_ref += STEPSIZE_64; - continue; - } - - src_p += debruijn64[((ulong)(diff & -diff) * 0x0218A392CDABBD3FL) >> 58]; - goto _endCount; - } - - if ((src_p < src_LASTLITERALS_3) && ((*(uint*)src_ref) == (*(uint*)src_p))) - { - src_p += 4; - src_ref += 4; - } - - if ((src_p < src_LASTLITERALS_1) && ((*(ushort*)src_ref) == (*(ushort*)src_p))) - { - src_p += 2; - src_ref += 2; - } - - if ((src_p < src_LASTLITERALS) && (*src_ref == *src_p)) - { - src_p++; - } - -_endCount: - -// Encode MatchLength - len = (int)(src_p - src_anchor); - - if (dst_p + (len >> 8) > dst_LASTLITERALS_1) - { - return 0; // Check output limit - } - - if (len >= ML_MASK) - { - *dst_token += ML_MASK; - len -= ML_MASK; - for (; len > 509; len -= 510) - { - *dst_p++ = 255; - *dst_p++ = 255; - } - - if (len > 254) - { - len -= 255; - *dst_p++ = 255; - } - - *dst_p++ = (byte)len; - } - else - { - *dst_token += (byte)len; - } - - // Test end of chunk - if (src_p > src_mflimit) - { - src_anchor = src_p; - break; - } - - // Fill table - hash_table[(*(uint*)(src_p - 2) * 2654435761u) >> HASH64K_ADJUST] = (ushort)(src_p - 2 - src_base); - - // Test next position - h = (*(uint*)src_p * 2654435761u) >> HASH64K_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = (ushort)(src_p - src_base); - - if ((*(uint*)src_ref) == (*(uint*)src_p)) - { - dst_token = dst_p++; - *dst_token = 0; - goto _next_match; - } - - // Prepare next loop - src_anchor = src_p++; - h_fwd = (*(uint*)src_p * 2654435761u) >> HASH64K_ADJUST; - } - -_last_literals: - -// Encode Last Literals - var lastRun = (int)(src_end - src_anchor); - if (dst_p + lastRun + 1 + ((lastRun - RUN_MASK + 255) / 255) > dst_end) - { - return 0; - } - - if (lastRun >= RUN_MASK) - { - *dst_p++ = RUN_MASK << ML_BITS; - lastRun -= RUN_MASK; - for (; lastRun > 254; lastRun -= 255) - { - *dst_p++ = 255; - } - - *dst_p++ = (byte)lastRun; - } - else - { - *dst_p++ = (byte)(lastRun << ML_BITS); - } - - BlockCopy64(src_anchor, dst_p, (int)(src_end - src_anchor)); - dst_p += src_end - src_anchor; - - // End - return (int)(dst_p - dst); - } - } - } - - #endregion - - #region LZ4_uncompress_64 - - private static unsafe int LZ4_uncompress_64( - byte* src, - byte* dst, - int dst_len) - { - unchecked - { - fixed (int* dec32table = &DECODER_TABLE_32[0]) - fixed (int* dec64table = &DECODER_TABLE_64[0]) - { - // r93 - var src_p = src; - byte* dst_ref; - - var dst_p = dst; - var dst_end = dst_p + dst_len; - byte* dst_cpy; - - var dst_LASTLITERALS = dst_end - LASTLITERALS; - var dst_COPYLENGTH = dst_end - COPYLENGTH; - var dst_COPYLENGTH_STEPSIZE_4 = dst_end - COPYLENGTH - (STEPSIZE_64 - 4); - - byte token; - - // Main Loop - while (true) - { - int length; - - // get runlength - token = *src_p++; - if ((length = token >> ML_BITS) == RUN_MASK) - { - int len; - for (; (len = *src_p++) == 255; length += 255) - { - /* do nothing */ - } - - length += len; - } - - // copy literals - dst_cpy = dst_p + length; - - if (dst_cpy > dst_COPYLENGTH) - { - if (dst_cpy != dst_end) - { - goto _output_error; // Error : not enough place for another match (min 4) + 5 literals - } - - BlockCopy64(src_p, dst_p, length); - src_p += length; - break; // EOF - } - - do - { - *(ulong*)dst_p = *(ulong*)src_p; - dst_p += 8; - src_p += 8; - } - while (dst_p < dst_cpy); - src_p -= dst_p - dst_cpy; - dst_p = dst_cpy; - - // get offset - dst_ref = dst_cpy - (*(ushort*)src_p); - src_p += 2; - if (dst_ref < dst) - { - goto _output_error; // Error : offset outside destination buffer - } - - // get matchlength - if ((length = token & ML_MASK) == ML_MASK) - { - for (; *src_p == 255; length += 255) - { - src_p++; - } - - length += *src_p++; - } - - // copy repeated sequence - if ((dst_p - dst_ref) < STEPSIZE_64) - { - var dec64 = dec64table[dst_p - dst_ref]; - - dst_p[0] = dst_ref[0]; - dst_p[1] = dst_ref[1]; - dst_p[2] = dst_ref[2]; - dst_p[3] = dst_ref[3]; - dst_p += 4; - dst_ref += 4; - dst_ref -= dec32table[dst_p - dst_ref]; - *(uint*)dst_p = *(uint*)dst_ref; - dst_p += STEPSIZE_64 - 4; - dst_ref -= dec64; - } - else - { - *(ulong*)dst_p = *(ulong*)dst_ref; - dst_p += 8; - dst_ref += 8; - } - - dst_cpy = dst_p + length - (STEPSIZE_64 - 4); - - if (dst_cpy > dst_COPYLENGTH_STEPSIZE_4) - { - if (dst_cpy > dst_LASTLITERALS) - { - goto _output_error; // Error : last 5 bytes must be literals - } - - while (dst_p < dst_COPYLENGTH) - { - *(ulong*)dst_p = *(ulong*)dst_ref; - dst_p += 8; - dst_ref += 8; - } - - while (dst_p < dst_cpy) - { - *dst_p++ = *dst_ref++; - } - - dst_p = dst_cpy; - continue; - } - - { - do - { - *(ulong*)dst_p = *(ulong*)dst_ref; - dst_p += 8; - dst_ref += 8; - } - while (dst_p < dst_cpy); - } - - dst_p = dst_cpy; // correction - } - - // end of decoding - return (int)(src_p - src); - -// write overflow error detected -_output_error: - return (int)-(src_p - src); - } - } - } - - #endregion - - /// Copies block of memory. - /// The source. - /// The destination. - /// The length (in bytes). - private static unsafe void BlockCopy64(byte* src, byte* dst, int len) - { - while (len >= 8) - { - *(ulong*)dst = *(ulong*)src; - dst += 8; - src += 8; - len -= 8; - } - - if (len >= 4) - { - *(uint*)dst = *(uint*)src; - dst += 4; - src += 4; - len -= 4; - } - - if (len >= 2) - { - *(ushort*)dst = *(ushort*)src; - dst += 2; - src += 2; - len -= 2; - } - - if (len >= 1) - { - *dst = *src; /* d++; s++; l--; */ - } - } - } -} diff --git a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Unsafe64.Dirty.cs.meta b/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Unsafe64.Dirty.cs.meta deleted file mode 100644 index 66706fb15..000000000 --- a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.Unsafe64.Dirty.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: fa2e5105dcebe0410bb8ed76f622889f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.cs b/Assets/Plugins/MessagePack/LZ4/LZ4Codec.cs deleted file mode 100644 index 8445807fc..000000000 --- a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.cs +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#region license - -/* -Copyright (c) 2013, Milosz Krajewski -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided -that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this list of conditions - and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this list of conditions - and the following disclaimer in the documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#endregion - -using System; - -#pragma warning disable SA1310 // Field names should not contain underscore - -namespace MessagePack.LZ4 -{ - internal static partial class LZ4Codec - { - #region configuration - - /// - /// Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.) - /// Increasing memory usage improves compression ratio - /// Reduced memory usage can improve speed, due to cache effect - /// Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache. - /// - private const int MEMORY_USAGE = 12; // modified use 12. - - /// - /// Decreasing this value will make the algorithm skip faster data segments considered "incompressible" - /// This may decrease compression ratio dramatically, but will be faster on incompressible data - /// Increasing this value will make the algorithm search more before declaring a segment "incompressible" - /// This could improve compression a bit, but will be slower on incompressible data - /// The default value (6) is recommended. - /// - private const int NOTCOMPRESSIBLE_DETECTIONLEVEL = 6; - - #endregion - - #region consts - - private const int MINMATCH = 4; - -#pragma warning disable 162, 429 - - private const int SKIPSTRENGTH = NOTCOMPRESSIBLE_DETECTIONLEVEL > 2 ? NOTCOMPRESSIBLE_DETECTIONLEVEL : 2; -#pragma warning restore 162, 429 - - private const int COPYLENGTH = 8; - private const int LASTLITERALS = 5; - private const int MFLIMIT = COPYLENGTH + MINMATCH; - private const int MINLENGTH = MFLIMIT + 1; - private const int MAXD_LOG = 16; - private const int MAXD = 1 << MAXD_LOG; - private const int MAXD_MASK = MAXD - 1; - private const int MAX_DISTANCE = (1 << MAXD_LOG) - 1; - private const int ML_BITS = 4; - private const int ML_MASK = (1 << ML_BITS) - 1; - private const int RUN_BITS = 8 - ML_BITS; - private const int RUN_MASK = (1 << RUN_BITS) - 1; - private const int STEPSIZE_64 = 8; - private const int STEPSIZE_32 = 4; - - private const int LZ4_64KLIMIT = (1 << 16) + (MFLIMIT - 1); - - private const int HASH_LOG = MEMORY_USAGE - 2; - private const int HASH_TABLESIZE = 1 << HASH_LOG; - private const int HASH_ADJUST = (MINMATCH * 8) - HASH_LOG; - - private const int HASH64K_LOG = HASH_LOG + 1; - private const int HASH64K_TABLESIZE = 1 << HASH64K_LOG; - private const int HASH64K_ADJUST = (MINMATCH * 8) - HASH64K_LOG; - - private const int HASHHC_LOG = MAXD_LOG - 1; - private const int HASHHC_TABLESIZE = 1 << HASHHC_LOG; - private const int HASHHC_ADJUST = (MINMATCH * 8) - HASHHC_LOG; - ////private const int HASHHC_MASK = HASHHC_TABLESIZE - 1; - - private const int MAX_NB_ATTEMPTS = 256; - private const int OPTIMAL_ML = ML_MASK - 1 + MINMATCH; - - private const int BLOCK_COPY_LIMIT = 16; - - private static readonly int[] DECODER_TABLE_32 = { 0, 3, 2, 3, 0, 0, 0, 0 }; - private static readonly int[] DECODER_TABLE_64 = { 0, 0, 0, -1, 0, 1, 2, 3 }; - - private static readonly int[] DEBRUIJN_TABLE_32 = - { - 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, - 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1, - }; - - private static readonly int[] DEBRUIJN_TABLE_64 = - { - 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, - 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, - 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, - 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7, - }; - - #endregion - - #region public interface (common) - - /// Gets maximum the length of the output. - /// Length of the input. - /// Maximum number of bytes needed for compressed buffer. - public static int MaximumOutputLength(int inputLength) - { - return inputLength + (inputLength / 255) + 16; - } - - #endregion - - #region internal interface (common) - - internal static void CheckArguments(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int outputLength) - { - if (inputLength == 0) - { - outputLength = 0; - return; - } - - if (input == null) - { - throw new ArgumentNullException("input"); - } - - if ((uint)inputOffset > (uint)input.Length) - { - throw new ArgumentOutOfRangeException("inputOffset"); - } - - if ((uint)inputLength > (uint)input.Length - (uint)inputOffset) - { - throw new ArgumentOutOfRangeException("inputLength"); - } - - if (output == null) - { - throw new ArgumentNullException("output"); - } - - if ((uint)outputOffset > (uint)output.Length) - { - throw new ArgumentOutOfRangeException("outputOffset"); - } - - if ((uint)outputLength > (uint)output.Length - (uint)outputOffset) - { - throw new ArgumentOutOfRangeException("outputLength"); - } - } - - #endregion - } -} diff --git a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.cs.meta b/Assets/Plugins/MessagePack/LZ4/LZ4Codec.cs.meta deleted file mode 100644 index 632797c95..000000000 --- a/Assets/Plugins/MessagePack/LZ4/LZ4Codec.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b67a7760eb98ee768b90af4f2d6d9dc4 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/MessagePack.ReactiveProperty.meta b/Assets/Plugins/MessagePack/MessagePack.ReactiveProperty.meta deleted file mode 100644 index ceceaa61d..000000000 --- a/Assets/Plugins/MessagePack/MessagePack.ReactiveProperty.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: b6674829093b8084dae06c4c1a73cbcd -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/MessagePack.ReactiveProperty/Formatters.cs b/Assets/Plugins/MessagePack/MessagePack.ReactiveProperty/Formatters.cs deleted file mode 100644 index f0063e7aa..000000000 --- a/Assets/Plugins/MessagePack/MessagePack.ReactiveProperty/Formatters.cs +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using MessagePack.Formatters; -using UniRx; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.ReactivePropertyExtension -{ - public class ReactivePropertyFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, ReactiveProperty value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - options.Resolver.GetFormatterWithVerify().Serialize(ref writer, value.Value, options); - } - } - - public ReactiveProperty Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - T v = options.Resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new ReactiveProperty(v); - } - } - } - - public class ReactiveCollectionFormatter : CollectionFormatterBase> - { - protected override void Add(ReactiveCollection collection, int index, T value, MessagePackSerializerOptions options) - { - collection.Add(value); - } - - protected override ReactiveCollection Create(int count, MessagePackSerializerOptions options) - { - return new ReactiveCollection(); - } - } - - public class UnitFormatter : IMessagePackFormatter - { - public static readonly UnitFormatter Instance = new UnitFormatter(); - - private UnitFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Unit value, MessagePackSerializerOptions options) - { - writer.WriteNil(); - } - - public Unit Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return Unit.Default; - } - else - { - throw new InvalidOperationException("Invalid Data type. Code: " + MessagePackCode.ToFormatName(reader.NextCode)); - } - } - } - - public class NullableUnitFormatter : IMessagePackFormatter - { - public static readonly NullableUnitFormatter Instance = new NullableUnitFormatter(); - - private NullableUnitFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Unit? value, MessagePackSerializerOptions options) - { - writer.WriteNil(); - } - - public Unit? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return Unit.Default; - } - else - { - throw new InvalidOperationException("Invalid Data type. Code: " + MessagePackCode.ToFormatName(reader.NextCode)); - } - } - } -} diff --git a/Assets/Plugins/MessagePack/MessagePack.ReactiveProperty/Formatters.cs.meta b/Assets/Plugins/MessagePack/MessagePack.ReactiveProperty/Formatters.cs.meta deleted file mode 100644 index 6ac350357..000000000 --- a/Assets/Plugins/MessagePack/MessagePack.ReactiveProperty/Formatters.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2ba66c25dd4bca148a26245df562577b -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/MessagePack.ReactiveProperty/ReactivePropertyResolver.cs b/Assets/Plugins/MessagePack/MessagePack.ReactiveProperty/ReactivePropertyResolver.cs deleted file mode 100644 index 97756b408..000000000 --- a/Assets/Plugins/MessagePack/MessagePack.ReactiveProperty/ReactivePropertyResolver.cs +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using System.Reflection; -using MessagePack.Formatters; -using UniRx; - -namespace MessagePack.ReactivePropertyExtension -{ - public class ReactivePropertyResolver : IFormatterResolver - { - public static readonly ReactivePropertyResolver Instance = new ReactivePropertyResolver(); - - private ReactivePropertyResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - internal static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - Formatter = (IMessagePackFormatter)ReactivePropertyResolverGetFormatterHelper.GetFormatter(typeof(T)); - } - } - } - - internal static class ReactivePropertyResolverGetFormatterHelper - { - private static readonly Dictionary FormatterMap = new Dictionary() - { - { typeof(ReactiveProperty<>), typeof(ReactivePropertyFormatter<>) }, - { typeof(ReactiveCollection<>), typeof(ReactiveCollectionFormatter<>) }, - }; - - internal static object GetFormatter(Type t) - { - if (t == typeof(Unit)) - { - return UnitFormatter.Instance; - } - else if (t == typeof(Unit?)) - { - return NullableUnitFormatter.Instance; - } - - TypeInfo ti = t.GetTypeInfo(); - - if (ti.IsGenericType) - { - Type genericType = ti.GetGenericTypeDefinition(); - Type formatterType; - if (FormatterMap.TryGetValue(genericType, out formatterType)) - { - return CreateInstance(formatterType, ti.GenericTypeArguments); - } - } - - return null; - } - - private static object CreateInstance(Type genericType, Type[] genericTypeArguments, params object[] arguments) - { - return Activator.CreateInstance(genericType.MakeGenericType(genericTypeArguments), arguments); - } - } -} diff --git a/Assets/Plugins/MessagePack/MessagePack.ReactiveProperty/ReactivePropertyResolver.cs.meta b/Assets/Plugins/MessagePack/MessagePack.ReactiveProperty/ReactivePropertyResolver.cs.meta deleted file mode 100644 index 3b6074ff2..000000000 --- a/Assets/Plugins/MessagePack/MessagePack.ReactiveProperty/ReactivePropertyResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9605defad6e10ba4e910ed209eb12b08 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/MessagePack.asmdef b/Assets/Plugins/MessagePack/MessagePack.asmdef deleted file mode 100644 index 6dc51d465..000000000 --- a/Assets/Plugins/MessagePack/MessagePack.asmdef +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "MessagePack", - "references": [ - "GUID:215598cda61754a45bc1f34e1d38d3af" - ], - "includePlatforms": [], - "excludePlatforms": [], - "allowUnsafeCode": true, - "overrideReferences": false, - "precompiledReferences": [], - "autoReferenced": true, - "defineConstraints": [], - "versionDefines": [], - "noEngineReferences": false -} \ No newline at end of file diff --git a/Assets/Plugins/MessagePack/MessagePack.asmdef.meta b/Assets/Plugins/MessagePack/MessagePack.asmdef.meta deleted file mode 100644 index f94a18979..000000000 --- a/Assets/Plugins/MessagePack/MessagePack.asmdef.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: ddc6e27fff8ae94ed9ccb00c84df6e24 -AssemblyDefinitionImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/MessagePackCode.cs b/Assets/Plugins/MessagePack/MessagePackCode.cs deleted file mode 100644 index 25374798c..000000000 --- a/Assets/Plugins/MessagePack/MessagePackCode.cs +++ /dev/null @@ -1,248 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using System.Text; - -namespace MessagePack -{ - /// - /// https://github.com/msgpack/msgpack/blob/master/spec.md#serialization-type-to-format-conversion. - /// -#if MESSAGEPACK_INTERNAL - internal -#else - public -#endif - enum MessagePackType : byte - { - Unknown = 0, - - Integer = 1, - Nil = 2, - Boolean = 3, - Float = 4, - String = 5, - Binary = 6, - Array = 7, - Map = 8, - Extension = 9, - } - - /// - /// The core type codes as defined by msgpack. - /// - /// -#if MESSAGEPACK_INTERNAL - internal -#else - public -#endif - static class MessagePackCode - { - public const byte MinFixInt = 0x00; // 0 - public const byte MaxFixInt = 0x7f; // 127 - public const byte MinFixMap = 0x80; // 128 - public const byte MaxFixMap = 0x8f; // 143 - public const byte MinFixArray = 0x90; // 144 - public const byte MaxFixArray = 0x9f; // 159 - public const byte MinFixStr = 0xa0; // 160 - public const byte MaxFixStr = 0xbf; // 191 - public const byte Nil = 0xc0; - public const byte NeverUsed = 0xc1; - public const byte False = 0xc2; - public const byte True = 0xc3; - public const byte Bin8 = 0xc4; - public const byte Bin16 = 0xc5; - public const byte Bin32 = 0xc6; - public const byte Ext8 = 0xc7; - public const byte Ext16 = 0xc8; - public const byte Ext32 = 0xc9; - public const byte Float32 = 0xca; - public const byte Float64 = 0xcb; - public const byte UInt8 = 0xcc; - public const byte UInt16 = 0xcd; - public const byte UInt32 = 0xce; - public const byte UInt64 = 0xcf; - public const byte Int8 = 0xd0; - public const byte Int16 = 0xd1; - public const byte Int32 = 0xd2; - public const byte Int64 = 0xd3; - public const byte FixExt1 = 0xd4; - public const byte FixExt2 = 0xd5; - public const byte FixExt4 = 0xd6; - public const byte FixExt8 = 0xd7; - public const byte FixExt16 = 0xd8; - public const byte Str8 = 0xd9; - public const byte Str16 = 0xda; - public const byte Str32 = 0xdb; - public const byte Array16 = 0xdc; - public const byte Array32 = 0xdd; - public const byte Map16 = 0xde; - public const byte Map32 = 0xdf; - public const byte MinNegativeFixInt = 0xe0; // 224 - public const byte MaxNegativeFixInt = 0xff; // 255 - - private static readonly MessagePackType[] TypeLookupTable = new MessagePackType[256]; - private static readonly string[] FormatNameTable = new string[256]; - - static MessagePackCode() - { - // Init Lookup Table - for (int i = MinFixInt; i <= MaxFixInt; i++) - { - TypeLookupTable[i] = MessagePackType.Integer; - FormatNameTable[i] = "positive fixint"; - } - - for (int i = MinFixMap; i <= MaxFixMap; i++) - { - TypeLookupTable[i] = MessagePackType.Map; - FormatNameTable[i] = "fixmap"; - } - - for (int i = MinFixArray; i <= MaxFixArray; i++) - { - TypeLookupTable[i] = MessagePackType.Array; - FormatNameTable[i] = "fixarray"; - } - - for (int i = MinFixStr; i <= MaxFixStr; i++) - { - TypeLookupTable[i] = MessagePackType.String; - FormatNameTable[i] = "fixstr"; - } - - TypeLookupTable[Nil] = MessagePackType.Nil; - TypeLookupTable[NeverUsed] = MessagePackType.Unknown; - TypeLookupTable[False] = MessagePackType.Boolean; - TypeLookupTable[True] = MessagePackType.Boolean; - TypeLookupTable[Bin8] = MessagePackType.Binary; - TypeLookupTable[Bin16] = MessagePackType.Binary; - TypeLookupTable[Bin32] = MessagePackType.Binary; - TypeLookupTable[Ext8] = MessagePackType.Extension; - TypeLookupTable[Ext16] = MessagePackType.Extension; - TypeLookupTable[Ext32] = MessagePackType.Extension; - TypeLookupTable[Float32] = MessagePackType.Float; - TypeLookupTable[Float64] = MessagePackType.Float; - TypeLookupTable[UInt8] = MessagePackType.Integer; - TypeLookupTable[UInt16] = MessagePackType.Integer; - TypeLookupTable[UInt32] = MessagePackType.Integer; - TypeLookupTable[UInt64] = MessagePackType.Integer; - TypeLookupTable[Int8] = MessagePackType.Integer; - TypeLookupTable[Int16] = MessagePackType.Integer; - TypeLookupTable[Int32] = MessagePackType.Integer; - TypeLookupTable[Int64] = MessagePackType.Integer; - TypeLookupTable[FixExt1] = MessagePackType.Extension; - TypeLookupTable[FixExt2] = MessagePackType.Extension; - TypeLookupTable[FixExt4] = MessagePackType.Extension; - TypeLookupTable[FixExt8] = MessagePackType.Extension; - TypeLookupTable[FixExt16] = MessagePackType.Extension; - TypeLookupTable[Str8] = MessagePackType.String; - TypeLookupTable[Str16] = MessagePackType.String; - TypeLookupTable[Str32] = MessagePackType.String; - TypeLookupTable[Array16] = MessagePackType.Array; - TypeLookupTable[Array32] = MessagePackType.Array; - TypeLookupTable[Map16] = MessagePackType.Map; - TypeLookupTable[Map32] = MessagePackType.Map; - - FormatNameTable[Nil] = "nil"; - FormatNameTable[NeverUsed] = "(never used)"; - FormatNameTable[False] = "false"; - FormatNameTable[True] = "true"; - FormatNameTable[Bin8] = "bin 8"; - FormatNameTable[Bin16] = "bin 16"; - FormatNameTable[Bin32] = "bin 32"; - FormatNameTable[Ext8] = "ext 8"; - FormatNameTable[Ext16] = "ext 16"; - FormatNameTable[Ext32] = "ext 32"; - FormatNameTable[Float32] = "float 32"; - FormatNameTable[Float64] = "float 64"; - FormatNameTable[UInt8] = "uint 8"; - FormatNameTable[UInt16] = "uint 16"; - FormatNameTable[UInt32] = "uint 32"; - FormatNameTable[UInt64] = "uint 64"; - FormatNameTable[Int8] = "int 8"; - FormatNameTable[Int16] = "int 16"; - FormatNameTable[Int32] = "int 32"; - FormatNameTable[Int64] = "int 64"; - FormatNameTable[FixExt1] = "fixext 1"; - FormatNameTable[FixExt2] = "fixext 2"; - FormatNameTable[FixExt4] = "fixext 4"; - FormatNameTable[FixExt8] = "fixext 8"; - FormatNameTable[FixExt16] = "fixext 16"; - FormatNameTable[Str8] = "str 8"; - FormatNameTable[Str16] = "str 16"; - FormatNameTable[Str32] = "str 32"; - FormatNameTable[Array16] = "array 16"; - FormatNameTable[Array32] = "array 32"; - FormatNameTable[Map16] = "map 16"; - FormatNameTable[Map32] = "map 32"; - - for (int i = MinNegativeFixInt; i <= MaxNegativeFixInt; i++) - { - TypeLookupTable[i] = MessagePackType.Integer; - FormatNameTable[i] = "negative fixint"; - } - } - - public static MessagePackType ToMessagePackType(byte code) - { - return TypeLookupTable[code]; - } - - public static string ToFormatName(byte code) - { - return FormatNameTable[code]; - } - - /// - /// Checks whether a given messagepack code represents an integer that might include a sign (i.e. might be a negative number). - /// - /// The messagepack code. - /// A boolean value. - internal static bool IsSignedInteger(byte code) - { - switch (code) - { - case Int8: - case Int16: - case Int32: - case Int64: - return true; - default: - return code >= MinNegativeFixInt && code <= MaxNegativeFixInt; - } - } - } - - /// - /// The officially defined messagepack extension type codes. - /// -#if MESSAGEPACK_INTERNAL - internal -#else - public -#endif - static class ReservedMessagePackExtensionTypeCode - { - public const sbyte DateTime = -1; - } - -#if MESSAGEPACK_INTERNAL - internal -#else - public -#endif - static class MessagePackRange - { - public const int MinFixNegativeInt = -32; - public const int MaxFixNegativeInt = -1; - public const int MaxFixPositiveInt = 127; - public const int MinFixStringLength = 0; - public const int MaxFixStringLength = 31; - public const int MaxFixMapCount = 15; - public const int MaxFixArrayCount = 15; - } -} diff --git a/Assets/Plugins/MessagePack/MessagePackCode.cs.meta b/Assets/Plugins/MessagePack/MessagePackCode.cs.meta deleted file mode 100644 index 296c8e42b..000000000 --- a/Assets/Plugins/MessagePack/MessagePackCode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d493a26c728a2e7d2abf11945f3486c3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/MessagePackCompression.cs b/Assets/Plugins/MessagePack/MessagePackCompression.cs deleted file mode 100644 index 1fb1a7229..000000000 --- a/Assets/Plugins/MessagePack/MessagePackCompression.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -namespace MessagePack -{ - /// - /// Identifies the various compression schemes which might be applied at the msgpack level. - /// - public enum MessagePackCompression - { - /// - /// No compression is applied at the msgpack level. - /// - None, - - /// - /// Compresses an entire msgpack sequence as a single lz4 block format. - /// This is the simple compression that achieves best compression ratio, - /// at the cost of copying the entire sequence when necessary to get contiguous memory. - /// - /// - /// Uses msgpack type code ext99 and is compatible with v1 of this library. - /// - /// - /// See also ThisLibraryExtensionTypeCodes.Lz4Block - /// - Lz4Block, - - /// - /// Compresses an entire msgpack sequence as a array of lz4 block format. - /// This is compressed/decompressed in chunks that do not consume LOH, - /// but the compression ratio is slightly sacrificed. - /// - /// - /// Uses msgpack type code ext98 in array. - /// - /// - /// See also ThisLibraryExtensionTypeCodes.Lz4BlockArray - /// - Lz4BlockArray, - } - -#pragma warning disable SA1649 // File name should match first type name - - /// - /// Extensions for . - /// - internal static class MessagePackCompressionExtensions - { - public static bool IsCompression(this MessagePackCompression compression) - { - return compression != MessagePackCompression.None; - } - } - -#pragma warning restore SA1649 // File name should match first type name -} diff --git a/Assets/Plugins/MessagePack/MessagePackCompression.cs.meta b/Assets/Plugins/MessagePack/MessagePackCompression.cs.meta deleted file mode 100644 index f5cf9b590..000000000 --- a/Assets/Plugins/MessagePack/MessagePackCompression.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 465ff1ba0b3de79669df07fa6a47971d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/MessagePackReader.cs b/Assets/Plugins/MessagePack/MessagePackReader.cs deleted file mode 100644 index ce94e841e..000000000 --- a/Assets/Plugins/MessagePack/MessagePackReader.cs +++ /dev/null @@ -1,1090 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Diagnostics; -using System.IO; -using System.Runtime.CompilerServices; -using System.Threading; -using MessagePack.Internal; - -namespace MessagePack -{ - /// - /// A primitive types reader for the MessagePack format. - /// - /// - /// The MessagePack spec.. - /// - /// Thrown when reading methods fail due to invalid data. - /// Thrown by reading methods when there are not enough bytes to read the required value. -#if MESSAGEPACK_INTERNAL - internal -#else - public -#endif - ref partial struct MessagePackReader - { - /// - /// The reader over the sequence. - /// - private SequenceReader reader; - - /// - /// Initializes a new instance of the struct. - /// - /// The buffer to read from. - public MessagePackReader(ReadOnlyMemory memory) - : this() - { - this.reader = new SequenceReader(memory); - this.Depth = 0; - } - - /// - /// Initializes a new instance of the struct. - /// - /// The sequence to read from. - public MessagePackReader(in ReadOnlySequence readOnlySequence) - : this() - { - this.reader = new SequenceReader(readOnlySequence); - this.Depth = 0; - } - - /// - /// Gets or sets the cancellation token for this deserialization operation. - /// - public CancellationToken CancellationToken { get; set; } - - /// - /// Gets or sets the present depth of the object graph being deserialized. - /// - public int Depth { get; set; } - - /// - /// Gets the originally supplied to the constructor. - /// - public ReadOnlySequence Sequence => this.reader.Sequence; - - /// - /// Gets the current position of the reader within . - /// - public SequencePosition Position => this.reader.Position; - - /// - /// Gets the number of bytes consumed by the reader. - /// - public long Consumed => this.reader.Consumed; - - /// - /// Gets a value indicating whether the reader is at the end of the sequence. - /// - public bool End => this.reader.End; - - /// - /// Gets a value indicating whether the reader position is pointing at a nil value. - /// - /// Thrown if the end of the sequence provided to the constructor is reached before the expected end of the data. - public bool IsNil => this.NextCode == MessagePackCode.Nil; - - /// - /// Gets the next message pack type to be read. - /// - public MessagePackType NextMessagePackType => MessagePackCode.ToMessagePackType(this.NextCode); - - /// - /// Gets the type of the next MessagePack block. - /// - /// Thrown if the end of the sequence provided to the constructor is reached before the expected end of the data. - /// - /// See for valid message pack codes and ranges. - /// - public byte NextCode - { - get - { - ThrowInsufficientBufferUnless(this.reader.TryPeek(out byte code)); - return code; - } - } - - /// - /// Initializes a new instance of the struct, - /// with the same settings as this one, but with its own buffer to read from. - /// - /// The sequence to read from. - /// The new reader. - public MessagePackReader Clone(in ReadOnlySequence readOnlySequence) => new MessagePackReader(readOnlySequence) - { - CancellationToken = this.CancellationToken, - Depth = this.Depth, - }; - - /// - /// Creates a new at this reader's current position. - /// The two readers may then be used independently without impacting each other. - /// - /// A new . - /// - /// Since this is a struct, copying it completely is as simple as returning itself - /// from a property that isn't a "ref return" property. - /// - public MessagePackReader CreatePeekReader() => this; - - /// - /// Advances the reader to the next MessagePack primitive to be read. - /// - /// - /// The entire primitive is skipped, including content of maps or arrays, or any other type with payloads. - /// To get the raw MessagePack sequence that was skipped, use instead. - /// - public void Skip() => ThrowInsufficientBufferUnless(this.TrySkip()); - - /// - /// Advances the reader to the next MessagePack primitive to be read. - /// - /// true if the entire structure beginning at the current is found in the ; false otherwise. - /// - /// The entire primitive is skipped, including content of maps or arrays, or any other type with payloads. - /// To get the raw MessagePack sequence that was skipped, use instead. - /// - internal bool TrySkip() - { - if (this.reader.Remaining == 0) - { - return false; - } - - byte code = this.NextCode; - switch (code) - { - case MessagePackCode.Nil: - case MessagePackCode.True: - case MessagePackCode.False: - return this.reader.TryAdvance(1); - case MessagePackCode.Int8: - case MessagePackCode.UInt8: - return this.reader.TryAdvance(2); - case MessagePackCode.Int16: - case MessagePackCode.UInt16: - return this.reader.TryAdvance(3); - case MessagePackCode.Int32: - case MessagePackCode.UInt32: - case MessagePackCode.Float32: - return this.reader.TryAdvance(5); - case MessagePackCode.Int64: - case MessagePackCode.UInt64: - case MessagePackCode.Float64: - return this.reader.TryAdvance(9); - case MessagePackCode.Map16: - case MessagePackCode.Map32: - return this.TrySkipNextMap(); - case MessagePackCode.Array16: - case MessagePackCode.Array32: - return this.TrySkipNextArray(); - case MessagePackCode.Str8: - case MessagePackCode.Str16: - case MessagePackCode.Str32: - return this.reader.TryAdvance(this.GetStringLengthInBytes()); - case MessagePackCode.Bin8: - case MessagePackCode.Bin16: - case MessagePackCode.Bin32: - return this.reader.TryAdvance(this.GetBytesLength()); - case MessagePackCode.FixExt1: - case MessagePackCode.FixExt2: - case MessagePackCode.FixExt4: - case MessagePackCode.FixExt8: - case MessagePackCode.FixExt16: - case MessagePackCode.Ext8: - case MessagePackCode.Ext16: - case MessagePackCode.Ext32: - return this.TryReadExtensionFormatHeader(out ExtensionHeader header) && this.reader.TryAdvance(header.Length); - default: - if ((code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) || - (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt)) - { - return this.reader.TryAdvance(1); - } - - if (code >= MessagePackCode.MinFixMap && code <= MessagePackCode.MaxFixMap) - { - return this.TrySkipNextMap(); - } - - if (code >= MessagePackCode.MinFixArray && code <= MessagePackCode.MaxFixArray) - { - return this.TrySkipNextArray(); - } - - if (code >= MessagePackCode.MinFixStr && code <= MessagePackCode.MaxFixStr) - { - return this.reader.TryAdvance(this.GetStringLengthInBytes()); - } - - // We don't actually expect to ever hit this point, since every code is supported. - Debug.Fail("Missing handler for code: " + code); - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads a value. - /// - /// A nil value. - public Nil ReadNil() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - return code == MessagePackCode.Nil - ? Nil.Default - : throw ThrowInvalidCode(code); - } - - /// - /// Reads nil if it is the next token. - /// - /// true if the next token was nil; false otherwise. - /// Thrown if the end of the sequence provided to the constructor is reached before the expected end of the data. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool TryReadNil() - { - if (this.NextCode == MessagePackCode.Nil) - { - this.reader.Advance(1); - return true; - } - - return false; - } - - /// - /// Reads a sequence of bytes without any decoding. - /// - /// The number of bytes to read. - /// The sequence of bytes read. - public ReadOnlySequence ReadRaw(long length) - { - try - { - ReadOnlySequence result = this.reader.Sequence.Slice(this.reader.Position, length); - this.reader.Advance(length); - return result; - } - catch (ArgumentOutOfRangeException ex) - { - throw ThrowNotEnoughBytesException(ex); - } - } - - /// - /// Reads the next MessagePack primitive. - /// - /// The raw MessagePack sequence. - /// - /// The entire primitive is read, including content of maps or arrays, or any other type with payloads. - /// - public ReadOnlySequence ReadRaw() - { - SequencePosition initialPosition = this.Position; - this.Skip(); - return this.Sequence.Slice(initialPosition, this.Position); - } - - /// - /// Read an array header from - /// , - /// , or - /// some built-in code between and . - /// - /// - /// Thrown if the header cannot be read in the bytes left in the - /// or if it is clear that there are insufficient bytes remaining after the header to include all the elements the header claims to be there. - /// - /// Thrown if a code other than an array header is encountered. - public int ReadArrayHeader() - { - ThrowInsufficientBufferUnless(this.TryReadArrayHeader(out int count)); - - // Protect against corrupted or mischievious data that may lead to allocating way too much memory. - // We allow for each primitive to be the minimal 1 byte in size. - // Formatters that know each element is larger can optionally add a stronger check. - ThrowInsufficientBufferUnless(this.reader.Remaining >= count); - - return count; - } - - /// - /// Reads an array header from - /// , - /// , or - /// some built-in code between and - /// if there is sufficient buffer to read it. - /// - /// Receives the number of elements in the array if the entire array header could be read. - /// true if there was sufficient buffer and an array header was found; false if the buffer incompletely describes an array header. - /// Thrown if a code other than an array header is encountered. - /// - /// When this method returns false the position of the reader is left in an undefined position. - /// The caller is expected to recreate the reader (presumably with a longer sequence to read from) before continuing. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool TryReadArrayHeader(out int count) - { - count = -1; - if (!this.reader.TryRead(out byte code)) - { - return false; - } - - switch (code) - { - case MessagePackCode.Array16: - if (!this.reader.TryReadBigEndian(out short shortValue)) - { - return false; - } - - count = unchecked((ushort)shortValue); - break; - case MessagePackCode.Array32: - if (!this.reader.TryReadBigEndian(out int intValue)) - { - return false; - } - - count = intValue; - break; - default: - if (code >= MessagePackCode.MinFixArray && code <= MessagePackCode.MaxFixArray) - { - count = code & 0xF; - break; - } - - throw ThrowInvalidCode(code); - } - - return true; - } - - /// - /// Read a map header from - /// , - /// , or - /// some built-in code between and . - /// - /// The number of key=value pairs in the map. - /// - /// Thrown if the header cannot be read in the bytes left in the - /// or if it is clear that there are insufficient bytes remaining after the header to include all the elements the header claims to be there. - /// - /// Thrown if a code other than an map header is encountered. - public int ReadMapHeader() - { - ThrowInsufficientBufferUnless(this.TryReadMapHeader(out int count)); - - // Protect against corrupted or mischievious data that may lead to allocating way too much memory. - // We allow for each primitive to be the minimal 1 byte in size, and we have a key=value map, so that's 2 bytes. - // Formatters that know each element is larger can optionally add a stronger check. - ThrowInsufficientBufferUnless(this.reader.Remaining >= count * 2); - - return count; - } - - /// - /// Reads a map header from - /// , - /// , or - /// some built-in code between and - /// if there is sufficient buffer to read it. - /// - /// Receives the number of key=value pairs in the map if the entire map header can be read. - /// true if there was sufficient buffer and a map header was found; false if the buffer incompletely describes an map header. - /// Thrown if a code other than an map header is encountered. - /// - /// When this method returns false the position of the reader is left in an undefined position. - /// The caller is expected to recreate the reader (presumably with a longer sequence to read from) before continuing. - /// - public bool TryReadMapHeader(out int count) - { - count = -1; - if (!this.reader.TryRead(out byte code)) - { - return false; - } - - switch (code) - { - case MessagePackCode.Map16: - if (!this.reader.TryReadBigEndian(out short shortValue)) - { - return false; - } - - count = unchecked((ushort)shortValue); - break; - case MessagePackCode.Map32: - if (!this.reader.TryReadBigEndian(out int intValue)) - { - return false; - } - - count = intValue; - break; - default: - if (code >= MessagePackCode.MinFixMap && code <= MessagePackCode.MaxFixMap) - { - count = (byte)(code & 0xF); - break; - } - - throw ThrowInvalidCode(code); - } - - return true; - } - - /// - /// Reads a boolean value from either a or . - /// - /// The value. - public bool ReadBoolean() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - switch (code) - { - case MessagePackCode.True: - return true; - case MessagePackCode.False: - return false; - default: - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads a from any of: - /// , - /// , - /// or anything between and . - /// - /// A character. - public char ReadChar() => (char)this.ReadUInt16(); - - /// - /// Reads an value from any value encoded with: - /// , - /// , - /// , - /// , - /// , - /// , - /// , - /// , - /// , - /// or some value between and , - /// or some value between and . - /// - /// The value. - public unsafe float ReadSingle() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - switch (code) - { - case MessagePackCode.Float32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out float floatValue)); - return floatValue; - case MessagePackCode.Float64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out double doubleValue)); - return (float)doubleValue; - case MessagePackCode.Int8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out sbyte sbyteValue)); - return sbyteValue; - case MessagePackCode.Int16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortValue)); - return shortValue; - case MessagePackCode.Int32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intValue)); - return intValue; - case MessagePackCode.Int64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longValue)); - return longValue; - case MessagePackCode.UInt8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteValue)); - return byteValue; - case MessagePackCode.UInt16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ushort ushortValue)); - return ushortValue; - case MessagePackCode.UInt32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out uint uintValue)); - return uintValue; - case MessagePackCode.UInt64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ulong ulongValue)); - return ulongValue; - default: - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return unchecked((sbyte)code); - } - else if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return code; - } - - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads an value from any value encoded with: - /// , - /// , - /// , - /// , - /// , - /// , - /// , - /// , - /// , - /// , - /// or some value between and , - /// or some value between and . - /// - /// The value. - public unsafe double ReadDouble() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - switch (code) - { - case MessagePackCode.Float64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out double doubleValue)); - return doubleValue; - case MessagePackCode.Float32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out float floatValue)); - return floatValue; - case MessagePackCode.Int8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteValue)); - return unchecked((sbyte)byteValue); - case MessagePackCode.Int16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortValue)); - return shortValue; - case MessagePackCode.Int32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intValue)); - return intValue; - case MessagePackCode.Int64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longValue)); - return longValue; - case MessagePackCode.UInt8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byteValue)); - return byteValue; - case MessagePackCode.UInt16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out shortValue)); - return unchecked((ushort)shortValue); - case MessagePackCode.UInt32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out intValue)); - return unchecked((uint)intValue); - case MessagePackCode.UInt64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out longValue)); - return unchecked((ulong)longValue); - default: - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return unchecked((sbyte)code); - } - else if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return code; - } - - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads a from a value encoded with - /// , - /// , or - /// . - /// Expects extension type code . - /// - /// The value. - public DateTime ReadDateTime() => this.ReadDateTime(this.ReadExtensionFormatHeader()); - - /// - /// Reads a from a value encoded with - /// , - /// , - /// . - /// Expects extension type code . - /// - /// The extension header that was already read. - /// The value. - public DateTime ReadDateTime(ExtensionHeader header) - { - if (header.TypeCode != ReservedMessagePackExtensionTypeCode.DateTime) - { - throw new MessagePackSerializationException(string.Format("Extension TypeCode is invalid. typeCode: {0}", header.TypeCode)); - } - - switch (header.Length) - { - case 4: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intValue)); - return DateTimeConstants.UnixEpoch.AddSeconds(unchecked((uint)intValue)); - case 8: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longValue)); - ulong ulongValue = unchecked((ulong)longValue); - long nanoseconds = (long)(ulongValue >> 34); - ulong seconds = ulongValue & 0x00000003ffffffffL; - return DateTimeConstants.UnixEpoch.AddSeconds(seconds).AddTicks(nanoseconds / DateTimeConstants.NanosecondsPerTick); - case 12: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out intValue)); - nanoseconds = unchecked((uint)intValue); - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out longValue)); - return DateTimeConstants.UnixEpoch.AddSeconds(longValue).AddTicks(nanoseconds / DateTimeConstants.NanosecondsPerTick); - default: - throw new MessagePackSerializationException($"Length of extension was {header.Length}. Either 4 or 8 were expected."); - } - } - - /// - /// Reads a span of bytes, whose length is determined by a header of one of these types: - /// , - /// , - /// , - /// or to support OldSpec compatibility: - /// , - /// , - /// or something beteween and . - /// - /// - /// A sequence of bytes, or null if the read token is . - /// The data is a slice from the original sequence passed to this reader's constructor. - /// - public ReadOnlySequence? ReadBytes() - { - if (this.TryReadNil()) - { - return null; - } - - int length = this.GetBytesLength(); - ThrowInsufficientBufferUnless(this.reader.Remaining >= length); - ReadOnlySequence result = this.reader.Sequence.Slice(this.reader.Position, length); - this.reader.Advance(length); - return result; - } - - /// - /// Reads a string of bytes, whose length is determined by a header of one of these types: - /// , - /// , - /// , - /// or a code between and . - /// - /// - /// The sequence of bytes, or null if the read token is . - /// The data is a slice from the original sequence passed to this reader's constructor. - /// - public ReadOnlySequence? ReadStringSequence() - { - if (this.TryReadNil()) - { - return null; - } - - int length = this.GetStringLengthInBytes(); - ThrowInsufficientBufferUnless(this.reader.Remaining >= length); - ReadOnlySequence result = this.reader.Sequence.Slice(this.reader.Position, length); - this.reader.Advance(length); - return result; - } - - /// - /// Reads a string of bytes, whose length is determined by a header of one of these types: - /// , - /// , - /// , - /// or a code between and . - /// - /// Receives the span to the string. - /// - /// true if the string is contiguous in memory such that it could be set as a single span. - /// false if the read token is or the string is not in a contiguous span. - /// - /// - /// Callers should generally be prepared for a false result and failover to calling - /// which can represent a null result and handle strings that are not contiguous in memory. - /// - public bool TryReadStringSpan(out ReadOnlySpan span) - { - if (this.IsNil) - { - span = default; - return false; - } - - long oldPosition = this.reader.Consumed; - int length = this.GetStringLengthInBytes(); - ThrowInsufficientBufferUnless(this.reader.Remaining >= length); - - if (this.reader.CurrentSpanIndex + length <= this.reader.CurrentSpan.Length) - { - span = this.reader.CurrentSpan.Slice(this.reader.CurrentSpanIndex, length); - this.reader.Advance(length); - return true; - } - else - { - this.reader.Rewind(this.reader.Consumed - oldPosition); - span = default; - return false; - } - } - - /// - /// Reads a string, whose length is determined by a header of one of these types: - /// , - /// , - /// , - /// or a code between and . - /// - /// A string, or null if the current msgpack token is . - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public string ReadString() - { - if (this.TryReadNil()) - { - return null; - } - - int byteLength = this.GetStringLengthInBytes(); - - ReadOnlySpan unreadSpan = this.reader.UnreadSpan; - //UnityEngine.Debug.Log(reader.CurrentSpan[0]); - //UnityEngine.Debug.Log(unreadSpan[0]); - if (unreadSpan.Length >= byteLength) - { - // Fast path: all bytes to decode appear in the same span. - string value = StringEncoding.UTF8.GetString(unreadSpan.Slice(0, byteLength)); - this.reader.Advance(byteLength); - return value; - } - else - { - return this.ReadStringSlow(byteLength); - } - } - - /// - /// Reads an extension format header, based on one of these codes: - /// , - /// , - /// , - /// , - /// , - /// , - /// , or - /// . - /// - /// The extension header. - /// - /// Thrown if the header cannot be read in the bytes left in the - /// or if it is clear that there are insufficient bytes remaining after the header to include all the bytes the header claims to be there. - /// - /// Thrown if a code other than an extension format header is encountered. - public ExtensionHeader ReadExtensionFormatHeader() - { - ThrowInsufficientBufferUnless(this.TryReadExtensionFormatHeader(out ExtensionHeader header)); - - // Protect against corrupted or mischievious data that may lead to allocating way too much memory. - ThrowInsufficientBufferUnless(this.reader.Remaining >= header.Length); - - return header; - } - - /// - /// Reads an extension format header, based on one of these codes: - /// , - /// , - /// , - /// , - /// , - /// , - /// , or - /// - /// if there is sufficient buffer to read it. - /// - /// Receives the extension header if the remaining bytes in the fully describe the header. - /// The number of key=value pairs in the map. - /// Thrown if a code other than an extension format header is encountered. - /// - /// When this method returns false the position of the reader is left in an undefined position. - /// The caller is expected to recreate the reader (presumably with a longer sequence to read from) before continuing. - /// - public bool TryReadExtensionFormatHeader(out ExtensionHeader extensionHeader) - { - extensionHeader = default; - if (!this.reader.TryRead(out byte code)) - { - return false; - } - - uint length; - switch (code) - { - case MessagePackCode.FixExt1: - length = 1; - break; - case MessagePackCode.FixExt2: - length = 2; - break; - case MessagePackCode.FixExt4: - length = 4; - break; - case MessagePackCode.FixExt8: - length = 8; - break; - case MessagePackCode.FixExt16: - length = 16; - break; - case MessagePackCode.Ext8: - if (!this.reader.TryRead(out byte byteLength)) - { - return false; - } - - length = byteLength; - break; - case MessagePackCode.Ext16: - if (!this.reader.TryReadBigEndian(out short shortLength)) - { - return false; - } - - length = unchecked((ushort)shortLength); - break; - case MessagePackCode.Ext32: - if (!this.reader.TryReadBigEndian(out int intLength)) - { - return false; - } - - length = unchecked((uint)intLength); - break; - default: - throw ThrowInvalidCode(code); - } - - if (!this.reader.TryRead(out byte typeCode)) - { - return false; - } - - extensionHeader = new ExtensionHeader(unchecked((sbyte)typeCode), length); - return true; - } - - /// - /// Reads an extension format header and data, based on one of these codes: - /// , - /// , - /// , - /// , - /// , - /// , - /// , or - /// . - /// - /// - /// The extension format. - /// The data is a slice from the original sequence passed to this reader's constructor. - /// - public ExtensionResult ReadExtensionFormat() - { - ExtensionHeader header = this.ReadExtensionFormatHeader(); - try - { - ReadOnlySequence data = this.reader.Sequence.Slice(this.reader.Position, header.Length); - this.reader.Advance(header.Length); - return new ExtensionResult(header.TypeCode, data); - } - catch (ArgumentOutOfRangeException ex) - { - throw ThrowNotEnoughBytesException(ex); - } - } - - /// - /// Throws an exception indicating that there aren't enough bytes remaining in the buffer to store - /// the promised data. - /// - private static EndOfStreamException ThrowNotEnoughBytesException() => throw new EndOfStreamException(); - - /// - /// Throws an exception indicating that there aren't enough bytes remaining in the buffer to store - /// the promised data. - /// - private static EndOfStreamException ThrowNotEnoughBytesException(Exception innerException) => throw new EndOfStreamException(new EndOfStreamException().Message, innerException); - - /// - /// Throws an explaining an unexpected code was encountered. - /// - /// The code that was encountered. - /// Nothing. This method always throws. - private static Exception ThrowInvalidCode(byte code) - { - throw new MessagePackSerializationException(string.Format("Unexpected msgpack code {0} ({1}) encountered.", code, MessagePackCode.ToFormatName(code))); - } - - /// - /// Throws if a condition is false. - /// - /// A boolean value. - /// Thrown if is false. - private static void ThrowInsufficientBufferUnless(bool condition) - { - if (!condition) - { - ThrowNotEnoughBytesException(); - } - } - - private int GetBytesLength() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - // In OldSpec mode, Bin didn't exist, so Str was used. Str8 didn't exist either. - int length; - switch (code) - { - case MessagePackCode.Bin8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteLength)); - length = byteLength; - break; - case MessagePackCode.Bin16: - case MessagePackCode.Str16: // OldSpec compatibility - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortLength)); - length = unchecked((ushort)shortLength); - break; - case MessagePackCode.Bin32: - case MessagePackCode.Str32: // OldSpec compatibility - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out length)); - break; - default: - // OldSpec compatibility - if (code >= MessagePackCode.MinFixStr && code <= MessagePackCode.MaxFixStr) - { - length = code & 0x1F; - break; - } - - throw ThrowInvalidCode(code); - } - - return length; - } - - /// - /// Gets the length of the next string. - /// - /// The length of the next string. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private int GetStringLengthInBytes() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - if (code >= MessagePackCode.MinFixStr && code <= MessagePackCode.MaxFixStr) - { - return code & 0x1F; - } - - return this.GetStringLengthInBytesSlow(code); - } - - private int GetStringLengthInBytesSlow(byte code) - { - switch (code) - { - case MessagePackCode.Str8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteValue)); - return byteValue; - case MessagePackCode.Str16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortValue)); - return unchecked((ushort)shortValue); - case MessagePackCode.Str32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intValue)); - return intValue; - default: - if (code >= MessagePackCode.MinFixStr && code <= MessagePackCode.MaxFixStr) - { - return code & 0x1F; - } - - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads a string assuming that it is spread across multiple spans in the . - /// - /// The length of the string to be decoded, in bytes. - /// The decoded string. - private string ReadStringSlow(int byteLength) - { - ThrowInsufficientBufferUnless(this.reader.Remaining >= byteLength); - - // We need to decode bytes incrementally across multiple spans. - int maxCharLength = StringEncoding.UTF8.GetMaxCharCount(byteLength); - char[] charArray = ArrayPool.Shared.Rent(maxCharLength); - System.Text.Decoder decoder = StringEncoding.UTF8.GetDecoder(); - - int remainingByteLength = byteLength; - int initializedChars = 0; - while (remainingByteLength > 0) - { - int bytesRead = Math.Min(remainingByteLength, this.reader.UnreadSpan.Length); - remainingByteLength -= bytesRead; - bool flush = remainingByteLength == 0; -#if NETCOREAPP2_1 - initializedChars += decoder.GetChars(this.reader.UnreadSpan.Slice(0, bytesRead), charArray.AsSpan(initializedChars), flush); -#else - unsafe - { - fixed (byte* pUnreadSpan = this.reader.UnreadSpan) - fixed (char* pCharArray = &charArray[initializedChars]) - { - initializedChars += decoder.GetChars(pUnreadSpan, bytesRead, pCharArray, charArray.Length - initializedChars, flush); - } - } -#endif - this.reader.Advance(bytesRead); - } - - string value = new string(charArray, 0, initializedChars); - ArrayPool.Shared.Return(charArray); - return value; - } - - private bool TrySkipNextArray() => this.TryReadArrayHeader(out int count) && this.TrySkip(count); - - private bool TrySkipNextMap() => this.TryReadMapHeader(out int count) && this.TrySkip(count * 2); - - private bool TrySkip(int count) - { - for (int i = 0; i < count; i++) - { - if (!this.TrySkip()) - { - return false; - } - } - - return true; - } - } -} diff --git a/Assets/Plugins/MessagePack/MessagePackReader.cs.meta b/Assets/Plugins/MessagePack/MessagePackReader.cs.meta deleted file mode 100644 index b74580f0a..000000000 --- a/Assets/Plugins/MessagePack/MessagePackReader.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 83f0995886fa5ea1fab77523785e1982 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/MessagePackSecurity.cs b/Assets/Plugins/MessagePack/MessagePackSecurity.cs deleted file mode 100644 index c362f9157..000000000 --- a/Assets/Plugins/MessagePack/MessagePackSecurity.cs +++ /dev/null @@ -1,417 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Runtime.ExceptionServices; -using MessagePack.Formatters; -using MessagePack.Internal; - -namespace MessagePack -{ - /// - /// Settings related to security, particularly relevant when deserializing data from untrusted sources. - /// - public class MessagePackSecurity - { - /// - /// Gets an instance preconfigured with settings that omit all protections. Useful for deserializing fully-trusted and valid msgpack sequences. - /// - public static readonly MessagePackSecurity TrustedData = new MessagePackSecurity(); - - /// - /// Gets an instance preconfigured with protections applied with reasonable settings for deserializing untrusted msgpack sequences. - /// - public static readonly MessagePackSecurity UntrustedData = new MessagePackSecurity - { - HashCollisionResistant = true, - MaximumObjectGraphDepth = 500, - }; - - private readonly ObjectFallbackEqualityComparer objectFallbackEqualityComparer; - - private MessagePackSecurity() - { - this.objectFallbackEqualityComparer = new ObjectFallbackEqualityComparer(this); - } - - /// - /// Initializes a new instance of the class - /// with properties copied from a provided template. - /// - /// The template to copy from. - protected MessagePackSecurity(MessagePackSecurity copyFrom) - : this() - { - if (copyFrom is null) - { - throw new ArgumentNullException(nameof(copyFrom)); - } - - this.HashCollisionResistant = copyFrom.HashCollisionResistant; - this.MaximumObjectGraphDepth = copyFrom.MaximumObjectGraphDepth; - } - - /// - /// Gets a value indicating whether data to be deserialized is untrusted and thus should not be allowed to create - /// dictionaries or other hash-based collections unless the hashed type has a hash collision resistant implementation available. - /// This can mitigate some denial of service attacks when deserializing untrusted code. - /// - /// - /// The value is false for and true for . - /// - public bool HashCollisionResistant { get; private set; } - - /// - /// Gets the maximum depth of an object graph that may be deserialized. - /// - /// - /// - /// This value can be reduced to avoid a stack overflow that would crash the process when deserializing a msgpack sequence designed to cause deep recursion. - /// A very short callstack on a thread with 1MB of total stack space might deserialize ~2000 nested arrays before crashing due to a stack overflow. - /// Since stack space occupied may vary by the kind of object deserialized, a conservative value for this property to defend against stack overflow attacks might be 500. - /// - /// - public int MaximumObjectGraphDepth { get; private set; } = int.MaxValue; - - /// - /// Gets a copy of these options with the property set to a new value. - /// - /// The new value for the property. - /// The new instance; or the original if the value is unchanged. - public MessagePackSecurity WithMaximumObjectGraphDepth(int maximumObjectGraphDepth) - { - if (this.MaximumObjectGraphDepth == maximumObjectGraphDepth) - { - return this; - } - - var clone = this.Clone(); - clone.MaximumObjectGraphDepth = maximumObjectGraphDepth; - return clone; - } - - /// - /// Gets a copy of these options with the property set to a new value. - /// - /// The new value for the property. - /// The new instance; or the original if the value is unchanged. - public MessagePackSecurity WithHashCollisionResistant(bool hashCollisionResistant) - { - if (this.HashCollisionResistant == hashCollisionResistant) - { - return this; - } - - var clone = this.Clone(); - clone.HashCollisionResistant = hashCollisionResistant; - return clone; - } - - /// - /// Gets an that is suitable to use with a hash-based collection. - /// - /// The type of key that will be hashed in the collection. - /// The to use. - /// - /// When is active, this will be a collision resistant instance which may reject certain key types. - /// When is not active, this will be . - /// - public IEqualityComparer GetEqualityComparer() - { - return this.HashCollisionResistant ? GetHashCollisionResistantEqualityComparer() : EqualityComparer.Default; - } - - /// - /// Gets an that is suitable to use with a hash-based collection. - /// - /// The to use. - /// - /// When is active, this will be a collision resistant instance which may reject certain key types. - /// When is not active, this will be . - /// - public IEqualityComparer GetEqualityComparer() - { - return this.HashCollisionResistant ? GetHashCollisionResistantEqualityComparer() : EqualityComparer.Default; - } - - /// - /// Returns a hash collision resistant equality comparer. - /// - /// The type of key that will be hashed in the collection. - /// A hash collision resistant equality comparer. - protected virtual IEqualityComparer GetHashCollisionResistantEqualityComparer() - { - IEqualityComparer result = null; - if (typeof(T).GetTypeInfo().IsEnum) - { - Type underlyingType = typeof(T).GetTypeInfo().GetEnumUnderlyingType(); - result = - underlyingType == typeof(sbyte) ? CollisionResistantHasher.Instance : - underlyingType == typeof(byte) ? CollisionResistantHasher.Instance : - underlyingType == typeof(short) ? CollisionResistantHasher.Instance : - underlyingType == typeof(ushort) ? CollisionResistantHasher.Instance : - underlyingType == typeof(int) ? CollisionResistantHasher.Instance : - underlyingType == typeof(uint) ? CollisionResistantHasher.Instance : - null; - } - else - { - // For anything 32-bits and under, our fallback base secure hasher is usually adequate since it makes the hash unpredictable. - // We should have special implementations for any value that is larger than 32-bits in order to make sure - // that all the data gets hashed securely rather than trivially and predictably compressed into 32-bits before being hashed. - // We also have to specially handle some 32-bit types (e.g. float) where multiple in-memory representations should hash to the same value. - // Any type supported by the PrimitiveObjectFormatter should be added here if supporting it as a key in a collection makes sense. - result = - // 32-bits or smaller: - typeof(T) == typeof(bool) ? CollisionResistantHasher.Instance : - typeof(T) == typeof(char) ? CollisionResistantHasher.Instance : - typeof(T) == typeof(sbyte) ? CollisionResistantHasher.Instance : - typeof(T) == typeof(byte) ? CollisionResistantHasher.Instance : - typeof(T) == typeof(short) ? CollisionResistantHasher.Instance : - typeof(T) == typeof(ushort) ? CollisionResistantHasher.Instance : - typeof(T) == typeof(int) ? CollisionResistantHasher.Instance : - typeof(T) == typeof(uint) ? CollisionResistantHasher.Instance : - - // Larger than 32-bits (or otherwise require special handling): - typeof(T) == typeof(long) ? (IEqualityComparer)Int64EqualityComparer.Instance : - typeof(T) == typeof(ulong) ? (IEqualityComparer)UInt64EqualityComparer.Instance : - typeof(T) == typeof(float) ? (IEqualityComparer)SingleEqualityComparer.Instance : - typeof(T) == typeof(double) ? (IEqualityComparer)DoubleEqualityComparer.Instance : - typeof(T) == typeof(string) ? (IEqualityComparer)StringEqualityComparer.Instance : - typeof(T) == typeof(Guid) ? (IEqualityComparer)GuidEqualityComparer.Instance : - typeof(T) == typeof(DateTime) ? (IEqualityComparer)DateTimeEqualityComparer.Instance : - typeof(T) == typeof(DateTimeOffset) ? (IEqualityComparer)DateTimeOffsetEqualityComparer.Instance : - typeof(T) == typeof(object) ? (IEqualityComparer)this.objectFallbackEqualityComparer : - null; - } - - // Any type we don't explicitly whitelist here shouldn't be allowed to use as the key in a hash-based collection since it isn't known to be hash resistant. - // This method can of course be overridden to add more hash collision resistant type support, or the deserializing party can indicate that the data is Trusted - // so that this method doesn't even get called. - return result ?? throw new TypeAccessException($"No hash-resistant equality comparer available for type: {typeof(T)}"); - } - - /// - /// Checks the depth of the deserializing graph and increments it by 1. - /// - /// The reader that is involved in deserialization. - /// - /// Callers should decrement after exiting that edge in the graph. - /// - /// Thrown if is already at or exceeds . - /// - /// Rather than wrap the body of every method, - /// this should wrap *calls* to these methods. They need not appear in pure "thunk" methods that simply delegate the deserialization to another formatter. - /// In this way, we can avoid repeatedly incrementing and decrementing the counter when deserializing each element of a collection. - /// - public void DepthStep(ref MessagePackReader reader) - { - if (reader.Depth >= this.MaximumObjectGraphDepth) - { - throw new InsufficientExecutionStackException($"This msgpack sequence has an object graph that exceeds the maximum depth allowed of {MaximumObjectGraphDepth}."); - } - - reader.Depth++; - } - - /// - /// Returns a hash collision resistant equality comparer. - /// - /// A hash collision resistant equality comparer. - protected virtual IEqualityComparer GetHashCollisionResistantEqualityComparer() => (IEqualityComparer)this.GetHashCollisionResistantEqualityComparer(); - - /// - /// Creates a new instance that is a copy of this one. - /// - /// - /// Derived types should override this method to instantiate their own derived type. - /// - protected virtual MessagePackSecurity Clone() => new MessagePackSecurity(this); - - /// - /// A hash collision resistant implementation of . - /// - /// The type of key that will be hashed. - private class CollisionResistantHasher : IEqualityComparer, IEqualityComparer - { - internal static readonly CollisionResistantHasher Instance = new CollisionResistantHasher(); - - public bool Equals(T x, T y) => EqualityComparer.Default.Equals(x, y); - - bool IEqualityComparer.Equals(object x, object y) => ((IEqualityComparer)EqualityComparer.Default).Equals(x, y); - - public int GetHashCode(object obj) => this.GetHashCode((T)obj); - - public virtual int GetHashCode(T value) => HashCode.Combine(value); - } - - /// - /// A special hash-resistent equality comparer that defers picking the actual implementation - /// till it can check the runtime type of each value to be hashed. - /// - private class ObjectFallbackEqualityComparer : IEqualityComparer, IEqualityComparer - { - private static readonly MethodInfo GetHashCollisionResistantEqualityComparerOpenGenericMethod = typeof(MessagePackSecurity).GetTypeInfo().DeclaredMethods.Single(m => m.Name == nameof(MessagePackSecurity.GetHashCollisionResistantEqualityComparer) && m.IsGenericMethod); - private readonly MessagePackSecurity security; - private readonly ThreadsafeTypeKeyHashTable equalityComparerCache = new ThreadsafeTypeKeyHashTable(); - - internal ObjectFallbackEqualityComparer(MessagePackSecurity security) - { - this.security = security ?? throw new ArgumentNullException(nameof(security)); - } - - bool IEqualityComparer.Equals(object x, object y) => EqualityComparer.Default.Equals(x, y); - - bool IEqualityComparer.Equals(object x, object y) => ((IEqualityComparer)EqualityComparer.Default).Equals(x, y); - - public int GetHashCode(object value) - { - if (value is null) - { - return 0; - } - - Type valueType = value.GetType(); - - // Take care to avoid recursion. - if (valueType == typeof(object)) - { - // We can trust object.GetHashCode() to be collision resistant. - return value.GetHashCode(); - } - - if (!equalityComparerCache.TryGetValue(valueType, out IEqualityComparer equalityComparer)) - { - try - { - equalityComparer = (IEqualityComparer)GetHashCollisionResistantEqualityComparerOpenGenericMethod.MakeGenericMethod(valueType).Invoke(this.security, Array.Empty()); - } - catch (TargetInvocationException ex) - { - ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); - } - - equalityComparerCache.TryAdd(valueType, equalityComparer); - } - - return equalityComparer.GetHashCode(value); - } - } - - private class UInt64EqualityComparer : CollisionResistantHasher - { - internal static new readonly UInt64EqualityComparer Instance = new UInt64EqualityComparer(); - - public override int GetHashCode(ulong value) => HashCode.Combine((uint)(value >> 32), unchecked((uint)value)); - } - - private class Int64EqualityComparer : CollisionResistantHasher - { - internal static new readonly Int64EqualityComparer Instance = new Int64EqualityComparer(); - - public override int GetHashCode(long value) => HashCode.Combine((int)(value >> 32), unchecked((int)value)); - } - - private class SingleEqualityComparer : CollisionResistantHasher - { - internal static new readonly SingleEqualityComparer Instance = new SingleEqualityComparer(); - - public override unsafe int GetHashCode(float value) - { - // Special check for 0.0 so that the hash of 0.0 and -0.0 will equal. - if (value == 0.0f) - { - return HashCode.Combine(0); - } - - // Standardize on the binary representation of NaN prior to hashing. - if (float.IsNaN(value)) - { - value = float.NaN; - } - - long l = *(long*)&value; - return HashCode.Combine((int)(l >> 32), unchecked((int)l)); - } - } - - private class DoubleEqualityComparer : CollisionResistantHasher - { - internal static new readonly DoubleEqualityComparer Instance = new DoubleEqualityComparer(); - - public override unsafe int GetHashCode(double value) - { - // Special check for 0.0 so that the hash of 0.0 and -0.0 will equal. - if (value == 0.0) - { - return HashCode.Combine(0); - } - - // Standardize on the binary representation of NaN prior to hashing. - if (double.IsNaN(value)) - { - value = double.NaN; - } - - long l = *(long*)&value; - return HashCode.Combine((int)(l >> 32), unchecked((int)l)); - } - } - - private class GuidEqualityComparer : CollisionResistantHasher - { - internal static new readonly GuidEqualityComparer Instance = new GuidEqualityComparer(); - - public override unsafe int GetHashCode(Guid value) - { - var hash = default(HashCode); - int* pGuid = (int*)&value; - for (int i = 0; i < sizeof(Guid) / sizeof(int); i++) - { - hash.Add(pGuid[i]); - } - - return hash.ToHashCode(); - } - } - - private class StringEqualityComparer : CollisionResistantHasher - { - internal static new readonly StringEqualityComparer Instance = new StringEqualityComparer(); - - public override int GetHashCode(string value) - { -#if NETCOREAPP - // .NET Core already has a secure string hashing function. Just use it. - return value?.GetHashCode() ?? 0; -#else - var hash = default(HashCode); - for (int i = 0; i < value.Length; i++) - { - hash.Add(value[i]); - } - - return hash.ToHashCode(); -#endif - } - } - - private class DateTimeEqualityComparer : CollisionResistantHasher - { - internal static new readonly DateTimeEqualityComparer Instance = new DateTimeEqualityComparer(); - - public override unsafe int GetHashCode(DateTime value) => HashCode.Combine((int)(value.Ticks >> 32), unchecked((int)value.Ticks), value.Kind); - } - - private class DateTimeOffsetEqualityComparer : CollisionResistantHasher - { - internal static new readonly DateTimeOffsetEqualityComparer Instance = new DateTimeOffsetEqualityComparer(); - - public override unsafe int GetHashCode(DateTimeOffset value) => HashCode.Combine((int)(value.UtcTicks >> 32), unchecked((int)value.UtcTicks)); - } - } -} diff --git a/Assets/Plugins/MessagePack/MessagePackSecurity.cs.meta b/Assets/Plugins/MessagePack/MessagePackSecurity.cs.meta deleted file mode 100644 index f7011bbe4..000000000 --- a/Assets/Plugins/MessagePack/MessagePackSecurity.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 26fcc356242b5925cb5329bd41e488c7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/MessagePackSerializationException.cs b/Assets/Plugins/MessagePack/MessagePackSerializationException.cs deleted file mode 100644 index 85aa1ef7e..000000000 --- a/Assets/Plugins/MessagePack/MessagePackSerializationException.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; - -namespace MessagePack -{ - /// - /// An exception thrown during serializing an object graph or deserializing a messagepack sequence. - /// - [Serializable] -#if MESSAGEPACK_INTERNAL - internal -#else - public -#endif - class MessagePackSerializationException : Exception - { - /// - /// Initializes a new instance of the class. - /// - public MessagePackSerializationException() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The exception message. - public MessagePackSerializationException(string message) - : base(message) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The exception message. - /// The inner exception. - public MessagePackSerializationException(string message, Exception inner) - : base(message, inner) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// Serialization info. - /// Serialization context. - protected MessagePackSerializationException( - System.Runtime.Serialization.SerializationInfo info, - System.Runtime.Serialization.StreamingContext context) - : base(info, context) - { - } - } -} diff --git a/Assets/Plugins/MessagePack/MessagePackSerializationException.cs.meta b/Assets/Plugins/MessagePack/MessagePackSerializationException.cs.meta deleted file mode 100644 index 995f0e36d..000000000 --- a/Assets/Plugins/MessagePack/MessagePackSerializationException.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 839dc4ff13364b00e8d85ca4c6293047 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/MessagePackSerializer.Json.cs b/Assets/Plugins/MessagePack/MessagePackSerializer.Json.cs deleted file mode 100644 index 091e2a950..000000000 --- a/Assets/Plugins/MessagePack/MessagePackSerializer.Json.cs +++ /dev/null @@ -1,497 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Globalization; -using System.IO; -using System.Text; -using System.Threading; -using MessagePack.Formatters; -using Nerdbank.Streams; - -namespace MessagePack -{ - // JSON API - public partial class MessagePackSerializer - { - /// - /// Serialize an object to JSON string. - /// - /// Thrown if an error occurs during serialization. - public static void SerializeToJson(TextWriter textWriter, T obj, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - using (var sequenceRental = SequencePool.Shared.Rent()) - { - var msgpackWriter = new MessagePackWriter(sequenceRental.Value) - { - CancellationToken = cancellationToken, - }; - Serialize(ref msgpackWriter, obj, options); - msgpackWriter.Flush(); - var msgpackReader = new MessagePackReader(sequenceRental.Value) - { - CancellationToken = cancellationToken, - }; - ConvertToJson(ref msgpackReader, textWriter, options); - } - } - - /// - /// Serialize an object to JSON string. - /// - /// Thrown if an error occurs during serialization. - public static string SerializeToJson(T obj, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - var writer = new StringWriter(); - SerializeToJson(writer, obj, options, cancellationToken); - return writer.ToString(); - } - - /// - /// Convert a message-pack binary to a JSON string. - /// - /// Thrown if an error occurs while reading the messagepack data or writing out the JSON. - public static string ConvertToJson(ReadOnlyMemory bytes, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) => ConvertToJson(new ReadOnlySequence(bytes), options, cancellationToken); - - /// - /// Convert a message-pack binary to a JSON string. - /// - /// Thrown if an error occurs while reading the messagepack data or writing out the JSON. - public static string ConvertToJson(in ReadOnlySequence bytes, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - var jsonWriter = new StringWriter(); - var reader = new MessagePackReader(bytes) - { - CancellationToken = cancellationToken, - }; - ConvertToJson(ref reader, jsonWriter, options); - return jsonWriter.ToString(); - } - - /// - /// Convert a message-pack binary to a JSON string. - /// - /// Thrown if an error occurs while reading the messagepack data or writing out the JSON. - public static void ConvertToJson(ref MessagePackReader reader, TextWriter jsonWriter, MessagePackSerializerOptions options = null) - { - if (reader.End) - { - return; - } - - options = options ?? DefaultOptions; - try - { - if (options.Compression.IsCompression()) - { - using (var scratchRental = SequencePool.Shared.Rent()) - { - if (TryDecompress(ref reader, scratchRental.Value)) - { - var scratchReader = new MessagePackReader(scratchRental.Value) - { - CancellationToken = reader.CancellationToken, - }; - if (scratchReader.End) - { - return; - } - - ToJsonCore(ref scratchReader, jsonWriter, options); - } - else - { - ToJsonCore(ref reader, jsonWriter, options); - } - } - } - else - { - ToJsonCore(ref reader, jsonWriter, options); - } - } - catch (Exception ex) - { - throw new MessagePackSerializationException("Error occurred while translating msgpack to JSON.", ex); - } - } - - /// - /// Translates the given JSON to MessagePack. - /// - public static void ConvertFromJson(string str, ref MessagePackWriter writer, MessagePackSerializerOptions options = null) - { - using (var sr = new StringReader(str)) - { - ConvertFromJson(sr, ref writer, options); - } - } - - /// - /// Translates the given JSON to MessagePack. - /// - public static byte[] ConvertFromJson(string str, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - using (var scratchRental = SequencePool.Shared.Rent()) - { - var writer = new MessagePackWriter(scratchRental.Value) - { - CancellationToken = cancellationToken, - }; - using (var sr = new StringReader(str)) - { - ConvertFromJson(sr, ref writer, options); - } - - writer.Flush(); - return scratchRental.Value.AsReadOnlySequence.ToArray(); - } - } - - /// - /// Translates the given JSON to MessagePack. - /// - public static void ConvertFromJson(TextReader reader, ref MessagePackWriter writer, MessagePackSerializerOptions options = null) - { - options = options ?? DefaultOptions; - if (options.Compression.IsCompression()) - { - using (var scratchRental = SequencePool.Shared.Rent()) - { - MessagePackWriter scratchWriter = writer.Clone(scratchRental.Value); - using (var jr = new TinyJsonReader(reader, false)) - { - FromJsonCore(jr, ref scratchWriter); - } - - scratchWriter.Flush(); - ToLZ4BinaryCore(scratchRental.Value, ref writer, options.Compression); - } - } - else - { - using (var jr = new TinyJsonReader(reader, false)) - { - FromJsonCore(jr, ref writer); - } - } - } - - private static uint FromJsonCore(TinyJsonReader jr, ref MessagePackWriter writer) - { - uint count = 0; - while (jr.Read()) - { - switch (jr.TokenType) - { - case TinyJsonToken.None: - break; - case TinyJsonToken.StartObject: - // Set up a scratch area to serialize the collection since we don't know its length yet, which must be written first. - using (var scratchRental = SequencePool.Shared.Rent()) - { - MessagePackWriter scratchWriter = writer.Clone(scratchRental.Value); - var mapCount = FromJsonCore(jr, ref scratchWriter); - scratchWriter.Flush(); - - mapCount = mapCount / 2; // remove propertyname string count. - writer.WriteMapHeader(mapCount); - writer.WriteRaw(scratchRental.Value); - } - - count++; - break; - case TinyJsonToken.EndObject: - return count; // break - case TinyJsonToken.StartArray: - // Set up a scratch area to serialize the collection since we don't know its length yet, which must be written first. - using (var scratchRental = SequencePool.Shared.Rent()) - { - MessagePackWriter scratchWriter = writer.Clone(scratchRental.Value); - var arrayCount = FromJsonCore(jr, ref scratchWriter); - scratchWriter.Flush(); - - writer.WriteArrayHeader(arrayCount); - writer.WriteRaw(scratchRental.Value); - } - - count++; - break; - case TinyJsonToken.EndArray: - return count; // break - case TinyJsonToken.Number: - ValueType v = jr.ValueType; - if (v == ValueType.Double) - { - writer.Write(jr.DoubleValue); - } - else if (v == ValueType.Long) - { - writer.Write(jr.LongValue); - } - else if (v == ValueType.ULong) - { - writer.Write(jr.ULongValue); - } - else if (v == ValueType.Decimal) - { - DecimalFormatter.Instance.Serialize(ref writer, jr.DecimalValue, null); - } - - count++; - break; - case TinyJsonToken.String: - writer.Write(jr.StringValue); - count++; - break; - case TinyJsonToken.True: - writer.Write(true); - count++; - break; - case TinyJsonToken.False: - writer.Write(false); - count++; - break; - case TinyJsonToken.Null: - writer.WriteNil(); - count++; - break; - default: - break; - } - } - - return count; - } - - private static void ToJsonCore(ref MessagePackReader reader, TextWriter writer, MessagePackSerializerOptions options) - { - MessagePackType type = reader.NextMessagePackType; - switch (type) - { - case MessagePackType.Integer: - if (MessagePackCode.IsSignedInteger(reader.NextCode)) - { - writer.Write(reader.ReadInt64().ToString(CultureInfo.InvariantCulture)); - } - else - { - writer.Write(reader.ReadUInt64().ToString(CultureInfo.InvariantCulture)); - } - - break; - case MessagePackType.Boolean: - writer.Write(reader.ReadBoolean() ? "true" : "false"); - break; - case MessagePackType.Float: - if (reader.NextCode == MessagePackCode.Float32) - { - writer.Write(reader.ReadSingle().ToString(CultureInfo.InvariantCulture)); - } - else - { - writer.Write(reader.ReadDouble().ToString(CultureInfo.InvariantCulture)); - } - - break; - case MessagePackType.String: - WriteJsonString(reader.ReadString(), writer); - break; - case MessagePackType.Binary: - ArraySegment segment = ByteArraySegmentFormatter.Instance.Deserialize(ref reader, DefaultOptions); - writer.Write("\"" + Convert.ToBase64String(segment.Array, segment.Offset, segment.Count) + "\""); - break; - case MessagePackType.Array: - { - int length = reader.ReadArrayHeader(); - options.Security.DepthStep(ref reader); - try - { - writer.Write("["); - for (int i = 0; i < length; i++) - { - ToJsonCore(ref reader, writer, options); - - if (i != length - 1) - { - writer.Write(","); - } - } - - writer.Write("]"); - } - finally - { - reader.Depth--; - } - - return; - } - - case MessagePackType.Map: - { - int length = reader.ReadMapHeader(); - options.Security.DepthStep(ref reader); - try - { - writer.Write("{"); - for (int i = 0; i < length; i++) - { - // write key - { - MessagePackType keyType = reader.NextMessagePackType; - if (keyType == MessagePackType.String || keyType == MessagePackType.Binary) - { - ToJsonCore(ref reader, writer, options); - } - else - { - writer.Write("\""); - ToJsonCore(ref reader, writer, options); - writer.Write("\""); - } - } - - writer.Write(":"); - - // write body - { - ToJsonCore(ref reader, writer, options); - } - - if (i != length - 1) - { - writer.Write(","); - } - } - - writer.Write("}"); - } - finally - { - reader.Depth--; - } - - return; - } - - case MessagePackType.Extension: - ExtensionHeader extHeader = reader.ReadExtensionFormatHeader(); - if (extHeader.TypeCode == ReservedMessagePackExtensionTypeCode.DateTime) - { - DateTime dt = reader.ReadDateTime(extHeader); - writer.Write("\""); - writer.Write(dt.ToString("o", CultureInfo.InvariantCulture)); - writer.Write("\""); - } -#if !UNITY_2018_3_OR_NEWER - else if (extHeader.TypeCode == ThisLibraryExtensionTypeCodes.TypelessFormatter) - { - // prepare type name token - var privateBuilder = new StringBuilder(); - var typeNameTokenBuilder = new StringBuilder(); - SequencePosition positionBeforeTypeNameRead = reader.Position; - ToJsonCore(ref reader, new StringWriter(typeNameTokenBuilder), options); - int typeNameReadSize = (int)reader.Sequence.Slice(positionBeforeTypeNameRead, reader.Position).Length; - if (extHeader.Length > typeNameReadSize) - { - // object map or array - MessagePackType typeInside = reader.NextMessagePackType; - if (typeInside != MessagePackType.Array && typeInside != MessagePackType.Map) - { - privateBuilder.Append("{"); - } - - ToJsonCore(ref reader, new StringWriter(privateBuilder), options); - - // insert type name token to start of object map or array - if (typeInside != MessagePackType.Array) - { - typeNameTokenBuilder.Insert(0, "\"$type\":"); - } - - if (typeInside != MessagePackType.Array && typeInside != MessagePackType.Map) - { - privateBuilder.Append("}"); - } - - if (privateBuilder.Length > 2) - { - typeNameTokenBuilder.Append(","); - } - - privateBuilder.Insert(1, typeNameTokenBuilder.ToString()); - - writer.Write(privateBuilder.ToString()); - } - else - { - writer.Write("{\"$type\":\"" + typeNameTokenBuilder.ToString() + "}"); - } - } -#endif - else - { - var data = reader.ReadRaw((long)extHeader.Length); - writer.Write("["); - writer.Write(extHeader.TypeCode); - writer.Write(","); - writer.Write("\""); - writer.Write(Convert.ToBase64String(data.ToArray())); - writer.Write("\""); - writer.Write("]"); - } - - break; - case MessagePackType.Nil: - reader.Skip(); - writer.Write("null"); - break; - default: - throw new MessagePackSerializationException($"code is invalid. code: {reader.NextCode} format: {MessagePackCode.ToFormatName(reader.NextCode)}"); - } - } - - // escape string - private static void WriteJsonString(string value, TextWriter builder) - { - builder.Write('\"'); - - var len = value.Length; - for (int i = 0; i < len; i++) - { - var c = value[i]; - switch (c) - { - case '"': - builder.Write("\\\""); - break; - case '\\': - builder.Write("\\\\"); - break; - case '\b': - builder.Write("\\b"); - break; - case '\f': - builder.Write("\\f"); - break; - case '\n': - builder.Write("\\n"); - break; - case '\r': - builder.Write("\\r"); - break; - case '\t': - builder.Write("\\t"); - break; - default: - builder.Write(c); - break; - } - } - - builder.Write('\"'); - } - } -} diff --git a/Assets/Plugins/MessagePack/MessagePackSerializer.Json.cs.meta b/Assets/Plugins/MessagePack/MessagePackSerializer.Json.cs.meta deleted file mode 100644 index ab90bbf74..000000000 --- a/Assets/Plugins/MessagePack/MessagePackSerializer.Json.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: dc00f1de4bb511e45840cd820c364204 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/MessagePackSerializer.NonGeneric.cs b/Assets/Plugins/MessagePack/MessagePackSerializer.NonGeneric.cs deleted file mode 100644 index 7302567c7..000000000 --- a/Assets/Plugins/MessagePack/MessagePackSerializer.NonGeneric.cs +++ /dev/null @@ -1,321 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.IO; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Threading; -using System.Threading.Tasks; - -namespace MessagePack -{ - public partial class MessagePackSerializer - { - private static readonly Func CreateCompiledMethods; - private static readonly MessagePack.Internal.ThreadsafeTypeKeyHashTable Serializes = new MessagePack.Internal.ThreadsafeTypeKeyHashTable(capacity: 64); - - static MessagePackSerializer() - { - CreateCompiledMethods = t => new CompiledMethods(t); - } - - /// - public static void Serialize(Type type, ref MessagePackWriter writer, object obj, MessagePackSerializerOptions options = null) - { - GetOrAdd(type).Serialize_MessagePackWriter_T_Options.Invoke(ref writer, obj, options); - } - - /// - public static void Serialize(Type type, IBufferWriter writer, object obj, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - GetOrAdd(type).Serialize_IBufferWriter_T_Options_CancellationToken.Invoke(writer, obj, options, cancellationToken); - } - - /// - public static byte[] Serialize(Type type, object obj, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - return GetOrAdd(type).Serialize_T_Options.Invoke(obj, options, cancellationToken); - } - - /// - public static void Serialize(Type type, Stream stream, object obj, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - GetOrAdd(type).Serialize_Stream_T_Options_CancellationToken.Invoke(stream, obj, options, cancellationToken); - } - - /// - public static Task SerializeAsync(Type type, Stream stream, object obj, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - return GetOrAdd(type).SerializeAsync_Stream_T_Options_CancellationToken.Invoke(stream, obj, options, cancellationToken); - } - - /// - public static object Deserialize(Type type, ref MessagePackReader reader, MessagePackSerializerOptions options = null) - { - return GetOrAdd(type).Deserialize_MessagePackReader_Options.Invoke(ref reader, options); - } - - /// - public static object Deserialize(Type type, Stream stream, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - return GetOrAdd(type).Deserialize_Stream_Options_CancellationToken.Invoke(stream, options, cancellationToken); - } - - /// - public static ValueTask DeserializeAsync(Type type, Stream stream, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - return GetOrAdd(type).DeserializeAsync_Stream_Options_CancellationToken.Invoke(stream, options, cancellationToken); - } - - /// - public static object Deserialize(Type type, ReadOnlyMemory bytes, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - return GetOrAdd(type).Deserialize_ReadOnlyMemory_Options.Invoke(bytes, options, cancellationToken); - } - - /// - public static object Deserialize(Type type, ReadOnlySequence bytes, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - return GetOrAdd(type).Deserialize_ReadOnlySequence_Options_CancellationToken.Invoke(bytes, options, cancellationToken); - } - - private static async ValueTask DeserializeObjectAsync(Stream stream, MessagePackSerializerOptions options, CancellationToken cancellationToken) => await DeserializeAsync(stream, options, cancellationToken).ConfigureAwait(false); - - private static CompiledMethods GetOrAdd(Type type) - { - return Serializes.GetOrAdd(type, CreateCompiledMethods); - } - - private class CompiledMethods - { - internal delegate void MessagePackWriterSerialize(ref MessagePackWriter writer, object value, MessagePackSerializerOptions options); - - internal delegate object MessagePackReaderDeserialize(ref MessagePackReader reader, MessagePackSerializerOptions options); - -#pragma warning disable SA1310 // Field names should not contain underscore -#pragma warning disable SA1307 // Accessible fields should begin with upper-case letter -#pragma warning disable SA1401 // Fields should be private - internal readonly Func Serialize_T_Options; - internal readonly Action Serialize_Stream_T_Options_CancellationToken; - internal readonly Func SerializeAsync_Stream_T_Options_CancellationToken; - internal readonly MessagePackWriterSerialize Serialize_MessagePackWriter_T_Options; - internal readonly Action, object, MessagePackSerializerOptions, CancellationToken> Serialize_IBufferWriter_T_Options_CancellationToken; - - internal readonly MessagePackReaderDeserialize Deserialize_MessagePackReader_Options; - internal readonly Func Deserialize_Stream_Options_CancellationToken; - internal readonly Func> DeserializeAsync_Stream_Options_CancellationToken; - - internal readonly Func, MessagePackSerializerOptions, CancellationToken, object> Deserialize_ReadOnlyMemory_Options; - internal readonly Func, MessagePackSerializerOptions, CancellationToken, object> Deserialize_ReadOnlySequence_Options_CancellationToken; -#pragma warning restore SA1401 // Fields should be private -#pragma warning restore SA1307 // Accessible fields should begin with upper-case letter -#pragma warning restore SA1310 // Field names should not contain underscore - - internal CompiledMethods(Type type) - { - TypeInfo ti = type.GetTypeInfo(); - { - // public static byte[] Serialize(T obj, MessagePackSerializerOptions options, CancellationToken cancellationToken) - MethodInfo serialize = GetMethod(nameof(Serialize), type, new Type[] { null, typeof(MessagePackSerializerOptions), typeof(CancellationToken) }); - - ParameterExpression param1 = Expression.Parameter(typeof(object), "obj"); - ParameterExpression param2 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - ParameterExpression param3 = Expression.Parameter(typeof(CancellationToken), "cancellationToken"); - - MethodCallExpression body = Expression.Call( - null, - serialize, - ti.IsValueType ? Expression.Unbox(param1, type) : Expression.Convert(param1, type), - param2, - param3); - Func lambda = Expression.Lambda>(body, param1, param2, param3).Compile(); - - this.Serialize_T_Options = lambda; - } - - { - // public static void Serialize(Stream stream, T obj, MessagePackSerializerOptions options, CancellationToken cancellationToken) - MethodInfo serialize = GetMethod(nameof(Serialize), type, new Type[] { typeof(Stream), null, typeof(MessagePackSerializerOptions), typeof(CancellationToken) }); - - ParameterExpression param1 = Expression.Parameter(typeof(Stream), "stream"); - ParameterExpression param2 = Expression.Parameter(typeof(object), "obj"); - ParameterExpression param3 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - ParameterExpression param4 = Expression.Parameter(typeof(CancellationToken), "cancellationToken"); - - MethodCallExpression body = Expression.Call( - null, - serialize, - param1, - ti.IsValueType ? Expression.Unbox(param2, type) : Expression.Convert(param2, type), - param3, - param4); - Action lambda = Expression.Lambda>(body, param1, param2, param3, param4).Compile(); - - this.Serialize_Stream_T_Options_CancellationToken = lambda; - } - - { - // public static Task SerializeAsync(Stream stream, T obj, MessagePackSerializerOptions options, CancellationToken cancellationToken) - MethodInfo serialize = GetMethod(nameof(SerializeAsync), type, new Type[] { typeof(Stream), null, typeof(MessagePackSerializerOptions), typeof(CancellationToken) }); - - ParameterExpression param1 = Expression.Parameter(typeof(Stream), "stream"); - ParameterExpression param2 = Expression.Parameter(typeof(object), "obj"); - ParameterExpression param3 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - ParameterExpression param4 = Expression.Parameter(typeof(CancellationToken), "cancellationToken"); - - MethodCallExpression body = Expression.Call( - null, - serialize, - param1, - ti.IsValueType ? Expression.Unbox(param2, type) : Expression.Convert(param2, type), - param3, - param4); - Func lambda = Expression.Lambda>(body, param1, param2, param3, param4).Compile(); - - this.SerializeAsync_Stream_T_Options_CancellationToken = lambda; - } - - { - // public static Task Serialize(IBufferWriter writer, T obj, MessagePackSerializerOptions options, CancellationToken cancellationToken) - MethodInfo serialize = GetMethod(nameof(Serialize), type, new Type[] { typeof(IBufferWriter), null, typeof(MessagePackSerializerOptions), typeof(CancellationToken) }); - - ParameterExpression param1 = Expression.Parameter(typeof(IBufferWriter), "writer"); - ParameterExpression param2 = Expression.Parameter(typeof(object), "obj"); - ParameterExpression param3 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - ParameterExpression param4 = Expression.Parameter(typeof(CancellationToken), "cancellationToken"); - - MethodCallExpression body = Expression.Call( - null, - serialize, - param1, - ti.IsValueType ? Expression.Unbox(param2, type) : Expression.Convert(param2, type), - param3, - param4); - Action, object, MessagePackSerializerOptions, CancellationToken> lambda = Expression.Lambda, object, MessagePackSerializerOptions, CancellationToken>>(body, param1, param2, param3, param4).Compile(); - - this.Serialize_IBufferWriter_T_Options_CancellationToken = lambda; - } - - { - // public static void Serialize(ref MessagePackWriter writer, T obj, MessagePackSerializerOptions options) - MethodInfo serialize = GetMethod(nameof(Serialize), type, new Type[] { typeof(MessagePackWriter).MakeByRefType(), null, typeof(MessagePackSerializerOptions) }); - - ParameterExpression param1 = Expression.Parameter(typeof(MessagePackWriter).MakeByRefType(), "writer"); - ParameterExpression param2 = Expression.Parameter(typeof(object), "obj"); - ParameterExpression param3 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - - MethodCallExpression body = Expression.Call( - null, - serialize, - param1, - ti.IsValueType ? Expression.Unbox(param2, type) : Expression.Convert(param2, type), - param3); - MessagePackWriterSerialize lambda = Expression.Lambda(body, param1, param2, param3).Compile(); - - this.Serialize_MessagePackWriter_T_Options = lambda; - } - - { - // public static T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - MethodInfo deserialize = GetMethod(nameof(Deserialize), type, new Type[] { typeof(MessagePackReader).MakeByRefType(), typeof(MessagePackSerializerOptions) }); - - ParameterExpression param1 = Expression.Parameter(typeof(MessagePackReader).MakeByRefType(), "reader"); - ParameterExpression param2 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - UnaryExpression body = Expression.Convert(Expression.Call(null, deserialize, param1, param2), typeof(object)); - MessagePackReaderDeserialize lambda = Expression.Lambda(body, param1, param2).Compile(); - - this.Deserialize_MessagePackReader_Options = lambda; - } - - { - // public static T Deserialize(Stream stream, MessagePackSerializerOptions options, CancellationToken cancellationToken) - MethodInfo deserialize = GetMethod(nameof(Deserialize), type, new Type[] { typeof(Stream), typeof(MessagePackSerializerOptions), typeof(CancellationToken) }); - - ParameterExpression param1 = Expression.Parameter(typeof(Stream), "stream"); - ParameterExpression param2 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - ParameterExpression param3 = Expression.Parameter(typeof(CancellationToken), "cancellationToken"); - UnaryExpression body = Expression.Convert(Expression.Call(null, deserialize, param1, param2, param3), typeof(object)); - Func lambda = Expression.Lambda>(body, param1, param2, param3).Compile(); - - this.Deserialize_Stream_Options_CancellationToken = lambda; - } - - { - // public static ValueTask DeserializeObjectAsync(Stream stream, MessagePackSerializerOptions options, CancellationToken cancellationToken) - MethodInfo deserialize = GetMethod(nameof(DeserializeObjectAsync), type, new Type[] { typeof(Stream), typeof(MessagePackSerializerOptions), typeof(CancellationToken) }); - - ParameterExpression param1 = Expression.Parameter(typeof(Stream), "stream"); - ParameterExpression param2 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - ParameterExpression param3 = Expression.Parameter(typeof(CancellationToken), "cancellationToken"); - UnaryExpression body = Expression.Convert(Expression.Call(null, deserialize, param1, param2, param3), typeof(ValueTask)); - Func> lambda = Expression.Lambda>>(body, param1, param2, param3).Compile(); - - this.DeserializeAsync_Stream_Options_CancellationToken = lambda; - } - - { - // public static T Deserialize(ReadOnlyMemory bytes, MessagePackSerializerOptions options, CancellationToken cancellationToken) - MethodInfo deserialize = GetMethod(nameof(Deserialize), type, new Type[] { typeof(ReadOnlyMemory), typeof(MessagePackSerializerOptions), typeof(CancellationToken) }); - - ParameterExpression param1 = Expression.Parameter(typeof(ReadOnlyMemory), "bytes"); - ParameterExpression param2 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - ParameterExpression param3 = Expression.Parameter(typeof(CancellationToken), "cancellationToken"); - UnaryExpression body = Expression.Convert(Expression.Call(null, deserialize, param1, param2, param3), typeof(object)); - Func, MessagePackSerializerOptions, CancellationToken, object> lambda = Expression.Lambda, MessagePackSerializerOptions, CancellationToken, object>>(body, param1, param2, param3).Compile(); - - this.Deserialize_ReadOnlyMemory_Options = lambda; - } - - { - // public static T Deserialize(ReadOnlySequence bytes, MessagePackSerializerOptions options, CancellationToken cancellationToken) - MethodInfo deserialize = GetMethod(nameof(Deserialize), type, new Type[] { typeof(ReadOnlySequence).MakeByRefType(), typeof(MessagePackSerializerOptions), typeof(CancellationToken) }); - - ParameterExpression param1 = Expression.Parameter(typeof(ReadOnlySequence), "bytes"); - ParameterExpression param2 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - ParameterExpression param3 = Expression.Parameter(typeof(CancellationToken), "cancellationToken"); - UnaryExpression body = Expression.Convert(Expression.Call(null, deserialize, param1, param2, param3), typeof(object)); - Func, MessagePackSerializerOptions, CancellationToken, object> lambda = Expression.Lambda, MessagePackSerializerOptions, CancellationToken, object>>(body, param1, param2, param3).Compile(); - - this.Deserialize_ReadOnlySequence_Options_CancellationToken = lambda; - } - } - - // null is generic type marker. - private static MethodInfo GetMethod(string methodName, Type type, Type[] parameters) - { - return typeof(MessagePackSerializer).GetRuntimeMethods().Single(x => - { - if (methodName != x.Name) - { - return false; - } - - ParameterInfo[] ps = x.GetParameters(); - if (ps.Length != parameters.Length) - { - return false; - } - - for (int i = 0; i < ps.Length; i++) - { - if (parameters[i] == null && ps[i].ParameterType.IsGenericParameter) - { - continue; - } - - if (ps[i].ParameterType != parameters[i]) - { - return false; - } - } - - return true; - }) - .MakeGenericMethod(type); - } - } - } -} diff --git a/Assets/Plugins/MessagePack/MessagePackSerializer.NonGeneric.cs.meta b/Assets/Plugins/MessagePack/MessagePackSerializer.NonGeneric.cs.meta deleted file mode 100644 index 6c1d5e929..000000000 --- a/Assets/Plugins/MessagePack/MessagePackSerializer.NonGeneric.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 16a18255b8720219687e6195745bf4a3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/MessagePackSerializer.cs b/Assets/Plugins/MessagePack/MessagePackSerializer.cs deleted file mode 100644 index 0a4dbc0b9..000000000 --- a/Assets/Plugins/MessagePack/MessagePackSerializer.cs +++ /dev/null @@ -1,670 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Diagnostics; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using MessagePack.LZ4; -using Nerdbank.Streams; - -namespace MessagePack -{ - /// - /// High-Level API of MessagePack for C#. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Each overload has sufficiently unique required parameters.")] - public static partial class MessagePackSerializer - { - private const int LZ4NotCompressionSizeInLz4BlockType = 64; - - /// - /// Gets or sets the default set of options to use when not explicitly specified for a method call. - /// - /// The default value is . - /// - /// This is an AppDomain or process-wide setting. - /// If you're writing a library, you should NOT set or rely on this property but should instead pass - /// in (or the required options) explicitly to every method call - /// to guarantee appropriate behavior in any application. - /// If you are an app author, realize that setting this property impacts the entire application so it should only be - /// set once, and before any use of occurs. - /// - public static MessagePackSerializerOptions DefaultOptions { get; set; } = MessagePackSerializerOptions.Standard; - - /// - /// A thread-local, recyclable array that may be used for short bursts of code. - /// - [ThreadStatic] - private static byte[] scratchArray; - - /// - /// Serializes a given value with the specified buffer writer. - /// - /// The buffer writer to serialize with. - /// The value to serialize. - /// The options. Use null to use default options. - /// A cancellation token. - /// Thrown when any error occurs during serialization. - public static void Serialize(IBufferWriter writer, T value, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - var fastWriter = new MessagePackWriter(writer) - { - CancellationToken = cancellationToken, - }; - Serialize(ref fastWriter, value, options); - fastWriter.Flush(); - } - - /// - /// Serializes a given value with the specified buffer writer. - /// - /// The buffer writer to serialize with. - /// The value to serialize. - /// The options. Use null to use default options. - /// Thrown when any error occurs during serialization. - public static void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options = null) - { - options = options ?? DefaultOptions; - bool originalOldSpecValue = writer.OldSpec; - if (options.OldSpec.HasValue) - { - writer.OldSpec = options.OldSpec.Value; - } - - try - { - if (options.Compression.IsCompression() && !PrimitiveChecker.IsMessagePackFixedSizePrimitive) - { - using (var scratchRental = SequencePool.Shared.Rent()) - { - var scratch = scratchRental.Value; - MessagePackWriter scratchWriter = writer.Clone(scratch); - options.Resolver.GetFormatterWithVerify().Serialize(ref scratchWriter, value, options); - scratchWriter.Flush(); - ToLZ4BinaryCore(scratch, ref writer, options.Compression); - } - } - else - { - options.Resolver.GetFormatterWithVerify().Serialize(ref writer, value, options); - } - } - catch (Exception ex) - { - throw new MessagePackSerializationException($"Failed to serialize {typeof(T).FullName} value.", ex); - } - finally - { - writer.OldSpec = originalOldSpecValue; - } - } - - /// - /// Serializes a given value with the specified buffer writer. - /// - /// The value to serialize. - /// The options. Use null to use default options. - /// A cancellation token. - /// A byte array with the serialized value. - /// Thrown when any error occurs during serialization. - public static byte[] Serialize(T value, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - byte[] array = scratchArray; - if (array == null) - { - scratchArray = array = new byte[65536]; - } - - var msgpackWriter = new MessagePackWriter(SequencePool.Shared, array) - { - CancellationToken = cancellationToken, - }; - Serialize(ref msgpackWriter, value, options); - return msgpackWriter.FlushAndGetArray(); - } - - /// - /// Serializes a given value to the specified stream. - /// - /// The stream to serialize to. - /// The value to serialize. - /// The options. Use null to use default options. - /// A cancellation token. - /// Thrown when any error occurs during serialization. - public static void Serialize(Stream stream, T value, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); - using (SequencePool.Rental sequenceRental = SequencePool.Shared.Rent()) - { - Serialize(sequenceRental.Value, value, options, cancellationToken); - - try - { - foreach (ReadOnlyMemory segment in sequenceRental.Value.AsReadOnlySequence) - { - cancellationToken.ThrowIfCancellationRequested(); - stream.Write(segment.Span); - } - } - catch (Exception ex) - { - throw new MessagePackSerializationException("Error occurred while writing the serialized data to the stream.", ex); - } - } - } - - /// - /// Serializes a given value to the specified stream. - /// - /// The stream to serialize to. - /// The value to serialize. - /// The options. Use null to use default options. - /// A cancellation token. - /// A task that completes with the result of the async serialization operation. - /// Thrown when any error occurs during serialization. - public static async Task SerializeAsync(Stream stream, T value, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); - using (SequencePool.Rental sequenceRental = SequencePool.Shared.Rent()) - { - Serialize(sequenceRental.Value, value, options, cancellationToken); - - try - { - foreach (ReadOnlyMemory segment in sequenceRental.Value.AsReadOnlySequence) - { - cancellationToken.ThrowIfCancellationRequested(); - await stream.WriteAsync(segment, cancellationToken).ConfigureAwait(false); - } - } - catch (Exception ex) - { - throw new MessagePackSerializationException("Error occurred while writing the serialized data to the stream.", ex); - } - } - } - - /// - /// Deserializes a value of a given type from a sequence of bytes. - /// - /// The type of value to deserialize. - /// The sequence to deserialize from. - /// The options. Use null to use default options. - /// A cancellation token. - /// The deserialized value. - /// Thrown when any error occurs during deserialization. - public static T Deserialize(in ReadOnlySequence byteSequence, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - var reader = new MessagePackReader(byteSequence) - { - CancellationToken = cancellationToken, - }; - return Deserialize(ref reader, options); - } - - /// - /// Deserializes a value of a given type from a sequence of bytes. - /// - /// The type of value to deserialize. - /// The reader to deserialize from. - /// The options. Use null to use default options. - /// The deserialized value. - /// Thrown when any error occurs during deserialization. - public static T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options = null) - { - options = options ?? DefaultOptions; - - try - { - if (options.Compression.IsCompression()) - { - using (var msgPackUncompressedRental = SequencePool.Shared.Rent()) - { - var msgPackUncompressed = msgPackUncompressedRental.Value; - if (TryDecompress(ref reader, msgPackUncompressed)) - { - MessagePackReader uncompressedReader = reader.Clone(msgPackUncompressed.AsReadOnlySequence); - return options.Resolver.GetFormatterWithVerify().Deserialize(ref uncompressedReader, options); - } - else - { - return options.Resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - } - } - } - else - { - return options.Resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - } - } - catch (Exception ex) - { - throw new MessagePackSerializationException($"Failed to deserialize {typeof(T).FullName} value.", ex); - } - } - - /// - /// Deserializes a value of a given type from a sequence of bytes. - /// - /// The type of value to deserialize. - /// The buffer to deserialize from. - /// The options. Use null to use default options. - /// A cancellation token. - /// The deserialized value. - /// Thrown when any error occurs during deserialization. - public static T Deserialize(ReadOnlyMemory buffer, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - var reader = new MessagePackReader(buffer) - { - CancellationToken = cancellationToken, - }; - return Deserialize(ref reader, options); - } - - /// - /// Deserializes a value of a given type from a sequence of bytes. - /// - /// The type of value to deserialize. - /// The memory to deserialize from. - /// The number of bytes read. - /// A cancellation token. - /// The deserialized value. - /// Thrown when any error occurs during deserialization. - public static T Deserialize(ReadOnlyMemory buffer, out int bytesRead, CancellationToken cancellationToken = default) => Deserialize(buffer, options: null, out bytesRead, cancellationToken); - - /// - /// Deserializes a value of a given type from a sequence of bytes. - /// - /// The type of value to deserialize. - /// The memory to deserialize from. - /// The options. Use null to use default options. - /// The number of bytes read. - /// A cancellation token. - /// The deserialized value. - /// Thrown when any error occurs during deserialization. - public static T Deserialize(ReadOnlyMemory buffer, MessagePackSerializerOptions options, out int bytesRead, CancellationToken cancellationToken = default) - { - var reader = new MessagePackReader(buffer) - { - CancellationToken = cancellationToken, - }; - T result = Deserialize(ref reader, options); - bytesRead = buffer.Slice(0, (int)reader.Consumed).Length; - return result; - } - - /// - /// Deserializes the entire content of a . - /// - /// The type of value to deserialize. - /// - /// The stream to deserialize from. - /// The entire stream will be read, and the first msgpack token deserialized will be returned. - /// If is true on the stream, its position will be set to just after the last deserialized byte. - /// - /// The options. Use null to use default options. - /// A cancellation token. - /// The deserialized value. - /// Thrown when any error occurs during deserialization. - /// - /// If multiple top-level msgpack data structures are expected on the stream, use instead. - /// - public static T Deserialize(Stream stream, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - if (TryDeserializeFromMemoryStream(stream, options, cancellationToken, out T result)) - { - return result; - } - - using (var sequenceRental = SequencePool.Shared.Rent()) - { - var sequence = sequenceRental.Value; - try - { - int bytesRead; - do - { - cancellationToken.ThrowIfCancellationRequested(); - Span span = sequence.GetSpan(stream.CanSeek ? (int)(stream.Length - stream.Position) : 0); - bytesRead = stream.Read(span); - sequence.Advance(bytesRead); - } - while (bytesRead > 0); - } - catch (Exception ex) - { - throw new MessagePackSerializationException("Error occurred while reading from the stream.", ex); - } - - return DeserializeFromSequenceAndRewindStreamIfPossible(stream, options, sequence, cancellationToken); - } - } - - /// - /// Deserializes the entire content of a . - /// - /// The type of value to deserialize. - /// - /// The stream to deserialize from. - /// The entire stream will be read, and the first msgpack token deserialized will be returned. - /// If is true on the stream, its position will be set to just after the last deserialized byte. - /// - /// The options. Use null to use default options. - /// A cancellation token. - /// The deserialized value. - /// Thrown when any error occurs during deserialization. - /// - /// If multiple top-level msgpack data structures are expected on the stream, use instead. - /// - public static async ValueTask DeserializeAsync(Stream stream, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - if (TryDeserializeFromMemoryStream(stream, options, cancellationToken, out T result)) - { - return result; - } - - using (var sequenceRental = SequencePool.Shared.Rent()) - { - var sequence = sequenceRental.Value; - try - { - int bytesRead; - do - { - Memory memory = sequence.GetMemory(stream.CanSeek ? (int)(stream.Length - stream.Position) : 0); - bytesRead = await stream.ReadAsync(memory, cancellationToken).ConfigureAwait(false); - sequence.Advance(bytesRead); - } - while (bytesRead > 0); - } - catch (Exception ex) - { - throw new MessagePackSerializationException("Error occurred while reading from the stream.", ex); - } - - return DeserializeFromSequenceAndRewindStreamIfPossible(stream, options, sequence, cancellationToken); - } - } - - private delegate int LZ4Transform(ReadOnlySpan input, Span output); - - private static readonly LZ4Transform LZ4CodecEncode = LZ4Codec.Encode; - private static readonly LZ4Transform LZ4CodecDecode = LZ4Codec.Decode; - - private static bool TryDeserializeFromMemoryStream(Stream stream, MessagePackSerializerOptions options, CancellationToken cancellationToken, out T result) - { - cancellationToken.ThrowIfCancellationRequested(); - if (stream is MemoryStream ms && ms.TryGetBuffer(out ArraySegment streamBuffer)) - { - result = Deserialize(streamBuffer.AsMemory(checked((int)ms.Position)), options, out int bytesRead, cancellationToken); - - // Emulate that we had actually "read" from the stream. - ms.Seek(bytesRead, SeekOrigin.Current); - return true; - } - - result = default; - return false; - } - - private static T DeserializeFromSequenceAndRewindStreamIfPossible(Stream streamToRewind, MessagePackSerializerOptions options, ReadOnlySequence sequence, CancellationToken cancellationToken) - { - if (streamToRewind is null) - { - throw new ArgumentNullException(nameof(streamToRewind)); - } - - var reader = new MessagePackReader(sequence) - { - CancellationToken = cancellationToken, - }; - T result = Deserialize(ref reader, options); - - if (streamToRewind.CanSeek && !reader.End) - { - // Reverse the stream as many bytes as we left unread. - int bytesNotRead = checked((int)reader.Sequence.Slice(reader.Position).Length); - streamToRewind.Seek(-bytesNotRead, SeekOrigin.Current); - } - - return result; - } - - /// - /// Performs LZ4 compression or decompression. - /// - /// The input for the operation. - /// The buffer to write the result of the operation. - /// The LZ4 codec transformation. - /// The number of bytes written to the . - private static int LZ4Operation(in ReadOnlySequence input, Span output, LZ4Transform lz4Operation) - { - ReadOnlySpan inputSpan; - byte[] rentedInputArray = null; - if (input.IsSingleSegment) - { - inputSpan = input.First.Span; - } - else - { - rentedInputArray = ArrayPool.Shared.Rent((int)input.Length); - input.CopyTo(rentedInputArray); - inputSpan = rentedInputArray.AsSpan(0, (int)input.Length); - } - - try - { - return lz4Operation(inputSpan, output); - } - finally - { - if (rentedInputArray != null) - { - ArrayPool.Shared.Return(rentedInputArray); - } - } - } - - private static bool TryDecompress(ref MessagePackReader reader, IBufferWriter writer) - { - if (!reader.End) - { - // Try to find LZ4Block - if (reader.NextMessagePackType == MessagePackType.Extension) - { - MessagePackReader peekReader = reader.CreatePeekReader(); - ExtensionHeader header = peekReader.ReadExtensionFormatHeader(); - if (header.TypeCode == ThisLibraryExtensionTypeCodes.Lz4Block) - { - // Read the extension using the original reader, so we "consume" it. - ExtensionResult extension = reader.ReadExtensionFormat(); - var extReader = new MessagePackReader(extension.Data); - - // The first part of the extension payload is a MessagePack-encoded Int32 that - // tells us the length the data will be AFTER decompression. - int uncompressedLength = extReader.ReadInt32(); - - // The rest of the payload is the compressed data itself. - ReadOnlySequence compressedData = extReader.Sequence.Slice(extReader.Position); - - Span uncompressedSpan = writer.GetSpan(uncompressedLength).Slice(0, uncompressedLength); - int actualUncompressedLength = LZ4Operation(compressedData, uncompressedSpan, LZ4CodecDecode); - Debug.Assert(actualUncompressedLength == uncompressedLength, "Unexpected length of uncompressed data."); - writer.Advance(actualUncompressedLength); - return true; - } - } - - // Try to find LZ4BlockArray - if (reader.NextMessagePackType == MessagePackType.Array) - { - MessagePackReader peekReader = reader.CreatePeekReader(); - var arrayLength = peekReader.ReadArrayHeader(); - if (arrayLength != 0 && peekReader.NextMessagePackType == MessagePackType.Extension) - { - ExtensionHeader header = peekReader.ReadExtensionFormatHeader(); - if (header.TypeCode == ThisLibraryExtensionTypeCodes.Lz4BlockArray) - { - // switch peekReader as original reader. - reader = peekReader; - - // Read from [Ext(98:int,int...), bin,bin,bin...] - var sequenceCount = arrayLength - 1; - var uncompressedLengths = ArrayPool.Shared.Rent(sequenceCount); - try - { - for (int i = 0; i < sequenceCount; i++) - { - uncompressedLengths[i] = reader.ReadInt32(); - } - - for (int i = 0; i < sequenceCount; i++) - { - var uncompressedLength = uncompressedLengths[i]; - var lz4Block = reader.ReadBytes(); - Span uncompressedSpan = writer.GetSpan(uncompressedLength).Slice(0, uncompressedLength); - var actualUncompressedLength = LZ4Operation(lz4Block.Value, uncompressedSpan, LZ4CodecDecode); - Debug.Assert(actualUncompressedLength == uncompressedLength, "Unexpected length of uncompressed data."); - writer.Advance(actualUncompressedLength); - } - - return true; - } - finally - { - ArrayPool.Shared.Return(uncompressedLengths); - } - } - } - } - } - - return false; - } - - private static void ToLZ4BinaryCore(in ReadOnlySequence msgpackUncompressedData, ref MessagePackWriter writer, MessagePackCompression compression) - { - if (compression == MessagePackCompression.Lz4Block) - { - if (msgpackUncompressedData.Length < LZ4NotCompressionSizeInLz4BlockType) - { - writer.WriteRaw(msgpackUncompressedData); - return; - } - - var maxCompressedLength = LZ4Codec.MaximumOutputLength((int)msgpackUncompressedData.Length); - var lz4Span = ArrayPool.Shared.Rent(maxCompressedLength); - try - { - int lz4Length = LZ4Operation(msgpackUncompressedData, lz4Span, LZ4CodecEncode); - - const int LengthOfUncompressedDataSizeHeader = 5; - writer.WriteExtensionFormatHeader(new ExtensionHeader(ThisLibraryExtensionTypeCodes.Lz4Block, LengthOfUncompressedDataSizeHeader + (uint)lz4Length)); - writer.WriteInt32((int)msgpackUncompressedData.Length); - writer.WriteRaw(lz4Span.AsSpan(0, lz4Length)); - } - finally - { - ArrayPool.Shared.Return(lz4Span); - } - } - else if (compression == MessagePackCompression.Lz4BlockArray) - { - // Write to [Ext(98:int,int...), bin,bin,bin...] - var sequenceCount = 0; - var extHeaderSize = 0; - foreach (var item in msgpackUncompressedData) - { - sequenceCount++; - extHeaderSize += GetUInt32WriteSize((uint)item.Length); - } - - writer.WriteArrayHeader(sequenceCount + 1); - writer.WriteExtensionFormatHeader(new ExtensionHeader(ThisLibraryExtensionTypeCodes.Lz4BlockArray, extHeaderSize)); - { - foreach (var item in msgpackUncompressedData) - { - writer.Write(item.Length); - } - } - - foreach (var item in msgpackUncompressedData) - { - var maxCompressedLength = LZ4Codec.MaximumOutputLength(item.Length); - var lz4Span = writer.GetSpan(maxCompressedLength + 5); - int lz4Length = LZ4Codec.Encode(item.Span, lz4Span.Slice(5, lz4Span.Length - 5)); - WriteBin32Header((uint)lz4Length, lz4Span); - writer.Advance(lz4Length + 5); - } - } - else - { - throw new ArgumentException("Invalid MessagePackCompression Code. Code:" + compression); - } - } - - private static int GetUInt32WriteSize(uint value) - { - if (value <= MessagePackRange.MaxFixPositiveInt) - { - return 1; - } - else if (value <= byte.MaxValue) - { - return 2; - } - else if (value <= ushort.MaxValue) - { - return 3; - } - else - { - return 5; - } - } - - private static void WriteBin32Header(uint value, Span span) - { - unchecked - { - span[0] = MessagePackCode.Bin32; - - // Write to highest index first so the JIT skips bounds checks on subsequent writes. - span[4] = (byte)value; - span[3] = (byte)(value >> 8); - span[2] = (byte)(value >> 16); - span[1] = (byte)(value >> 24); - } - } - - private static class PrimitiveChecker - { - public static readonly bool IsMessagePackFixedSizePrimitive; - - static PrimitiveChecker() - { - IsMessagePackFixedSizePrimitive = IsMessagePackFixedSizePrimitiveTypeHelper(typeof(T)); - } - } - - private static bool IsMessagePackFixedSizePrimitiveTypeHelper(Type type) - { - return type == typeof(short) - || type == typeof(int) - || type == typeof(long) - || type == typeof(ushort) - || type == typeof(uint) - || type == typeof(ulong) - || type == typeof(float) - || type == typeof(double) - || type == typeof(bool) - || type == typeof(byte) - || type == typeof(sbyte) - || type == typeof(char) - ; - } - } -} diff --git a/Assets/Plugins/MessagePack/MessagePackSerializer.cs.meta b/Assets/Plugins/MessagePack/MessagePackSerializer.cs.meta deleted file mode 100644 index 41bd3c47d..000000000 --- a/Assets/Plugins/MessagePack/MessagePackSerializer.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d7b51af2d7d3d2fb985dbe15e77b9461 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/MessagePackSerializerOptions.cs b/Assets/Plugins/MessagePack/MessagePackSerializerOptions.cs deleted file mode 100644 index a259c99ce..000000000 --- a/Assets/Plugins/MessagePack/MessagePackSerializerOptions.cs +++ /dev/null @@ -1,284 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using System.Text.RegularExpressions; - -namespace MessagePack -{ -#if !DYNAMICCODEDUMPER - /// - /// An immutable description of options for running the . - /// -#endif - public class MessagePackSerializerOptions - { - // see:http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx - internal static readonly Regex AssemblyNameVersionSelectorRegex = new Regex(@", Version=\d+.\d+.\d+.\d+, Culture=[\w-]+, PublicKeyToken=(?:null|[a-f0-9]{16})$", RegexOptions.Compiled); - - /// - /// A collection of known dangerous types that are not expected in a typical MessagePack stream, - /// and thus are rejected by the default implementation of . - /// - private static readonly HashSet BlacklistCheck = new HashSet - { - "System.CodeDom.Compiler.TempFileCollection", - "System.Management.IWbemClassObjectFreeThreaded", - }; - -#if !DYNAMICCODEDUMPER - /// - /// Gets a good default set of options that uses the and no compression. - /// - public static MessagePackSerializerOptions Standard => MessagePackSerializerOptionsDefaultSettingsLazyInitializationHelper.Standard; -#endif - - /// - /// Initializes a new instance of the class. - /// - protected internal MessagePackSerializerOptions(IFormatterResolver resolver) - { - this.Resolver = resolver ?? throw new ArgumentNullException(nameof(resolver)); - } - - /// - /// Initializes a new instance of the class - /// with members initialized from an existing instance. - /// - /// The options to copy from. - protected MessagePackSerializerOptions(MessagePackSerializerOptions copyFrom) - { - if (copyFrom == null) - { - throw new ArgumentNullException(nameof(copyFrom)); - } - - this.Resolver = copyFrom.Resolver; - this.Compression = copyFrom.Compression; - this.OldSpec = copyFrom.OldSpec; - this.OmitAssemblyVersion = copyFrom.OmitAssemblyVersion; - this.AllowAssemblyVersionMismatch = copyFrom.AllowAssemblyVersionMismatch; - this.Security = copyFrom.Security; - } - - /// - /// Gets the resolver to use for complex types. - /// - /// An instance of . Never null. - /// Thrown if an attempt is made to set this property to null. - public IFormatterResolver Resolver { get; private set; } - - /// - /// Gets the compression scheme to apply to serialized sequences. - /// - /// - /// When set to something other than , - /// deserialization can still work on uncompressed sequences, - /// and serialization may not compress if msgpack sequences are short enough that compression would not likely be advantageous. - /// - public MessagePackCompression Compression { get; private set; } - - /// - /// Gets a value indicating whether to serialize with set to some value - /// causing messagepack spec compliance to be explicitly set to the old or new format. - /// - /// - /// A null value means the 's default or previous setting will be used. - /// A non-null value will be applied to the property for the duration of a - /// serialization and then reverted to its prior setting. - /// - /// - /// Reading always supports both new and old spec. - /// - public bool? OldSpec { get; private set; } - - /// - /// Gets a value indicating whether serialization should omit assembly version, culture and public key token metadata when using the typeless formatter. - /// - /// The default value is false. - public bool OmitAssemblyVersion { get; private set; } - - /// - /// Gets a value indicating whether deserialization may instantiate types from an assembly with a different version if a matching version cannot be found. - /// - /// The default value is false. - public bool AllowAssemblyVersionMismatch { get; private set; } - - /// - /// Gets the security-related options for deserializing messagepack sequences. - /// - /// - /// The default value is to use . - /// - public MessagePackSecurity Security { get; private set; } = MessagePackSecurity.TrustedData; - - /// - /// Gets a type given a string representation of the type. - /// - /// The name of the type to load. This is typically the but may use the assembly's simple name. - /// The loaded type or null if no matching type could be found. - public virtual Type LoadType(string typeName) - { - Type result = Type.GetType(typeName, false); - if (result == null && this.AllowAssemblyVersionMismatch) - { - string shortenedName = AssemblyNameVersionSelectorRegex.Replace(typeName, string.Empty); - if (shortenedName != typeName) - { - result = Type.GetType(shortenedName, false); - } - } - - return result; - } - - /// - /// Checks whether a given type may be deserialized. - /// - /// The type to be instantiated. - /// Thrown if the is not allowed to be deserialized. - /// - /// This method provides a means for an important security mitigation when using the Typeless formatter to prevent untrusted messagepack from - /// deserializing objects that may be harmful if instantiated, disposed or finalized. - /// The default implementation throws for only a few known dangerous types. - /// Applications that deserialize from untrusted sources should override this method and throw if the type is not among the expected set. - /// - public virtual void ThrowIfDeserializingTypeIsDisallowed(Type type) - { - if (BlacklistCheck.Contains(type.FullName)) - { - throw new MessagePackSerializationException("Deserialization attempted to create the type " + type.FullName + " which is not allowed."); - } - } - - /// - /// Gets a copy of these options with the property set to a new value. - /// - /// The new value for the . - /// The new instance; or the original if the value is unchanged. - public MessagePackSerializerOptions WithResolver(IFormatterResolver resolver) - { - if (this.Resolver == resolver) - { - return this; - } - - var result = this.Clone(); - result.Resolver = resolver; - return result; - } - - /// - /// Gets a copy of these options with the property set to a new value. - /// - /// The new value for the property. - /// The new instance; or the original if the value is unchanged. - public MessagePackSerializerOptions WithCompression(MessagePackCompression compression) - { - if (this.Compression == compression) - { - return this; - } - - var result = this.Clone(); - result.Compression = compression; - return result; - } - - /// - /// Gets a copy of these options with the property set to a new value. - /// - /// The new value for the . - /// The new instance; or the original if the value is unchanged. - public MessagePackSerializerOptions WithOldSpec(bool? oldSpec = true) - { - if (this.OldSpec == oldSpec) - { - return this; - } - - var result = this.Clone(); - result.OldSpec = oldSpec; - return result; - } - - /// - /// Gets a copy of these options with the property set to a new value. - /// - /// The new value for the property. - /// The new instance; or the original if the value is unchanged. - public MessagePackSerializerOptions WithOmitAssemblyVersion(bool omitAssemblyVersion) - { - if (this.OmitAssemblyVersion == omitAssemblyVersion) - { - return this; - } - - var result = this.Clone(); - result.OmitAssemblyVersion = omitAssemblyVersion; - return result; - } - - /// - /// Gets a copy of these options with the property set to a new value. - /// - /// The new value for the property. - /// The new instance; or the original if the value is unchanged. - public MessagePackSerializerOptions WithAllowAssemblyVersionMismatch(bool allowAssemblyVersionMismatch) - { - if (this.AllowAssemblyVersionMismatch == allowAssemblyVersionMismatch) - { - return this; - } - - var result = this.Clone(); - result.AllowAssemblyVersionMismatch = allowAssemblyVersionMismatch; - return result; - } - - /// - /// Gets a copy of these options with the property set to a new value. - /// - /// The new value for the property. - /// The new instance; or the original if the value is unchanged. - public MessagePackSerializerOptions WithSecurity(MessagePackSecurity security) - { - if (security is null) - { - throw new ArgumentNullException(nameof(security)); - } - - if (this.Security == security) - { - return this; - } - - var result = this.Clone(); - result.Security = security; - return result; - } - - /// - /// Creates a clone of this instance with the same properties set. - /// - /// The cloned instance. Guaranteed to be a new instance. - /// Thrown if this instance is a derived type that doesn't override this method. - protected virtual MessagePackSerializerOptions Clone() - { - if (this.GetType() != typeof(MessagePackSerializerOptions)) - { - throw new NotSupportedException($"The derived type {this.GetType().FullName} did not override the {nameof(Clone)} method as required."); - } - - return new MessagePackSerializerOptions(this); - } - -#if !DYNAMICCODEDUMPER - private static class MessagePackSerializerOptionsDefaultSettingsLazyInitializationHelper - { - public static readonly MessagePackSerializerOptions Standard = new MessagePackSerializerOptions(Resolvers.StandardResolver.Instance); - } -#endif - } -} diff --git a/Assets/Plugins/MessagePack/MessagePackSerializerOptions.cs.meta b/Assets/Plugins/MessagePack/MessagePackSerializerOptions.cs.meta deleted file mode 100644 index 86bd30ca6..000000000 --- a/Assets/Plugins/MessagePack/MessagePackSerializerOptions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 97c761333b96605e78fae4ae77707e1b -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/MessagePackStreamReader.cs b/Assets/Plugins/MessagePack/MessagePackStreamReader.cs deleted file mode 100644 index fb439ddc7..000000000 --- a/Assets/Plugins/MessagePack/MessagePackStreamReader.cs +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using Nerdbank.Streams; - -namespace MessagePack -{ - /// - /// Reads one or more messagepack data structures from a . - /// - /// - /// This class is *not* thread-safe. Do not call more than one member at once and be sure any call completes (including asynchronous tasks) - /// before calling the next one. - /// - public partial class MessagePackStreamReader : IDisposable - { - private readonly Stream stream; - private readonly bool leaveOpen; - private SequencePool.Rental sequenceRental = SequencePool.Shared.Rent(); - private SequencePosition? endOfLastMessage; - - /// - /// Initializes a new instance of the class. - /// - /// The stream to read from. This stream will be disposed of when this is disposed. - public MessagePackStreamReader(Stream stream) - : this(stream, leaveOpen: false) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The stream to read from. - /// If true, leaves the stream open after this is disposed; otherwise, false. - public MessagePackStreamReader(Stream stream, bool leaveOpen) - { - this.stream = stream ?? throw new ArgumentNullException(nameof(stream)); - this.leaveOpen = leaveOpen; - } - - /// - /// Gets any bytes that have been read since the last complete message returned from . - /// - public ReadOnlySequence RemainingBytes => this.endOfLastMessage.HasValue ? this.ReadData.AsReadOnlySequence.Slice(this.endOfLastMessage.Value) : this.ReadData.AsReadOnlySequence; - - /// - /// Gets the sequence that we read data from the into. - /// - private Sequence ReadData => this.sequenceRental.Value; - - /// - /// Reads the next whole (top-level) messagepack data structure. - /// - /// A cancellation token. - /// - /// A task whose result is the next whole data structure from the stream, or null if the stream ends. - /// The returned sequence is valid until this is disposed or - /// until this method is called again, whichever comes first. - /// - /// - /// When null is the result of the returned task, - /// any extra bytes read (between the last complete message and the end of the stream) will be available via the property. - /// - public async ValueTask?> ReadAsync(CancellationToken cancellationToken) - { - this.RecycleLastMessage(); - - while (true) - { - // Check if we have a complete message and return it if we have it. - // We do this before reading anything since a previous read may have brought in several messages. - cancellationToken.ThrowIfCancellationRequested(); - if (this.TryReadNextMessage(out ReadOnlySequence completeMessage)) - { - return completeMessage; - } - - if (!await this.TryReadMoreDataAsync(cancellationToken).ConfigureAwait(false)) - { - // We've reached the end of the stream. - // We already checked for a complete message with what we already had, so evidently it's not a complete message. - return null; - } - } - } - - /// - /// Arranges for the next read operation to start by reading from the underlying - /// instead of any data buffered from a previous read. - /// - /// - /// This is appropriate if the underlying has been repositioned such that - /// any previously buffered data is no longer applicable to what the caller wants to read. - /// - public void DiscardBufferedData() - { - this.sequenceRental.Value.Reset(); - this.endOfLastMessage = default; - } - - /// - public void Dispose() - { - if (!this.leaveOpen) - { - this.stream.Dispose(); - } - - this.sequenceRental.Dispose(); - this.sequenceRental = default; - } - - /// - /// Recycle memory from a previously returned message. - /// - private void RecycleLastMessage() - { - if (this.endOfLastMessage.HasValue) - { - // A previously returned message can now be safely recycled since the caller wants more. - this.ReadData.AdvanceTo(this.endOfLastMessage.Value); - this.endOfLastMessage = null; - } - } - - /// - /// Read more data from the stream into the buffer. - /// - /// A cancellation token. - /// true if more data was read; false if the end of the stream had already been reached. - private async Task TryReadMoreDataAsync(CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - Memory buffer = this.ReadData.GetMemory(sizeHint: 0); - int bytesRead = 0; - try - { - bytesRead = await this.stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); - return bytesRead > 0; - } - finally - { - // Keep our state clean in case the caller wants to call us again. - this.ReadData.Advance(bytesRead); - } - } - - /// - /// Checks whether the content in include a complete messagepack structure. - /// - /// Receives the sequence of the first complete data structure found, if any. - /// true if a complete data structure was found; false otherwise. - private bool TryReadNextMessage(out ReadOnlySequence completeMessage) - { - if (this.ReadData.Length > 0) - { - var reader = new MessagePackReader(this.ReadData); - - // Perf opportunity: instead of skipping from the start each time, we could incrementally skip across tries - // possibly as easy as simply keeping a count of how many tokens still need to be skipped (that we know about). - if (reader.TrySkip()) - { - this.endOfLastMessage = reader.Position; - completeMessage = reader.Sequence.Slice(0, reader.Position); - return true; - } - } - - completeMessage = default; - return false; - } - } -} diff --git a/Assets/Plugins/MessagePack/MessagePackStreamReader.cs.meta b/Assets/Plugins/MessagePack/MessagePackStreamReader.cs.meta deleted file mode 100644 index cc25ca51a..000000000 --- a/Assets/Plugins/MessagePack/MessagePackStreamReader.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 680529136fcef07e78156a87b5d33f1f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/MessagePackWriter.cs b/Assets/Plugins/MessagePack/MessagePackWriter.cs deleted file mode 100644 index 71296ed70..000000000 --- a/Assets/Plugins/MessagePack/MessagePackWriter.cs +++ /dev/null @@ -1,1322 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections.Generic; -using System.ComponentModel; -using System.Runtime.CompilerServices; -using System.Text; -using System.Threading; -using MessagePack.Internal; -using Microsoft; - -namespace MessagePack -{ - /// - /// A primitive types writer for the MessagePack format. - /// - /// - /// The MessagePack spec.. - /// -#if MESSAGEPACK_INTERNAL - internal -#else - public -#endif - ref struct MessagePackWriter - { - /// - /// The writer to use. - /// - private BufferWriter writer; - - /// - /// Initializes a new instance of the struct. - /// - /// The writer to use. - public MessagePackWriter(IBufferWriter writer) - : this() - { - this.writer = new BufferWriter(writer); - this.OldSpec = false; - } - - /// - /// Initializes a new instance of the struct. - /// - /// The pool from which to draw an if required.. - /// An array to start with so we can avoid accessing the if possible. - internal MessagePackWriter(SequencePool sequencePool, byte[] array) - : this() - { - this.writer = new BufferWriter(sequencePool, array); - this.OldSpec = false; - } - - /// - /// Gets or sets the cancellation token for this serialization operation. - /// - public CancellationToken CancellationToken { get; set; } - - /// - /// Gets or sets a value indicating whether to write in old spec compatibility mode. - /// - public bool OldSpec { get; set; } - - /// - /// Initializes a new instance of the struct, - /// with the same settings as this one, but with its own buffer writer. - /// - /// The writer to use for the new instance. - /// The new writer. - public MessagePackWriter Clone(IBufferWriter writer) => new MessagePackWriter(writer) - { - OldSpec = this.OldSpec, - CancellationToken = this.CancellationToken, - }; - - /// - /// Ensures everything previously written has been flushed to the underlying . - /// - public void Flush() => this.writer.Commit(); - - /// - /// Writes a value. - /// - public void WriteNil() - { - Span span = this.writer.GetSpan(1); - span[0] = MessagePackCode.Nil; - this.writer.Advance(1); - } - - /// - /// Copies bytes directly into the message pack writer. - /// - /// The span of bytes to copy from. - public void WriteRaw(ReadOnlySpan rawMessagePackBlock) => this.writer.Write(rawMessagePackBlock); - - /// - /// Copies bytes directly into the message pack writer. - /// - /// The span of bytes to copy from. - public void WriteRaw(in ReadOnlySequence rawMessagePackBlock) - { - foreach (ReadOnlyMemory segment in rawMessagePackBlock) - { - this.writer.Write(segment.Span); - } - } - - /// - /// Write the length of the next array to be written in the most compact form of - /// , - /// , or - /// . - /// - /// The number of elements that will be written in the array. - public void WriteArrayHeader(int count) => this.WriteArrayHeader((uint)count); - - /// - /// Write the length of the next array to be written in the most compact form of - /// , - /// , or - /// . - /// - /// The number of elements that will be written in the array. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void WriteArrayHeader(uint count) - { - if (count <= MessagePackRange.MaxFixArrayCount) - { - Span span = this.writer.GetSpan(1); - span[0] = (byte)(MessagePackCode.MinFixArray | count); - this.writer.Advance(1); - } - else if (count <= ushort.MaxValue) - { - Span span = this.writer.GetSpan(3); - span[0] = MessagePackCode.Array16; - WriteBigEndian((ushort)count, span.Slice(1)); - this.writer.Advance(3); - } - else - { - Span span = this.writer.GetSpan(5); - span[0] = MessagePackCode.Array32; - WriteBigEndian(count, span.Slice(1)); - this.writer.Advance(5); - } - } - - /// - /// Write the length of the next map to be written in the most compact form of - /// , - /// , or - /// . - /// - /// The number of key=value pairs that will be written in the map. - public void WriteMapHeader(int count) => this.WriteMapHeader((uint)count); - - /// - /// Write the length of the next map to be written in the most compact form of - /// , - /// , or - /// . - /// - /// The number of key=value pairs that will be written in the map. - public void WriteMapHeader(uint count) - { - if (count <= MessagePackRange.MaxFixMapCount) - { - Span span = this.writer.GetSpan(1); - span[0] = (byte)(MessagePackCode.MinFixMap | count); - this.writer.Advance(1); - } - else if (count <= ushort.MaxValue) - { - Span span = this.writer.GetSpan(3); - span[0] = MessagePackCode.Map16; - WriteBigEndian((ushort)count, span.Slice(1)); - this.writer.Advance(3); - } - else - { - Span span = this.writer.GetSpan(5); - span[0] = MessagePackCode.Map32; - WriteBigEndian(count, span.Slice(1)); - this.writer.Advance(5); - } - } - - /// - /// Writes a value using a 1-byte code when possible, otherwise as . - /// - /// The value. - public void Write(byte value) - { - if (value <= MessagePackCode.MaxFixInt) - { - Span span = this.writer.GetSpan(1); - span[0] = value; - this.writer.Advance(1); - } - else - { - this.WriteUInt8(value); - } - } - - /// - /// Writes a value using . - /// - /// The value. - public void WriteUInt8(byte value) - { - Span span = this.writer.GetSpan(2); - span[0] = MessagePackCode.UInt8; - span[1] = value; - this.writer.Advance(2); - } - - /// - /// Writes an 8-bit value using a 1-byte code when possible, otherwise as . - /// - /// The value. - public void Write(sbyte value) - { - if (value < MessagePackRange.MinFixNegativeInt) - { - this.WriteInt8(value); - } - else - { - Span span = this.writer.GetSpan(1); - span[0] = unchecked((byte)value); - this.writer.Advance(1); - } - } - - /// - /// Writes an 8-bit value using . - /// - /// The value. - public void WriteInt8(sbyte value) - { - Span span = this.writer.GetSpan(2); - span[0] = MessagePackCode.Int8; - span[1] = unchecked((byte)value); - this.writer.Advance(2); - } - - /// - /// Writes a value using a 1-byte code when possible, otherwise as or . - /// - /// The value. - public void Write(ushort value) - { - if (value <= MessagePackRange.MaxFixPositiveInt) - { - Span span = this.writer.GetSpan(1); - span[0] = unchecked((byte)value); - this.writer.Advance(1); - } - else if (value <= byte.MaxValue) - { - Span span = this.writer.GetSpan(2); - span[0] = MessagePackCode.UInt8; - span[1] = unchecked((byte)value); - this.writer.Advance(2); - } - else - { - this.WriteUInt16(value); - } - } - - /// - /// Writes a value using . - /// - /// The value. - public void WriteUInt16(ushort value) - { - Span span = this.writer.GetSpan(3); - span[0] = MessagePackCode.UInt16; - WriteBigEndian(value, span.Slice(1)); - this.writer.Advance(3); - } - - /// - /// Writes a using a built-in 1-byte code when within specific MessagePack-supported ranges, - /// or the most compact of - /// , - /// , - /// , or - /// . - /// - /// The value to write. - public void Write(short value) - { - if (value >= 0) - { - this.Write((ushort)value); - } - else - { - // negative int(use int) - if (value >= MessagePackRange.MinFixNegativeInt) - { - Span span = this.writer.GetSpan(1); - span[0] = unchecked((byte)value); - this.writer.Advance(1); - } - else if (value >= sbyte.MinValue) - { - Span span = this.writer.GetSpan(2); - span[0] = MessagePackCode.Int8; - span[1] = unchecked((byte)value); - this.writer.Advance(2); - } - else - { - this.WriteInt16(value); - } - } - } - - /// - /// Writes a using . - /// - /// The value to write. - public void WriteInt16(short value) - { - Span span = this.writer.GetSpan(3); - span[0] = MessagePackCode.Int16; - WriteBigEndian(value, span.Slice(1)); - this.writer.Advance(3); - } - - /// - /// Writes an using a built-in 1-byte code when within specific MessagePack-supported ranges, - /// or the most compact of - /// , - /// , or - /// . - /// - /// The value to write. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(uint value) - { - if (value <= MessagePackRange.MaxFixPositiveInt) - { - Span span = this.writer.GetSpan(1); - span[0] = unchecked((byte)value); - this.writer.Advance(1); - } - else if (value <= byte.MaxValue) - { - Span span = this.writer.GetSpan(2); - span[0] = MessagePackCode.UInt8; - span[1] = unchecked((byte)value); - this.writer.Advance(2); - } - else if (value <= ushort.MaxValue) - { - Span span = this.writer.GetSpan(3); - span[0] = MessagePackCode.UInt16; - WriteBigEndian((ushort)value, span.Slice(1)); - this.writer.Advance(3); - } - else - { - this.WriteUInt32(value); - } - } - - /// - /// Writes an using . - /// - /// The value to write. - public void WriteUInt32(uint value) - { - Span span = this.writer.GetSpan(5); - span[0] = MessagePackCode.UInt32; - WriteBigEndian(value, span.Slice(1)); - this.writer.Advance(5); - } - - /// - /// Writes an using a built-in 1-byte code when within specific MessagePack-supported ranges, - /// or the most compact of - /// , - /// , - /// , - /// , - /// , - /// . - /// - /// The value to write. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(int value) - { - if (value >= 0) - { - this.Write((uint)value); - } - else - { - // negative int(use int) - if (value >= MessagePackRange.MinFixNegativeInt) - { - Span span = this.writer.GetSpan(1); - span[0] = unchecked((byte)value); - this.writer.Advance(1); - } - else if (value >= sbyte.MinValue) - { - Span span = this.writer.GetSpan(2); - span[0] = MessagePackCode.Int8; - span[1] = unchecked((byte)value); - this.writer.Advance(2); - } - else if (value >= short.MinValue) - { - Span span = this.writer.GetSpan(3); - span[0] = MessagePackCode.Int16; - WriteBigEndian((short)value, span.Slice(1)); - this.writer.Advance(3); - } - else - { - this.WriteInt32(value); - } - } - } - - /// - /// Writes an using . - /// - /// The value to write. - public void WriteInt32(int value) - { - Span span = this.writer.GetSpan(5); - span[0] = MessagePackCode.Int32; - WriteBigEndian(value, span.Slice(1)); - this.writer.Advance(5); - } - - /// - /// Writes an using a built-in 1-byte code when within specific MessagePack-supported ranges, - /// or the most compact of - /// , - /// , - /// , - /// , - /// , - /// . - /// - /// The value to write. - public void Write(ulong value) - { - if (value <= MessagePackRange.MaxFixPositiveInt) - { - Span span = this.writer.GetSpan(1); - span[0] = unchecked((byte)value); - this.writer.Advance(1); - } - else if (value <= byte.MaxValue) - { - Span span = this.writer.GetSpan(2); - span[0] = MessagePackCode.UInt8; - span[1] = unchecked((byte)value); - this.writer.Advance(2); - } - else if (value <= ushort.MaxValue) - { - Span span = this.writer.GetSpan(3); - span[0] = MessagePackCode.UInt16; - WriteBigEndian((ushort)value, span.Slice(1)); - this.writer.Advance(3); - } - else if (value <= uint.MaxValue) - { - Span span = this.writer.GetSpan(5); - span[0] = MessagePackCode.UInt32; - WriteBigEndian((uint)value, span.Slice(1)); - this.writer.Advance(5); - } - else - { - this.WriteUInt64(value); - } - } - - /// - /// Writes an using . - /// - /// The value to write. - public void WriteUInt64(ulong value) - { - Span span = this.writer.GetSpan(9); - span[0] = MessagePackCode.UInt64; - WriteBigEndian(value, span.Slice(1)); - this.writer.Advance(9); - } - - /// - /// Writes an using a built-in 1-byte code when within specific MessagePack-supported ranges, - /// or the most compact of - /// , - /// , - /// , - /// , - /// , - /// , - /// , - /// . - /// - /// The value to write. - public void Write(long value) - { - if (value >= 0) - { - this.Write((ulong)value); - } - else - { - // negative int(use int) - if (value >= MessagePackRange.MinFixNegativeInt) - { - Span span = this.writer.GetSpan(1); - span[0] = unchecked((byte)value); - this.writer.Advance(1); - } - else if (value >= sbyte.MinValue) - { - Span span = this.writer.GetSpan(2); - span[0] = MessagePackCode.Int8; - span[1] = unchecked((byte)value); - this.writer.Advance(2); - } - else if (value >= short.MinValue) - { - Span span = this.writer.GetSpan(3); - span[0] = MessagePackCode.Int16; - WriteBigEndian((short)value, span.Slice(1)); - this.writer.Advance(3); - } - else if (value >= int.MinValue) - { - Span span = this.writer.GetSpan(5); - span[0] = MessagePackCode.Int32; - WriteBigEndian((int)value, span.Slice(1)); - this.writer.Advance(5); - } - else - { - this.WriteInt64(value); - } - } - } - - /// - /// Writes a using . - /// - /// The value to write. - public void WriteInt64(long value) - { - Span span = this.writer.GetSpan(9); - span[0] = MessagePackCode.Int64; - WriteBigEndian(value, span.Slice(1)); - this.writer.Advance(9); - } - - /// - /// Writes a value using either or . - /// - /// The value. - public void Write(bool value) - { - Span span = this.writer.GetSpan(1); - span[0] = value ? MessagePackCode.True : MessagePackCode.False; - this.writer.Advance(1); - } - - /// - /// Writes a value using a 1-byte code when possible, otherwise as or . - /// - /// The value. - public void Write(char value) => this.Write((ushort)value); - - /// - /// Writes a value. - /// - /// The value. - public void Write(float value) - { - Span span = this.writer.GetSpan(5); - span[0] = MessagePackCode.Float32; - WriteBigEndian(value, span.Slice(1)); - this.writer.Advance(5); - } - - /// - /// Writes a value. - /// - /// The value. - public void Write(double value) - { - Span span = this.writer.GetSpan(9); - span[0] = MessagePackCode.Float64; - WriteBigEndian(value, span.Slice(1)); - this.writer.Advance(9); - } - - /// - /// Writes a using the message code . - /// - /// The value to write. - /// Thrown when is true because the old spec does not define a format. - public void Write(DateTime dateTime) - { - if (this.OldSpec) - { - throw new NotSupportedException($"The MsgPack spec does not define a format for {nameof(DateTime)} in {nameof(this.OldSpec)} mode. Turn off {nameof(this.OldSpec)} mode or use NativeDateTimeFormatter."); - } - else - { - // Timestamp spec - // https://github.com/msgpack/msgpack/pull/209 - // FixExt4(-1) => seconds | [1970-01-01 00:00:00 UTC, 2106-02-07 06:28:16 UTC) range - // FixExt8(-1) => nanoseconds + seconds | [1970-01-01 00:00:00.000000000 UTC, 2514-05-30 01:53:04.000000000 UTC) range - // Ext8(12,-1) => nanoseconds + seconds | [-584554047284-02-23 16:59:44 UTC, 584554051223-11-09 07:00:16.000000000 UTC) range - - // The spec requires UTC. Convert to UTC if we're sure the value was expressed as Local time. - // If it's Unspecified, we want to leave it alone since .NET will change the value when we convert - // and we simply don't know, so we should leave it as-is. - if (dateTime.Kind == DateTimeKind.Local) - { - dateTime = dateTime.ToUniversalTime(); - } - - var secondsSinceBclEpoch = dateTime.Ticks / TimeSpan.TicksPerSecond; - var seconds = secondsSinceBclEpoch - DateTimeConstants.BclSecondsAtUnixEpoch; - var nanoseconds = (dateTime.Ticks % TimeSpan.TicksPerSecond) * DateTimeConstants.NanosecondsPerTick; - - // reference pseudo code. - /* - struct timespec { - long tv_sec; // seconds - long tv_nsec; // nanoseconds - } time; - if ((time.tv_sec >> 34) == 0) - { - uint64_t data64 = (time.tv_nsec << 34) | time.tv_sec; - if (data & 0xffffffff00000000L == 0) - { - // timestamp 32 - uint32_t data32 = data64; - serialize(0xd6, -1, data32) - } - else - { - // timestamp 64 - serialize(0xd7, -1, data64) - } - } - else - { - // timestamp 96 - serialize(0xc7, 12, -1, time.tv_nsec, time.tv_sec) - } - */ - - if ((seconds >> 34) == 0) - { - var data64 = unchecked((ulong)((nanoseconds << 34) | seconds)); - if ((data64 & 0xffffffff00000000L) == 0) - { - // timestamp 32(seconds in 32-bit unsigned int) - var data32 = (UInt32)data64; - Span span = this.writer.GetSpan(6); - span[0] = MessagePackCode.FixExt4; - span[1] = unchecked((byte)ReservedMessagePackExtensionTypeCode.DateTime); - WriteBigEndian(data32, span.Slice(2)); - this.writer.Advance(6); - } - else - { - // timestamp 64(nanoseconds in 30-bit unsigned int | seconds in 34-bit unsigned int) - Span span = this.writer.GetSpan(10); - span[0] = MessagePackCode.FixExt8; - span[1] = unchecked((byte)ReservedMessagePackExtensionTypeCode.DateTime); - WriteBigEndian(data64, span.Slice(2)); - this.writer.Advance(10); - } - } - else - { - // timestamp 96( nanoseconds in 32-bit unsigned int | seconds in 64-bit signed int ) - Span span = this.writer.GetSpan(15); - span[0] = MessagePackCode.Ext8; - span[1] = 12; - span[2] = unchecked((byte)ReservedMessagePackExtensionTypeCode.DateTime); - WriteBigEndian((uint)nanoseconds, span.Slice(3)); - WriteBigEndian(seconds, span.Slice(7)); - this.writer.Advance(15); - } - } - } - - /// - /// Writes a [], prefixed with a length encoded as the smallest fitting from: - /// , - /// , - /// , - /// or if is null. - /// - /// The array of bytes to write. May be null. - public void Write(byte[] src) - { - if (src == null) - { - this.WriteNil(); - } - else - { - this.Write(src.AsSpan()); - } - } - - /// - /// Writes a span of bytes, prefixed with a length encoded as the smallest fitting from: - /// , - /// , or - /// . - /// - /// The span of bytes to write. - /// - /// When is true, the msgpack code used is , or instead. - /// - public void Write(ReadOnlySpan src) - { - int length = (int)src.Length; - this.WriteBinHeader(length); - var span = this.writer.GetSpan(length); - src.CopyTo(span); - this.writer.Advance(length); - } - - /// - /// Writes a sequence of bytes, prefixed with a length encoded as the smallest fitting from: - /// , - /// , or - /// . - /// - /// The span of bytes to write. - /// - /// When is true, the msgpack code used is , or instead. - /// - public void Write(in ReadOnlySequence src) - { - int length = (int)src.Length; - this.WriteBinHeader(length); - var span = this.writer.GetSpan(length); - src.CopyTo(span); - this.writer.Advance(length); - } - - /// - /// Writes the header that precedes a raw binary sequence with a length encoded as the smallest fitting from: - /// , - /// , or - /// . - /// - /// The length of bytes that will be written next. - /// - /// - /// The caller should use or - /// after calling this method to actually write the content. - /// Alternatively a single call to or will take care of the header and content in one call. - /// - /// - /// When is true, the msgpack code used is , or instead. - /// - /// - public void WriteBinHeader(int length) - { - if (this.OldSpec) - { - this.WriteStringHeader(length); - return; - } - - // When we write the header, we'll ask for all the space we need for the payload as well - // as that may help ensure we only allocate a buffer once. - if (length <= byte.MaxValue) - { - var size = length + 2; - Span span = this.writer.GetSpan(size); - - span[0] = MessagePackCode.Bin8; - span[1] = (byte)length; - - this.writer.Advance(2); - } - else if (length <= UInt16.MaxValue) - { - var size = length + 3; - Span span = this.writer.GetSpan(size); - - span[0] = MessagePackCode.Bin16; - WriteBigEndian((ushort)length, span.Slice(1)); - - this.writer.Advance(3); - } - else - { - var size = length + 5; - Span span = this.writer.GetSpan(size); - - span[0] = MessagePackCode.Bin32; - WriteBigEndian(length, span.Slice(1)); - - this.writer.Advance(5); - } - } - - /// - /// Writes out an array of bytes that (may) represent a UTF-8 encoded string, prefixed with the length using one of these message codes: - /// , - /// , - /// , or - /// . - /// - /// The bytes to write. - public void WriteString(in ReadOnlySequence utf8stringBytes) - { - var length = (int)utf8stringBytes.Length; - this.WriteStringHeader(length); - Span span = this.writer.GetSpan(length); - utf8stringBytes.CopyTo(span); - this.writer.Advance(length); - } - - /// - /// Writes out an array of bytes that (may) represent a UTF-8 encoded string, prefixed with the length using one of these message codes: - /// , - /// , - /// , or - /// . - /// - /// The bytes to write. - public void WriteString(ReadOnlySpan utf8stringBytes) - { - var length = utf8stringBytes.Length; - this.WriteStringHeader(length); - Span span = this.writer.GetSpan(length); - utf8stringBytes.CopyTo(span); - this.writer.Advance(length); - } - - /// - /// Writes out the header that may precede a UTF-8 encoded string, prefixed with the length using one of these message codes: - /// , - /// , - /// , or - /// . - /// - /// The number of bytes in the string that will follow this header. - /// - /// The caller should use or - /// after calling this method to actually write the content. - /// Alternatively a single call to or will take care of the header and content in one call. - /// - public void WriteStringHeader(int byteCount) - { - // When we write the header, we'll ask for all the space we need for the payload as well - // as that may help ensure we only allocate a buffer once. - if (byteCount <= MessagePackRange.MaxFixStringLength) - { - Span span = this.writer.GetSpan(byteCount + 1); - span[0] = (byte)(MessagePackCode.MinFixStr | byteCount); - this.writer.Advance(1); - } - else if (byteCount <= byte.MaxValue && !this.OldSpec) - { - Span span = this.writer.GetSpan(byteCount + 2); - span[0] = MessagePackCode.Str8; - span[1] = unchecked((byte)byteCount); - this.writer.Advance(2); - } - else if (byteCount <= ushort.MaxValue) - { - Span span = this.writer.GetSpan(byteCount + 3); - span[0] = MessagePackCode.Str16; - WriteBigEndian((ushort)byteCount, span.Slice(1)); - this.writer.Advance(3); - } - else - { - Span span = this.writer.GetSpan(byteCount + 5); - span[0] = MessagePackCode.Str32; - WriteBigEndian(byteCount, span.Slice(1)); - this.writer.Advance(5); - } - } - - /// - /// Writes out a , prefixed with the length using one of these message codes: - /// , - /// , - /// , - /// , - /// or if the is null. - /// - /// The value to write. May be null. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe void Write(string value) - { - if (value == null) - { - this.WriteNil(); - return; - } - - ref byte buffer = ref this.WriteString_PrepareSpan(value.Length, out int bufferSize, out int useOffset); - fixed (char* pValue = value) - fixed (byte* pBuffer = &buffer) - { - int byteCount = StringEncoding.UTF8.GetBytes(pValue, value.Length, pBuffer + useOffset, bufferSize); - this.WriteString_PostEncoding(pBuffer, useOffset, byteCount); - } - } - - /// - /// Writes out a , prefixed with the length using one of these message codes: - /// , - /// , - /// , - /// . - /// - /// The value to write. - public unsafe void Write(ReadOnlySpan value) - { - ref byte buffer = ref this.WriteString_PrepareSpan(value.Length, out int bufferSize, out int useOffset); - fixed (char* pValue = value) - fixed (byte* pBuffer = &buffer) - { - int byteCount = StringEncoding.UTF8.GetBytes(pValue, value.Length, pBuffer + useOffset, bufferSize); - this.WriteString_PostEncoding(pBuffer, useOffset, byteCount); - } - } - - /// - /// Writes the extension format header, using the smallest one of these codes: - /// , - /// , - /// , - /// , - /// , - /// , - /// , or - /// . - /// - /// The extension header. - public void WriteExtensionFormatHeader(ExtensionHeader extensionHeader) - { - int dataLength = (int)extensionHeader.Length; - byte typeCode = unchecked((byte)extensionHeader.TypeCode); - switch (dataLength) - { - case 1: - Span span = this.writer.GetSpan(2); - span[0] = MessagePackCode.FixExt1; - span[1] = unchecked(typeCode); - this.writer.Advance(2); - return; - case 2: - span = this.writer.GetSpan(2); - span[0] = MessagePackCode.FixExt2; - span[1] = unchecked(typeCode); - this.writer.Advance(2); - return; - case 4: - span = this.writer.GetSpan(2); - span[0] = MessagePackCode.FixExt4; - span[1] = unchecked(typeCode); - this.writer.Advance(2); - return; - case 8: - span = this.writer.GetSpan(2); - span[0] = MessagePackCode.FixExt8; - span[1] = unchecked(typeCode); - this.writer.Advance(2); - return; - case 16: - span = this.writer.GetSpan(2); - span[0] = MessagePackCode.FixExt16; - span[1] = unchecked(typeCode); - this.writer.Advance(2); - return; - default: - unchecked - { - if (dataLength <= byte.MaxValue) - { - span = this.writer.GetSpan(dataLength + 3); - span[0] = MessagePackCode.Ext8; - span[1] = unchecked((byte)dataLength); - span[2] = unchecked(typeCode); - this.writer.Advance(3); - } - else if (dataLength <= UInt16.MaxValue) - { - span = this.writer.GetSpan(dataLength + 4); - span[0] = MessagePackCode.Ext16; - WriteBigEndian((ushort)dataLength, span.Slice(1)); - span[3] = unchecked(typeCode); - this.writer.Advance(4); - } - else - { - span = this.writer.GetSpan(dataLength + 6); - span[0] = MessagePackCode.Ext32; - WriteBigEndian(dataLength, span.Slice(1)); - span[5] = unchecked(typeCode); - this.writer.Advance(6); - } - } - - break; - } - } - - /// - /// Writes an extension format, using the smallest one of these codes: - /// , - /// , - /// , - /// , - /// , - /// , - /// , or - /// . - /// - /// The extension data. - public void WriteExtensionFormat(ExtensionResult extensionData) - { - this.WriteExtensionFormatHeader(extensionData.Header); - this.WriteRaw(extensionData.Data); - } - - /// - /// Gets memory where raw messagepack data can be written. - /// - /// The size of the memory block required. - /// The span of memory to write to. This *may* exceed . - /// - /// After initializing the resulting memory, always follow up with a call to . - /// - /// This is similar in purpose to - /// but provides uninitialized memory for the caller to write to instead of copying initialized memory from elsewhere. - /// - /// - /// - public Span GetSpan(int length) => this.writer.GetSpan(length); - - /// - /// Commits memory previously returned from as initialized. - /// - /// The number of bytes initialized with messagepack data from the previously returned span. - /// - public void Advance(int length) => this.writer.Advance(length); - - /// - /// Writes a 16-bit integer in big endian format. - /// - /// The integer. - internal void WriteBigEndian(ushort value) - { - Span span = this.writer.GetSpan(2); - WriteBigEndian(value, span); - this.writer.Advance(2); - } - - /// - /// Writes a 32-bit integer in big endian format. - /// - /// The integer. - internal void WriteBigEndian(uint value) - { - Span span = this.writer.GetSpan(4); - WriteBigEndian(value, span); - this.writer.Advance(4); - } - - /// - /// Writes a 64-bit integer in big endian format. - /// - /// The integer. - internal void WriteBigEndian(ulong value) - { - Span span = this.writer.GetSpan(8); - WriteBigEndian(value, span); - this.writer.Advance(8); - } - - internal byte[] FlushAndGetArray() - { - if (this.writer.TryGetUncommittedSpan(out ReadOnlySpan span)) - { - return span.ToArray(); - } - else - { - if (this.writer.SequenceRental.Value == null) - { - throw new NotSupportedException("This instance was not initialized to support this operation."); - } - - this.Flush(); - byte[] result = this.writer.SequenceRental.Value.AsReadOnlySequence.ToArray(); - this.writer.SequenceRental.Dispose(); - return result; - } - } - - private static void WriteBigEndian(short value, Span span) => WriteBigEndian(unchecked((ushort)value), span); - - private static void WriteBigEndian(int value, Span span) => WriteBigEndian(unchecked((uint)value), span); - - private static void WriteBigEndian(long value, Span span) => WriteBigEndian(unchecked((ulong)value), span); - - private static void WriteBigEndian(ushort value, Span span) - { - unchecked - { - // Write to highest index first so the JIT skips bounds checks on subsequent writes. - span[1] = (byte)value; - span[0] = (byte)(value >> 8); - } - } - - private static unsafe void WriteBigEndian(ushort value, byte* span) - { - unchecked - { - span[0] = (byte)(value >> 8); - span[1] = (byte)value; - } - } - - private static void WriteBigEndian(uint value, Span span) - { - unchecked - { - // Write to highest index first so the JIT skips bounds checks on subsequent writes. - span[3] = (byte)value; - span[2] = (byte)(value >> 8); - span[1] = (byte)(value >> 16); - span[0] = (byte)(value >> 24); - } - } - - private static unsafe void WriteBigEndian(uint value, byte* span) - { - unchecked - { - span[0] = (byte)(value >> 24); - span[1] = (byte)(value >> 16); - span[2] = (byte)(value >> 8); - span[3] = (byte)value; - } - } - - private static void WriteBigEndian(ulong value, Span span) - { - unchecked - { - // Write to highest index first so the JIT skips bounds checks on subsequent writes. - span[7] = (byte)value; - span[6] = (byte)(value >> 8); - span[5] = (byte)(value >> 16); - span[4] = (byte)(value >> 24); - span[3] = (byte)(value >> 32); - span[2] = (byte)(value >> 40); - span[1] = (byte)(value >> 48); - span[0] = (byte)(value >> 56); - } - } - - private static unsafe void WriteBigEndian(float value, Span span) => WriteBigEndian(*(int*)&value, span); - - private static unsafe void WriteBigEndian(double value, Span span) => WriteBigEndian(*(long*)&value, span); - - /// - /// Estimates the length of the header required for a given string. - /// - /// The length of the string to be written, in characters. - /// Receives the guaranteed length of the returned buffer. - /// Receives the offset within the returned buffer to write the encoded string to. - /// - /// A reference to the first byte in the buffer. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private ref byte WriteString_PrepareSpan(int characterLength, out int bufferSize, out int encodedBytesOffset) - { - // MaxByteCount -> WritePrefix -> GetBytes has some overheads of `MaxByteCount` - // solves heuristic length check - - // ensure buffer by MaxByteCount(faster than GetByteCount) - bufferSize = StringEncoding.UTF8.GetMaxByteCount(characterLength) + 5; - ref byte buffer = ref this.writer.GetPointer(bufferSize); - - int useOffset; - if (characterLength <= MessagePackRange.MaxFixStringLength) - { - useOffset = 1; - } - else if (characterLength <= byte.MaxValue && !this.OldSpec) - { - useOffset = 2; - } - else if (characterLength <= ushort.MaxValue) - { - useOffset = 3; - } - else - { - useOffset = 5; - } - - encodedBytesOffset = useOffset; - return ref buffer; - } - - /// - /// Finalizes an encoding of a string. - /// - /// A pointer obtained from a prior call to . - /// The offset obtained from a prior call to . - /// The number of bytes used to actually encode the string. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private unsafe void WriteString_PostEncoding(byte* pBuffer, int estimatedOffset, int byteCount) - { - int bufferLength = estimatedOffset + byteCount; - - // move body and write prefix - if (byteCount <= MessagePackRange.MaxFixStringLength) - { - if (estimatedOffset != 1) - { - MemoryCopy(pBuffer + estimatedOffset, pBuffer + 1, byteCount, byteCount); - } - - pBuffer[0] = (byte)(MessagePackCode.MinFixStr | byteCount); - this.writer.Advance(byteCount + 1); - } - else if (byteCount <= byte.MaxValue && !this.OldSpec) - { - if (estimatedOffset != 2) - { - MemoryCopy(pBuffer + estimatedOffset, pBuffer + 2, byteCount, byteCount); - } - - pBuffer[0] = MessagePackCode.Str8; - pBuffer[1] = unchecked((byte)byteCount); - this.writer.Advance(byteCount + 2); - } - else if (byteCount <= ushort.MaxValue) - { - if (estimatedOffset != 3) - { - MemoryCopy(pBuffer + estimatedOffset, pBuffer + 3, byteCount, byteCount); - } - - pBuffer[0] = MessagePackCode.Str16; - WriteBigEndian((ushort)byteCount, pBuffer + 1); - this.writer.Advance(byteCount + 3); - } - else - { - if (estimatedOffset != 5) - { - MemoryCopy(pBuffer + estimatedOffset, pBuffer + 5, byteCount, byteCount); - } - - pBuffer[0] = MessagePackCode.Str32; - WriteBigEndian((uint)byteCount, pBuffer + 1); - this.writer.Advance(byteCount + 5); - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe void MemoryCopy(void* source, void* destination, long destinationSizeInBytes, long sourceBytesToCopy) - { - if (Utilities.IsMono) - { - // mono does not guarantee overlapped memcpy so for Unity and NETSTANDARD use slow path. - // https://github.com/neuecc/MessagePack-CSharp/issues/562 - var buffer = ArrayPool.Shared.Rent((int)sourceBytesToCopy); - try - { - fixed (byte* p = buffer) - { - Buffer.MemoryCopy(source, p, sourceBytesToCopy, sourceBytesToCopy); - Buffer.MemoryCopy(p, destination, destinationSizeInBytes, sourceBytesToCopy); - } - } - finally - { - ArrayPool.Shared.Return(buffer); - } - } - else - { - Buffer.MemoryCopy(source, destination, destinationSizeInBytes, sourceBytesToCopy); - } - } - } -} diff --git a/Assets/Plugins/MessagePack/MessagePackWriter.cs.meta b/Assets/Plugins/MessagePack/MessagePackWriter.cs.meta deleted file mode 100644 index cee44775c..000000000 --- a/Assets/Plugins/MessagePack/MessagePackWriter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3855642516b66bac99136d08d7dd7a8e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Nil.cs b/Assets/Plugins/MessagePack/Nil.cs deleted file mode 100644 index 9533d24dd..000000000 --- a/Assets/Plugins/MessagePack/Nil.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; - -namespace MessagePack -{ -#if MESSAGEPACK_INTERNAL - internal -#else - public -#endif - struct Nil : IEquatable - { - public static readonly Nil Default = default(Nil); - - public override bool Equals(object obj) - { - return obj is Nil; - } - - public bool Equals(Nil other) - { - return true; - } - - public override int GetHashCode() - { - return 0; - } - - public override string ToString() - { - return "()"; - } - } -} diff --git a/Assets/Plugins/MessagePack/Nil.cs.meta b/Assets/Plugins/MessagePack/Nil.cs.meta deleted file mode 100644 index 28259fa68..000000000 --- a/Assets/Plugins/MessagePack/Nil.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 7a76d2880a8f9b1f7b740d0c5e62a461 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Resolvers.meta b/Assets/Plugins/MessagePack/Resolvers.meta deleted file mode 100644 index ec940c559..000000000 --- a/Assets/Plugins/MessagePack/Resolvers.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 65a2261e5aa0e2b47b4acee0f027c933 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Resolvers/AttributeFormatterResolver.cs b/Assets/Plugins/MessagePack/Resolvers/AttributeFormatterResolver.cs deleted file mode 100644 index 8532be840..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/AttributeFormatterResolver.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Linq; // require UNITY_2018_3_OR_NEWER -using System.Reflection; -using MessagePack.Formatters; - -namespace MessagePack.Resolvers -{ - /// - /// Get formatter from . - /// - public sealed class AttributeFormatterResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly AttributeFormatterResolver Instance = new AttributeFormatterResolver(); - - private AttributeFormatterResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { -#if UNITY_2018_3_OR_NEWER && !NETFX_CORE - var attr = (MessagePackFormatterAttribute)typeof(T).GetCustomAttributes(typeof(MessagePackFormatterAttribute), true).FirstOrDefault(); -#else - MessagePackFormatterAttribute attr = typeof(T).GetTypeInfo().GetCustomAttribute(); -#endif - if (attr == null) - { - return; - } - - if (attr.Arguments == null) - { - Formatter = (IMessagePackFormatter)Activator.CreateInstance(attr.FormatterType); - } - else - { - Formatter = (IMessagePackFormatter)Activator.CreateInstance(attr.FormatterType, attr.Arguments); - } - } - } - } -} diff --git a/Assets/Plugins/MessagePack/Resolvers/AttributeFormatterResolver.cs.meta b/Assets/Plugins/MessagePack/Resolvers/AttributeFormatterResolver.cs.meta deleted file mode 100644 index 9bba94c8a..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/AttributeFormatterResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f1da7b0fb18e1d4e79aeb7ac56ba9607 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Resolvers/BuiltinResolver.cs b/Assets/Plugins/MessagePack/Resolvers/BuiltinResolver.cs deleted file mode 100644 index 52c3210e6..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/BuiltinResolver.cs +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using System.Text; -using MessagePack.Formatters; -using MessagePack.Internal; -using MessagePack.Resolvers; - -#pragma warning disable SA1403 // File may only contain a single namespace -#pragma warning disable SA1509 // Opening braces should not be preceded by blank line - -namespace MessagePack.Resolvers -{ - public sealed class BuiltinResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly BuiltinResolver Instance = new BuiltinResolver(); - - private BuiltinResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - // Reduce IL2CPP code generate size(don't write long code in ) - Formatter = (IMessagePackFormatter)BuiltinResolverGetFormatterHelper.GetFormatter(typeof(T)); - } - } - } -} - -namespace MessagePack.Internal -{ - internal static class BuiltinResolverGetFormatterHelper - { - private static readonly Dictionary FormatterMap = new Dictionary() - { - // Primitive - { typeof(Int16), Int16Formatter.Instance }, - { typeof(Int32), Int32Formatter.Instance }, - { typeof(Int64), Int64Formatter.Instance }, - { typeof(UInt16), UInt16Formatter.Instance }, - { typeof(UInt32), UInt32Formatter.Instance }, - { typeof(UInt64), UInt64Formatter.Instance }, - { typeof(Single), SingleFormatter.Instance }, - { typeof(Double), DoubleFormatter.Instance }, - { typeof(bool), BooleanFormatter.Instance }, - { typeof(byte), ByteFormatter.Instance }, - { typeof(sbyte), SByteFormatter.Instance }, - { typeof(DateTime), DateTimeFormatter.Instance }, - { typeof(char), CharFormatter.Instance }, - - // Nulllable Primitive - { typeof(Int16?), NullableInt16Formatter.Instance }, - { typeof(Int32?), NullableInt32Formatter.Instance }, - { typeof(Int64?), NullableInt64Formatter.Instance }, - { typeof(UInt16?), NullableUInt16Formatter.Instance }, - { typeof(UInt32?), NullableUInt32Formatter.Instance }, - { typeof(UInt64?), NullableUInt64Formatter.Instance }, - { typeof(Single?), NullableSingleFormatter.Instance }, - { typeof(Double?), NullableDoubleFormatter.Instance }, - { typeof(bool?), NullableBooleanFormatter.Instance }, - { typeof(byte?), NullableByteFormatter.Instance }, - { typeof(sbyte?), NullableSByteFormatter.Instance }, - { typeof(DateTime?), NullableDateTimeFormatter.Instance }, - { typeof(char?), NullableCharFormatter.Instance }, - - // StandardClassLibraryFormatter - { typeof(string), NullableStringFormatter.Instance }, - { typeof(decimal), DecimalFormatter.Instance }, - { typeof(decimal?), new StaticNullableFormatter(DecimalFormatter.Instance) }, - { typeof(TimeSpan), TimeSpanFormatter.Instance }, - { typeof(TimeSpan?), new StaticNullableFormatter(TimeSpanFormatter.Instance) }, - { typeof(DateTimeOffset), DateTimeOffsetFormatter.Instance }, - { typeof(DateTimeOffset?), new StaticNullableFormatter(DateTimeOffsetFormatter.Instance) }, - { typeof(Guid), GuidFormatter.Instance }, - { typeof(Guid?), new StaticNullableFormatter(GuidFormatter.Instance) }, - { typeof(Uri), UriFormatter.Instance }, - { typeof(Version), VersionFormatter.Instance }, - { typeof(StringBuilder), StringBuilderFormatter.Instance }, - { typeof(BitArray), BitArrayFormatter.Instance }, - - // special primitive - { typeof(byte[]), ByteArrayFormatter.Instance }, - - // Nil - { typeof(Nil), NilFormatter.Instance }, - { typeof(Nil?), NullableNilFormatter.Instance }, - - // otpmitized primitive array formatter - { typeof(Int16[]), Int16ArrayFormatter.Instance }, - { typeof(Int32[]), Int32ArrayFormatter.Instance }, - { typeof(Int64[]), Int64ArrayFormatter.Instance }, - { typeof(UInt16[]), UInt16ArrayFormatter.Instance }, - { typeof(UInt32[]), UInt32ArrayFormatter.Instance }, - { typeof(UInt64[]), UInt64ArrayFormatter.Instance }, - { typeof(Single[]), SingleArrayFormatter.Instance }, - { typeof(Double[]), DoubleArrayFormatter.Instance }, - { typeof(Boolean[]), BooleanArrayFormatter.Instance }, - { typeof(SByte[]), SByteArrayFormatter.Instance }, - { typeof(DateTime[]), DateTimeArrayFormatter.Instance }, - { typeof(Char[]), CharArrayFormatter.Instance }, - { typeof(string[]), NullableStringArrayFormatter.Instance }, - - // well known collections - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - - { typeof(object[]), new ArrayFormatter() }, - { typeof(List), new ListFormatter() }, - - { typeof(ArraySegment), ByteArraySegmentFormatter.Instance }, - { typeof(ArraySegment?), new StaticNullableFormatter>(ByteArraySegmentFormatter.Instance) }, - - { typeof(System.Numerics.BigInteger), BigIntegerFormatter.Instance }, - { typeof(System.Numerics.BigInteger?), new StaticNullableFormatter(BigIntegerFormatter.Instance) }, - { typeof(System.Numerics.Complex), ComplexFormatter.Instance }, - { typeof(System.Numerics.Complex?), new StaticNullableFormatter(ComplexFormatter.Instance) }, - }; - - internal static object GetFormatter(Type t) - { - object formatter; - if (FormatterMap.TryGetValue(t, out formatter)) - { - return formatter; - } - - return null; - } - } -} diff --git a/Assets/Plugins/MessagePack/Resolvers/BuiltinResolver.cs.meta b/Assets/Plugins/MessagePack/Resolvers/BuiltinResolver.cs.meta deleted file mode 100644 index d6acb9743..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/BuiltinResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 22f2bfd36b9810653baff3342b3403e7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Resolvers/CachingFormatterResolver.cs b/Assets/Plugins/MessagePack/Resolvers/CachingFormatterResolver.cs deleted file mode 100644 index 4f69183d0..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/CachingFormatterResolver.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using MessagePack.Formatters; -using MessagePack.Internal; - -namespace MessagePack.Resolvers -{ - /// - /// A base class for classes that want to cache their responses for perf reasons. - /// - internal abstract class CachingFormatterResolver : IFormatterResolver - { - /// - /// The cache of types to their formatters. - /// - private readonly ThreadsafeTypeKeyHashTable formatters = new ThreadsafeTypeKeyHashTable(); - - /// - public IMessagePackFormatter GetFormatter() - { - if (!this.formatters.TryGetValue(typeof(T), out IMessagePackFormatter formatter)) - { - formatter = this.GetFormatterCore(); - this.formatters.TryAdd(typeof(T), formatter); - } - - return (IMessagePackFormatter)formatter; - } - - /// - /// Looks up a formatter for a type that has not been previously cached. - /// - /// The type to be formatted. - /// The formatter to use, or null if none found. - protected abstract IMessagePackFormatter GetFormatterCore(); - } -} diff --git a/Assets/Plugins/MessagePack/Resolvers/CachingFormatterResolver.cs.meta b/Assets/Plugins/MessagePack/Resolvers/CachingFormatterResolver.cs.meta deleted file mode 100644 index 43cc41adc..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/CachingFormatterResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 961f65a9ca79040c5b3021c7612f3c08 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Resolvers/CompositeResolver.cs b/Assets/Plugins/MessagePack/Resolvers/CompositeResolver.cs deleted file mode 100644 index daec23554..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/CompositeResolver.cs +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using MessagePack.Formatters; -using MessagePack.Internal; - -namespace MessagePack.Resolvers -{ - /// - /// Represents a collection of formatters and resolvers acting as one. - /// - /// - /// This class is not thread-safe for mutations. It is thread-safe when not being written to. - /// - public static class CompositeResolver - { - private static readonly ReadOnlyDictionary EmptyFormattersByType = new ReadOnlyDictionary(new Dictionary()); - - /// - /// Initializes a new instance of an with the specified formatters and sub-resolvers. - /// - /// - /// A list of instances of to prefer (above the ). - /// The formatters are searched in the order given, so if two formatters support serializing the same type, the first one is used. - /// May not be null, but may be . - /// - /// - /// A list of resolvers to use for serializing types for which does not include a formatter. - /// The resolvers are searched in the order given, so if two resolvers support serializing the same type, the first one is used. - /// May not be null, but may be . - /// - /// - /// An instance of . - /// - public static IFormatterResolver Create(IReadOnlyList formatters, IReadOnlyList resolvers) - { - if (formatters is null) - { - throw new ArgumentNullException(nameof(formatters)); - } - - if (resolvers is null) - { - throw new ArgumentNullException(nameof(resolvers)); - } - - // Make a copy of the resolvers list provided by the caller to guard against them changing it later. - var immutableFormatters = formatters.ToArray(); - var immutableResolvers = resolvers.ToArray(); - - return new CachingResolver(immutableFormatters, immutableResolvers); - } - - public static IFormatterResolver Create(params IFormatterResolver[] resolvers) => Create(Array.Empty(), resolvers); - - public static IFormatterResolver Create(params IMessagePackFormatter[] formatters) => Create(formatters, Array.Empty()); - - private class CachingResolver : IFormatterResolver - { - private readonly ThreadsafeTypeKeyHashTable formattersCache = new ThreadsafeTypeKeyHashTable(); - private readonly IMessagePackFormatter[] subFormatters; - private readonly IFormatterResolver[] subResolvers; - - /// - /// Initializes a new instance of the class. - /// - internal CachingResolver(IMessagePackFormatter[] subFormatters, IFormatterResolver[] subResolvers) - { - this.subFormatters = subFormatters ?? throw new ArgumentNullException(nameof(subFormatters)); - this.subResolvers = subResolvers ?? throw new ArgumentNullException(nameof(subResolvers)); - } - - public IMessagePackFormatter GetFormatter() - { - if (!this.formattersCache.TryGetValue(typeof(T), out IMessagePackFormatter formatter)) - { - foreach (var subFormatter in this.subFormatters) - { - if (subFormatter is IMessagePackFormatter) - { - formatter = subFormatter; - goto CACHE; - } - } - - foreach (IFormatterResolver resolver in this.subResolvers) - { - formatter = resolver.GetFormatter(); - if (formatter != null) - { - goto CACHE; - } - } - -// when not found, cache null. -CACHE: - this.formattersCache.TryAdd(typeof(T), formatter); - } - - return (IMessagePackFormatter)formatter; - } - } - } -} diff --git a/Assets/Plugins/MessagePack/Resolvers/CompositeResolver.cs.meta b/Assets/Plugins/MessagePack/Resolvers/CompositeResolver.cs.meta deleted file mode 100644 index 119460e57..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/CompositeResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ed6833da3299a096c923be585b3372a1 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Resolvers/ContractlessReflectionObjectResolver.cs b/Assets/Plugins/MessagePack/Resolvers/ContractlessReflectionObjectResolver.cs deleted file mode 100644 index 04b9e5e05..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/ContractlessReflectionObjectResolver.cs +++ /dev/null @@ -1,302 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using System.Text; -using MessagePack.Formatters; -using MessagePack.Internal; - -namespace MessagePack.Resolvers -{ - // MEMO: Not completely implemented. - - ////public static class ContractlessReflectionObjectResolver - ////{ - //// // TODO:CamelCase Option? AllowPrivate? - //// public static readonly IFormatterResolver Default = new DefaultResolver(); - //// public static readonly IFormatterResolver Contractless = new ContractlessResolver(); - //// public static readonly IFormatterResolver ContractlessForceStringKey = new ContractlessForceStringResolver(); - - //// class DefaultResolver : IFormatterResolver - //// { - //// const bool ForceStringKey = false; - //// const bool Contractless = false; - //// const bool AllowPrivate = false; - - //// public IMessagePackFormatter GetFormatter() - //// { - //// return Cache.formatter; - //// } - - //// static class Cache - //// { - //// public static readonly IMessagePackFormatter formatter; - - //// static Cache() - //// { - //// var metaInfo = ObjectSerializationInfo.CreateOrNull(typeof(T), ForceStringKey, Contractless, AllowPrivate); - //// if (metaInfo != null) - //// { - //// formatter = new ReflectionObjectFormatter(metaInfo); - //// } - //// } - //// } - //// } - - //// class ContractlessResolver : IFormatterResolver - //// { - //// const bool ForceStringKey = false; - //// const bool Contractless = true; - //// const bool AllowPrivate = false; - - //// public IMessagePackFormatter GetFormatter() - //// { - //// return Cache.formatter; - //// } - - //// static class Cache - //// { - //// public static readonly IMessagePackFormatter formatter; - - //// static Cache() - //// { - //// var metaInfo = ObjectSerializationInfo.CreateOrNull(typeof(T), ForceStringKey, Contractless, AllowPrivate); - //// if (metaInfo != null) - //// { - //// formatter = new ReflectionObjectFormatter(metaInfo); - //// } - //// } - //// } - //// } - - //// class ContractlessForceStringResolver : IFormatterResolver - //// { - //// const bool ForceStringKey = true; - //// const bool Contractless = true; - //// const bool AllowPrivate = false; - - //// public IMessagePackFormatter GetFormatter() - //// { - //// return Cache.formatter; - //// } - - //// static class Cache - //// { - //// public static readonly IMessagePackFormatter formatter; - - //// static Cache() - //// { - //// var metaInfo = ObjectSerializationInfo.CreateOrNull(typeof(T), ForceStringKey, Contractless, AllowPrivate); - //// if (metaInfo != null) - //// { - //// formatter = new ReflectionObjectFormatter(metaInfo); - //// } - //// } - //// } - //// } - - ////} - - ////public class ReflectionObjectFormatter : IMessagePackFormatter - ////{ - //// readonly ObjectSerializationInfo metaInfo; - - //// // for write - //// readonly byte[][] writeMemberNames; - //// readonly ObjectSerializationInfo.EmittableMember[] writeMembers; - - //// // for read - //// readonly int[] constructorParameterIndexes; - //// readonly AutomataDictionary mapMemberDictionary; - //// readonly ObjectSerializationInfo.EmittableMember[] readMembers; - - //// internal ReflectionObjectFormatter(ObjectSerializationInfo metaInfo) - //// { - //// this.metaInfo = metaInfo; - - //// // for write - //// { - //// var memberNameList = new List(metaInfo.Members.Length); - //// var emmitableMemberList = new List(metaInfo.Members.Length); - //// foreach (var item in metaInfo.Members) - //// { - //// if (item.IsWritable) - //// { - //// emmitableMemberList.Add(item); - //// memberNameList.Add(Encoding.UTF8.GetBytes(item.Name)); - //// } - //// } - //// this.writeMemberNames = memberNameList.ToArray(); - //// this.writeMembers = emmitableMemberList.ToArray(); - //// } - //// // for read - //// { - //// var automata = new AutomataDictionary(); - //// var emmitableMemberList = new List(metaInfo.Members.Length); - //// int index = 0; - //// foreach (var item in metaInfo.Members) - //// { - //// if (item.IsReadable) - //// { - //// emmitableMemberList.Add(item); - //// automata.Add(item.Name, index++); - //// } - //// } - //// this.readMembers = emmitableMemberList.ToArray(); - //// this.mapMemberDictionary = automata; - //// } - //// } - - //// public void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options) - //// { - //// // reduce generic method size, avoid write code in type. - //// if (metaInfo.IsIntKey) - //// { - //// return ReflectionObjectFormatterHelper.WriteArraySerialize(metaInfo, writeMembers, ref bytes, offset, value, formatterResolver); - //// } - //// else - //// { - //// return ReflectionObjectFormatterHelper.WriteMapSerialize(metaInfo, writeMembers, writeMemberNames, ref bytes, offset, value, formatterResolver); - //// } - //// } - - //// public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - //// { - //// return (T)ReflectionObjectFormatterHelper.Deserialize(metaInfo, readMembers, constructorParameterIndexes, mapMemberDictionary, bytes, offset, formatterResolver, out readSize); - //// } - ////} - - ////internal static class ReflectionObjectFormatterHelper - ////{ - //// internal static int WriteArraySerialize(ObjectSerializationInfo metaInfo, ObjectSerializationInfo.EmittableMember[] writeMembers, ref byte[] bytes, int offset, object value, IFormatterResolver formatterResolver) - //// { - //// var startOffset = offset; - - //// offset += MessagePackBinary.WriteArrayHeader(ref bytes, offset, writeMembers.Length); - //// foreach (var item in metaInfo.Members) - //// { - //// if (item == null) - //// { - //// offset += MessagePackBinary.WriteNil(ref bytes, offset); - //// } - //// else - //// { - //// var memberValue = item.ReflectionLoadValue(value); - //// offset += MessagePackSerializer.NonGeneric.Serialize(item.Type, ref bytes, offset, memberValue, formatterResolver); - //// } - //// } - - //// return offset - startOffset; - //// } - - //// internal static int WriteMapSerialize(ObjectSerializationInfo metaInfo, ObjectSerializationInfo.EmittableMember[] writeMembers, byte[][] memberNames, ref byte[] bytes, int offset, object value, IFormatterResolver formatterResolver) - //// { - //// var startOffset = offset; - - //// offset += MessagePackBinary.WriteMapHeader(ref bytes, offset, writeMembers.Length); - - //// for (int i = 0; i < writeMembers.Length; i++) - //// { - //// offset += MessagePackBinary.WriteStringBytes(ref bytes, offset, memberNames[i]); - //// var memberValue = writeMembers[i].ReflectionLoadValue(value); - //// offset += MessagePackSerializer.NonGeneric.Serialize(writeMembers[i].Type, ref bytes, offset, memberValue, formatterResolver); - //// } - - //// return offset - startOffset; - //// } - - //// internal static object Deserialize(ObjectSerializationInfo metaInfo, ObjectSerializationInfo.EmittableMember[] readMembers, int[] constructorParameterIndexes, AutomataDictionary mapMemberDictionary, byte[] bytes, int offset, IFormatterResolver formatterResolver, out int readSize) - //// { - //// var startOffset = offset; - //// object[] parameters = null; - - //// var headerType = MessagePackBinary.GetMessagePackType(bytes, offset); - //// if (headerType == MessagePackType.Nil) - //// { - //// readSize = 1; - //// return null; - //// } - //// else if (headerType == MessagePackType.Array) - //// { - //// var arraySize = MessagePackBinary.ReadArrayHeader(bytes, offset, out readSize); - //// offset += readSize; - - //// // ReadValues - //// parameters = new object[arraySize]; - //// for (int i = 0; i < arraySize; i++) - //// { - //// var info = readMembers[i]; - //// if (info != null) - //// { - //// parameters[i] = MessagePackSerializer.NonGeneric.Deserialize(info.Type, bytes, offset, formatterResolver, out readSize); - //// offset += readSize; - //// } - //// else - //// { - //// offset += MessagePackBinary.ReadNextBlock(bytes, offset); - //// } - //// } - //// } - //// else if (headerType == MessagePackType.Map) - //// { - //// var mapSize = MessagePackBinary.ReadMapHeader(bytes, offset, out readSize); - //// offset += readSize; - - //// // ReadValues - //// parameters = new object[mapSize]; - //// for (int i = 0; i < mapSize; i++) - //// { - //// var rawPropName = MessagePackBinary.ReadStringSegment(bytes, offset, out readSize); - //// offset += readSize; - - //// int index; - //// if (mapMemberDictionary.TryGetValue(rawPropName.Array, rawPropName.Offset, rawPropName.Count, out index)) - //// { - //// var info = readMembers[index]; - //// parameters[index] = MessagePackSerializer.NonGeneric.Deserialize(info.Type, bytes, offset, formatterResolver, out readSize); - //// offset += readSize; - //// } - //// else - //// { - //// offset += MessagePackBinary.ReadNextBlock(bytes, offset); - //// } - //// } - //// } - //// else - //// { - //// throw new MessagePackSerializationException("Invalid MessagePackType:" + MessagePackCode.ToFormatName(bytes[offset])); - //// } - - //// // CreateObject - //// object result = null; - //// if (constructorParameterIndexes.Length == 0) - //// { - //// result = Activator.CreateInstance(metaInfo.Type); - //// } - //// else - //// { - //// var args = new object[constructorParameterIndexes.Length]; - //// for (int i = 0; i < constructorParameterIndexes.Length; i++) - //// { - //// args[i] = parameters[constructorParameterIndexes[i]]; - //// } - - //// result = Activator.CreateInstance(metaInfo.Type, args); - //// } - - //// // SetMembers - //// for (int i = 0; i < readMembers.Length; i++) - //// { - //// var info = readMembers[i]; - //// if (info != null) - //// { - //// info.ReflectionStoreValue(result, parameters[i]); - //// } - //// } - - //// readSize = offset - startOffset; - //// return result; - //// } - ////} -} diff --git a/Assets/Plugins/MessagePack/Resolvers/ContractlessReflectionObjectResolver.cs.meta b/Assets/Plugins/MessagePack/Resolvers/ContractlessReflectionObjectResolver.cs.meta deleted file mode 100644 index e5eb91669..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/ContractlessReflectionObjectResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 953431b29940de61a8da84acda591d9e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Resolvers/DynamicEnumAsStringResolver.cs b/Assets/Plugins/MessagePack/Resolvers/DynamicEnumAsStringResolver.cs deleted file mode 100644 index f31bb2ac9..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/DynamicEnumAsStringResolver.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Reflection; -using MessagePack.Formatters; -using MessagePack.Internal; - -namespace MessagePack.Resolvers -{ - public sealed class DynamicEnumAsStringResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly DynamicEnumAsStringResolver Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - static DynamicEnumAsStringResolver() - { - Instance = new DynamicEnumAsStringResolver(); - Options = new MessagePackSerializerOptions(Instance); - } - - private DynamicEnumAsStringResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - TypeInfo ti = typeof(T).GetTypeInfo(); - - if (ti.IsNullable()) - { - // build underlying type and use wrapped formatter. - ti = ti.GenericTypeArguments[0].GetTypeInfo(); - if (!ti.IsEnum) - { - return; - } - - var innerFormatter = DynamicEnumAsStringResolver.Instance.GetFormatterDynamic(ti.AsType()); - if (innerFormatter == null) - { - return; - } - - Formatter = (IMessagePackFormatter)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); - return; - } - else if (!ti.IsEnum) - { - return; - } - - Formatter = (IMessagePackFormatter)(object)new EnumAsStringFormatter(); - } - } - } -} diff --git a/Assets/Plugins/MessagePack/Resolvers/DynamicEnumAsStringResolver.cs.meta b/Assets/Plugins/MessagePack/Resolvers/DynamicEnumAsStringResolver.cs.meta deleted file mode 100644 index 148e98eb8..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/DynamicEnumAsStringResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 54a09685d140ed621bbd779af8f4e6cc -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Resolvers/DynamicEnumResolver.cs b/Assets/Plugins/MessagePack/Resolvers/DynamicEnumResolver.cs deleted file mode 100644 index 07ccaa7f6..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/DynamicEnumResolver.cs +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if !(UNITY_2018_3_OR_NEWER && NET_STANDARD_2_0) - -using System; -using System.Buffers; -using System.Reflection; -using System.Reflection.Emit; -using System.Threading; -using MessagePack.Formatters; -using MessagePack.Internal; - -namespace MessagePack.Resolvers -{ - /// - /// EnumResolver by dynamic code generation, serialized underlying type. - /// - public sealed class DynamicEnumResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly DynamicEnumResolver Instance = new DynamicEnumResolver(); - - private const string ModuleName = "MessagePack.Resolvers.DynamicEnumResolver"; - - private static readonly DynamicAssembly DynamicAssembly; - - private static int nameSequence = 0; - - private DynamicEnumResolver() - { - } - - static DynamicEnumResolver() - { - DynamicAssembly = new DynamicAssembly(ModuleName); - } - -#if NETFRAMEWORK - public AssemblyBuilder Save() - { - return DynamicAssembly.Save(); - } -#endif - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - TypeInfo ti = typeof(T).GetTypeInfo(); - if (ti.IsNullable()) - { - // build underlying type and use wrapped formatter. - ti = ti.GenericTypeArguments[0].GetTypeInfo(); - if (!ti.IsEnum) - { - return; - } - - var innerFormatter = DynamicEnumResolver.Instance.GetFormatterDynamic(ti.AsType()); - if (innerFormatter == null) - { - return; - } - - Formatter = (IMessagePackFormatter)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); - return; - } - else if (!ti.IsEnum) - { - return; - } - - TypeInfo formatterTypeInfo = BuildType(typeof(T)); - Formatter = (IMessagePackFormatter)Activator.CreateInstance(formatterTypeInfo.AsType()); - } - } - - private static TypeInfo BuildType(Type enumType) - { - Type underlyingType = Enum.GetUnderlyingType(enumType); - Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(enumType); - - TypeBuilder typeBuilder = DynamicAssembly.DefineType("MessagePack.Formatters." + enumType.FullName.Replace(".", "_") + "Formatter" + Interlocked.Increment(ref nameSequence), TypeAttributes.Public | TypeAttributes.Sealed, null, new[] { formatterType }); - - // void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options); - { - MethodBuilder method = typeBuilder.DefineMethod( - "Serialize", - MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual, - null, - new Type[] { typeof(MessagePackWriter).MakeByRefType(), enumType, typeof(MessagePackSerializerOptions) }); - - ILGenerator il = method.GetILGenerator(); - il.Emit(OpCodes.Ldarg_1); - il.Emit(OpCodes.Ldarg_2); - il.Emit(OpCodes.Call, typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.Write), new[] { underlyingType })); - il.Emit(OpCodes.Ret); - } - - // T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options); - { - MethodBuilder method = typeBuilder.DefineMethod( - "Deserialize", - MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual, - enumType, - new Type[] { typeof(MessagePackReader).MakeByRefType(), typeof(MessagePackSerializerOptions) }); - - ILGenerator il = method.GetILGenerator(); - il.Emit(OpCodes.Ldarg_1); - il.Emit(OpCodes.Call, typeof(MessagePackReader).GetRuntimeMethod("Read" + underlyingType.Name, Type.EmptyTypes)); - il.Emit(OpCodes.Ret); - } - - return typeBuilder.CreateTypeInfo(); - } - } -} - -#endif diff --git a/Assets/Plugins/MessagePack/Resolvers/DynamicEnumResolver.cs.meta b/Assets/Plugins/MessagePack/Resolvers/DynamicEnumResolver.cs.meta deleted file mode 100644 index 0a79f17c7..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/DynamicEnumResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 56f454cdc164d6a03bcb2dd11fa9e73a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Resolvers/DynamicGenericResolver.cs b/Assets/Plugins/MessagePack/Resolvers/DynamicGenericResolver.cs deleted file mode 100644 index 94d72820c..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/DynamicGenericResolver.cs +++ /dev/null @@ -1,284 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.Reflection; -using System.Threading.Tasks; -using MessagePack.Formatters; -using MessagePack.Internal; - -#pragma warning disable SA1403 // File may only contain a single namespace - -namespace MessagePack.Resolvers -{ - public sealed class DynamicGenericResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly DynamicGenericResolver Instance = new DynamicGenericResolver(); - - private DynamicGenericResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - Formatter = (IMessagePackFormatter)DynamicGenericResolverGetFormatterHelper.GetFormatter(typeof(T)); - } - } - } -} - -namespace MessagePack.Internal -{ - internal static class DynamicGenericResolverGetFormatterHelper - { - private static readonly Dictionary FormatterMap = new Dictionary() - { - { typeof(List<>), typeof(ListFormatter<>) }, - { typeof(LinkedList<>), typeof(LinkedListFormatter<>) }, - { typeof(Queue<>), typeof(QueueFormatter<>) }, - { typeof(Stack<>), typeof(StackFormatter<>) }, - { typeof(HashSet<>), typeof(HashSetFormatter<>) }, - { typeof(ReadOnlyCollection<>), typeof(ReadOnlyCollectionFormatter<>) }, - { typeof(IList<>), typeof(InterfaceListFormatter2<>) }, - { typeof(ICollection<>), typeof(InterfaceCollectionFormatter2<>) }, - { typeof(IEnumerable<>), typeof(InterfaceEnumerableFormatter<>) }, - { typeof(Dictionary<,>), typeof(DictionaryFormatter<,>) }, - { typeof(IDictionary<,>), typeof(InterfaceDictionaryFormatter<,>) }, - { typeof(SortedDictionary<,>), typeof(SortedDictionaryFormatter<,>) }, - { typeof(SortedList<,>), typeof(SortedListFormatter<,>) }, - { typeof(ILookup<,>), typeof(InterfaceLookupFormatter<,>) }, - { typeof(IGrouping<,>), typeof(InterfaceGroupingFormatter<,>) }, - { typeof(ObservableCollection<>), typeof(ObservableCollectionFormatter<>) }, - { typeof(ReadOnlyObservableCollection<>), typeof(ReadOnlyObservableCollectionFormatter<>) }, - { typeof(IReadOnlyList<>), typeof(InterfaceReadOnlyListFormatter<>) }, - { typeof(IReadOnlyCollection<>), typeof(InterfaceReadOnlyCollectionFormatter<>) }, - { typeof(ISet<>), typeof(InterfaceSetFormatter<>) }, - { typeof(System.Collections.Concurrent.ConcurrentBag<>), typeof(ConcurrentBagFormatter<>) }, - { typeof(System.Collections.Concurrent.ConcurrentQueue<>), typeof(ConcurrentQueueFormatter<>) }, - { typeof(System.Collections.Concurrent.ConcurrentStack<>), typeof(ConcurrentStackFormatter<>) }, - { typeof(ReadOnlyDictionary<,>), typeof(ReadOnlyDictionaryFormatter<,>) }, - { typeof(IReadOnlyDictionary<,>), typeof(InterfaceReadOnlyDictionaryFormatter<,>) }, - { typeof(System.Collections.Concurrent.ConcurrentDictionary<,>), typeof(ConcurrentDictionaryFormatter<,>) }, - { typeof(Lazy<>), typeof(LazyFormatter<>) }, - }; - - // Reduce IL2CPP code generate size(don't write long code in ) - internal static object GetFormatter(Type t) - { - TypeInfo ti = t.GetTypeInfo(); - - if (t.IsArray) - { - var rank = t.GetArrayRank(); - if (rank == 1) - { - if (t.GetElementType() == typeof(byte)) - { - // byte[] is also supported in builtin formatter. - return ByteArrayFormatter.Instance; - } - - return Activator.CreateInstance(typeof(ArrayFormatter<>).MakeGenericType(t.GetElementType())); - } - else if (rank == 2) - { - return Activator.CreateInstance(typeof(TwoDimensionalArrayFormatter<>).MakeGenericType(t.GetElementType())); - } - else if (rank == 3) - { - return Activator.CreateInstance(typeof(ThreeDimensionalArrayFormatter<>).MakeGenericType(t.GetElementType())); - } - else if (rank == 4) - { - return Activator.CreateInstance(typeof(FourDimensionalArrayFormatter<>).MakeGenericType(t.GetElementType())); - } - else - { - return null; // not supported built-in - } - } - else if (ti.IsGenericType) - { - Type genericType = ti.GetGenericTypeDefinition(); - TypeInfo genericTypeInfo = genericType.GetTypeInfo(); - var isNullable = genericTypeInfo.IsNullable(); - Type nullableElementType = isNullable ? ti.GenericTypeArguments[0] : null; - - if (genericType == typeof(KeyValuePair<,>)) - { - return CreateInstance(typeof(KeyValuePairFormatter<,>), ti.GenericTypeArguments); - } - - // Tuple - else if (ti.FullName.StartsWith("System.Tuple")) - { - Type tupleFormatterType = null; - switch (ti.GenericTypeArguments.Length) - { - case 1: - tupleFormatterType = typeof(TupleFormatter<>); - break; - case 2: - tupleFormatterType = typeof(TupleFormatter<,>); - break; - case 3: - tupleFormatterType = typeof(TupleFormatter<,,>); - break; - case 4: - tupleFormatterType = typeof(TupleFormatter<,,,>); - break; - case 5: - tupleFormatterType = typeof(TupleFormatter<,,,,>); - break; - case 6: - tupleFormatterType = typeof(TupleFormatter<,,,,,>); - break; - case 7: - tupleFormatterType = typeof(TupleFormatter<,,,,,,>); - break; - case 8: - tupleFormatterType = typeof(TupleFormatter<,,,,,,,>); - break; - default: - break; - } - - return CreateInstance(tupleFormatterType, ti.GenericTypeArguments); - } - - // ValueTuple - else if (ti.FullName.StartsWith("System.ValueTuple")) - { - Type tupleFormatterType = null; - switch (ti.GenericTypeArguments.Length) - { - case 1: - tupleFormatterType = typeof(ValueTupleFormatter<>); - break; - case 2: - tupleFormatterType = typeof(ValueTupleFormatter<,>); - break; - case 3: - tupleFormatterType = typeof(ValueTupleFormatter<,,>); - break; - case 4: - tupleFormatterType = typeof(ValueTupleFormatter<,,,>); - break; - case 5: - tupleFormatterType = typeof(ValueTupleFormatter<,,,,>); - break; - case 6: - tupleFormatterType = typeof(ValueTupleFormatter<,,,,,>); - break; - case 7: - tupleFormatterType = typeof(ValueTupleFormatter<,,,,,,>); - break; - case 8: - tupleFormatterType = typeof(ValueTupleFormatter<,,,,,,,>); - break; - default: - break; - } - - return CreateInstance(tupleFormatterType, ti.GenericTypeArguments); - } - - // ArraySegement - else if (genericType == typeof(ArraySegment<>)) - { - if (ti.GenericTypeArguments[0] == typeof(byte)) - { - return ByteArraySegmentFormatter.Instance; - } - else - { - return CreateInstance(typeof(ArraySegmentFormatter<>), ti.GenericTypeArguments); - } - } - - // Standard Nullable - else if (isNullable) - { - return CreateInstance(typeof(NullableFormatter<>), new[] { nullableElementType }); - } - - // Mapped formatter - else - { - Type formatterType; - if (FormatterMap.TryGetValue(genericType, out formatterType)) - { - return CreateInstance(formatterType, ti.GenericTypeArguments); - } - - // generic collection - else if (ti.GenericTypeArguments.Length == 1 - && ti.ImplementedInterfaces.Any(x => x.GetTypeInfo().IsConstructedGenericType() && x.GetGenericTypeDefinition() == typeof(ICollection<>)) - && ti.DeclaredConstructors.Any(x => x.GetParameters().Length == 0)) - { - Type elemType = ti.GenericTypeArguments[0]; - return CreateInstance(typeof(GenericCollectionFormatter<,>), new[] { elemType, t }); - } - - // generic dictionary - else if (ti.GenericTypeArguments.Length == 2 - && ti.ImplementedInterfaces.Any(x => x.GetTypeInfo().IsConstructedGenericType() && x.GetGenericTypeDefinition() == typeof(IDictionary<,>)) - && ti.DeclaredConstructors.Any(x => x.GetParameters().Length == 0)) - { - Type keyType = ti.GenericTypeArguments[0]; - Type valueType = ti.GenericTypeArguments[1]; - return CreateInstance(typeof(GenericDictionaryFormatter<,,>), new[] { keyType, valueType, t }); - } - } - } - else if (ti.IsEnum) - { - return CreateInstance(typeof(GenericEnumFormatter<>), new[] { t }); - } - else - { - // NonGeneric Collection - if (t == typeof(IList)) - { - return NonGenericInterfaceListFormatter.Instance; - } - else if (t == typeof(IDictionary)) - { - return NonGenericInterfaceDictionaryFormatter.Instance; - } - - if (typeof(IList).GetTypeInfo().IsAssignableFrom(ti) && ti.DeclaredConstructors.Any(x => x.GetParameters().Length == 0)) - { - return Activator.CreateInstance(typeof(NonGenericListFormatter<>).MakeGenericType(t)); - } - else if (typeof(IDictionary).GetTypeInfo().IsAssignableFrom(ti) && ti.DeclaredConstructors.Any(x => x.GetParameters().Length == 0)) - { - return Activator.CreateInstance(typeof(NonGenericDictionaryFormatter<>).MakeGenericType(t)); - } - } - - return null; - } - - private static object CreateInstance(Type genericType, Type[] genericTypeArguments, params object[] arguments) - { - return Activator.CreateInstance(genericType.MakeGenericType(genericTypeArguments), arguments); - } - } -} diff --git a/Assets/Plugins/MessagePack/Resolvers/DynamicGenericResolver.cs.meta b/Assets/Plugins/MessagePack/Resolvers/DynamicGenericResolver.cs.meta deleted file mode 100644 index ce3133db6..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/DynamicGenericResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c97d6b550962b8536b1363db3bd98cae -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Resolvers/DynamicObjectResolver.cs b/Assets/Plugins/MessagePack/Resolvers/DynamicObjectResolver.cs deleted file mode 100644 index 90a6772ed..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/DynamicObjectResolver.cs +++ /dev/null @@ -1,2071 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if !(UNITY_2018_3_OR_NEWER && NET_STANDARD_2_0) - -using System; -using System.Buffers; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Reflection.Emit; -using System.Runtime.Serialization; -using System.Text.RegularExpressions; -using System.Threading; -using MessagePack.Formatters; -using MessagePack.Internal; - -#pragma warning disable SA1403 // File may only contain a single namespace - -namespace MessagePack.Resolvers -{ - /// - /// ObjectResolver by dynamic code generation. - /// - public sealed class DynamicObjectResolver : IFormatterResolver - { - private const string ModuleName = "MessagePack.Resolvers.DynamicObjectResolver"; - - /// - /// The singleton instance that can be used. - /// - public static readonly DynamicObjectResolver Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - internal static readonly DynamicAssembly DynamicAssembly; - - static DynamicObjectResolver() - { - Instance = new DynamicObjectResolver(); - Options = new MessagePackSerializerOptions(Instance); - DynamicAssembly = new DynamicAssembly(ModuleName); - } - - private DynamicObjectResolver() - { - } - -#if NETFRAMEWORK - public AssemblyBuilder Save() - { - return DynamicAssembly.Save(); - } -#endif - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - TypeInfo ti = typeof(T).GetTypeInfo(); - - if (ti.IsInterface) - { - return; - } - - if (ti.IsNullable()) - { - ti = ti.GenericTypeArguments[0].GetTypeInfo(); - - var innerFormatter = DynamicObjectResolver.Instance.GetFormatterDynamic(ti.AsType()); - if (innerFormatter == null) - { - return; - } - - Formatter = (IMessagePackFormatter)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); - return; - } - - if (ti.IsAnonymous()) - { - Formatter = (IMessagePackFormatter)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), true, true, false); - return; - } - - TypeInfo formatterTypeInfo = DynamicObjectTypeBuilder.BuildType(DynamicAssembly, typeof(T), false, false); - if (formatterTypeInfo == null) - { - return; - } - - Formatter = (IMessagePackFormatter)Activator.CreateInstance(formatterTypeInfo.AsType()); - } - } - } - - /// - /// ObjectResolver by dynamic code generation, allow private member. - /// - public sealed class DynamicObjectResolverAllowPrivate : IFormatterResolver - { - public static readonly DynamicObjectResolverAllowPrivate Instance = new DynamicObjectResolverAllowPrivate(); - - private DynamicObjectResolverAllowPrivate() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - internal static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - TypeInfo ti = typeof(T).GetTypeInfo(); - - if (ti.IsInterface) - { - return; - } - - if (ti.IsNullable()) - { - ti = ti.GenericTypeArguments[0].GetTypeInfo(); - - var innerFormatter = DynamicObjectResolverAllowPrivate.Instance.GetFormatterDynamic(ti.AsType()); - if (innerFormatter == null) - { - return; - } - - Formatter = (IMessagePackFormatter)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); - return; - } - - if (ti.IsAnonymous()) - { - Formatter = (IMessagePackFormatter)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), true, true, false); - } - else - { - Formatter = (IMessagePackFormatter)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), false, false, true); - } - } - } - } - - /// - /// ObjectResolver by dynamic code generation, no needs MessagePackObject attribute and serialized key as string. - /// - public sealed class DynamicContractlessObjectResolver : IFormatterResolver - { - public static readonly DynamicContractlessObjectResolver Instance = new DynamicContractlessObjectResolver(); - - private const string ModuleName = "MessagePack.Resolvers.DynamicContractlessObjectResolver"; - - private static readonly DynamicAssembly DynamicAssembly; - - private DynamicContractlessObjectResolver() - { - } - - static DynamicContractlessObjectResolver() - { - DynamicAssembly = new DynamicAssembly(ModuleName); - } - -#if NETFRAMEWORK - public AssemblyBuilder Save() - { - return DynamicAssembly.Save(); - } -#endif - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - if (typeof(T) == typeof(object)) - { - return; - } - - TypeInfo ti = typeof(T).GetTypeInfo(); - - if (ti.IsInterface) - { - return; - } - - if (ti.IsNullable()) - { - ti = ti.GenericTypeArguments[0].GetTypeInfo(); - - var innerFormatter = DynamicContractlessObjectResolver.Instance.GetFormatterDynamic(ti.AsType()); - if (innerFormatter == null) - { - return; - } - - Formatter = (IMessagePackFormatter)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); - return; - } - - if (ti.IsAnonymous()) - { - Formatter = (IMessagePackFormatter)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), true, true, false); - return; - } - - TypeInfo formatterTypeInfo = DynamicObjectTypeBuilder.BuildType(DynamicAssembly, typeof(T), true, true); - if (formatterTypeInfo == null) - { - return; - } - - Formatter = (IMessagePackFormatter)Activator.CreateInstance(formatterTypeInfo.AsType()); - } - } - } - - /// - /// ObjectResolver by dynamic code generation, no needs MessagePackObject attribute and serialized key as string, allow private member. - /// - public sealed class DynamicContractlessObjectResolverAllowPrivate : IFormatterResolver - { - public static readonly DynamicContractlessObjectResolverAllowPrivate Instance = new DynamicContractlessObjectResolverAllowPrivate(); - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - internal static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - if (typeof(T) == typeof(object)) - { - return; - } - - TypeInfo ti = typeof(T).GetTypeInfo(); - - if (ti.IsInterface) - { - return; - } - - if (ti.IsNullable()) - { - ti = ti.GenericTypeArguments[0].GetTypeInfo(); - - var innerFormatter = DynamicContractlessObjectResolverAllowPrivate.Instance.GetFormatterDynamic(ti.AsType()); - if (innerFormatter == null) - { - return; - } - - Formatter = (IMessagePackFormatter)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); - return; - } - - if (ti.IsAnonymous()) - { - Formatter = (IMessagePackFormatter)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), true, true, false); - } - else - { - Formatter = (IMessagePackFormatter)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), true, true, true); - } - } - } - } -} - -namespace MessagePack.Internal -{ - internal static class DynamicObjectTypeBuilder - { -#if !UNITY_2018_3_OR_NEWER - private static readonly Regex SubtractFullNameRegex = new Regex(@", Version=\d+.\d+.\d+.\d+, Culture=\w+, PublicKeyToken=\w+", RegexOptions.Compiled); -#else - static readonly Regex SubtractFullNameRegex = new Regex(@", Version=\d+.\d+.\d+.\d+, Culture=\w+, PublicKeyToken=\w+"); -#endif - - private static int nameSequence = 0; - - private static HashSet ignoreTypes = new HashSet - { - { typeof(object) }, - { typeof(short) }, - { typeof(int) }, - { typeof(long) }, - { typeof(ushort) }, - { typeof(uint) }, - { typeof(ulong) }, - { typeof(float) }, - { typeof(double) }, - { typeof(bool) }, - { typeof(byte) }, - { typeof(sbyte) }, - { typeof(decimal) }, - { typeof(char) }, - { typeof(string) }, - { typeof(System.Guid) }, - { typeof(System.TimeSpan) }, - { typeof(System.DateTime) }, - { typeof(System.DateTimeOffset) }, - { typeof(MessagePack.Nil) }, - }; - - public static TypeInfo BuildType(DynamicAssembly assembly, Type type, bool forceStringKey, bool contractless) - { - if (ignoreTypes.Contains(type)) - { - return null; - } - - var serializationInfo = MessagePack.Internal.ObjectSerializationInfo.CreateOrNull(type, forceStringKey, contractless, false); - if (serializationInfo == null) - { - return null; - } - - if (!(type.IsPublic || type.IsNestedPublic)) - { - throw new MessagePackSerializationException("Building dynamic formatter only allows public type. Type: " + type.FullName); - } - - Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(type); - TypeBuilder typeBuilder = assembly.DefineType("MessagePack.Formatters." + SubtractFullNameRegex.Replace(type.FullName, string.Empty).Replace(".", "_") + "Formatter" + Interlocked.Increment(ref nameSequence), TypeAttributes.Public | TypeAttributes.Sealed, null, new[] { formatterType }); - - FieldBuilder stringByteKeysField = null; - Dictionary customFormatterLookup = null; - - // string key needs string->int mapper for deserialize switch statement - if (serializationInfo.IsStringKey) - { - ConstructorBuilder method = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes); - stringByteKeysField = typeBuilder.DefineField("stringByteKeys", typeof(byte[][]), FieldAttributes.Private | FieldAttributes.InitOnly); - - ILGenerator il = method.GetILGenerator(); - BuildConstructor(type, serializationInfo, method, stringByteKeysField, il); - customFormatterLookup = BuildCustomFormatterField(typeBuilder, serializationInfo, il); - il.Emit(OpCodes.Ret); - } - else - { - ConstructorBuilder method = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes); - ILGenerator il = method.GetILGenerator(); - il.EmitLoadThis(); - il.Emit(OpCodes.Call, objectCtor); - customFormatterLookup = BuildCustomFormatterField(typeBuilder, serializationInfo, il); - il.Emit(OpCodes.Ret); - } - - { - MethodBuilder method = typeBuilder.DefineMethod( - "Serialize", - MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual, - returnType: null, - parameterTypes: new Type[] { typeof(MessagePackWriter).MakeByRefType(), type, typeof(MessagePackSerializerOptions) }); - method.DefineParameter(1, ParameterAttributes.None, "writer"); - method.DefineParameter(2, ParameterAttributes.None, "value"); - method.DefineParameter(3, ParameterAttributes.None, "options"); - - ILGenerator il = method.GetILGenerator(); - BuildSerialize( - type, - serializationInfo, - il, - () => - { - il.EmitLoadThis(); - il.EmitLdfld(stringByteKeysField); - }, - (index, member) => - { - FieldInfo fi; - if (!customFormatterLookup.TryGetValue(member, out fi)) - { - return null; - } - - return () => - { - il.EmitLoadThis(); - il.EmitLdfld(fi); - }; - }, - 1); - } - - { - MethodBuilder method = typeBuilder.DefineMethod( - "Deserialize", - MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual, - type, - new Type[] { refMessagePackReader, typeof(MessagePackSerializerOptions) }); - method.DefineParameter(1, ParameterAttributes.None, "reader"); - method.DefineParameter(2, ParameterAttributes.None, "options"); - - ILGenerator il = method.GetILGenerator(); - BuildDeserialize( - type, - serializationInfo, - il, - (index, member) => - { - FieldInfo fi; - if (!customFormatterLookup.TryGetValue(member, out fi)) - { - return null; - } - - return () => - { - il.EmitLoadThis(); - il.EmitLdfld(fi); - }; - }, - 1); // firstArgIndex:0 is this. - } - - return typeBuilder.CreateTypeInfo(); - } - - public static object BuildFormatterToDynamicMethod(Type type, bool forceStringKey, bool contractless, bool allowPrivate) - { - var serializationInfo = ObjectSerializationInfo.CreateOrNull(type, forceStringKey, contractless, allowPrivate); - if (serializationInfo == null) - { - return null; - } - - // internal delegate void AnonymousSerializeFunc(byte[][] stringByteKeysField, object[] customFormatters, ref MessagePackWriter writer, T value, MessagePackSerializerOptions options); - // internal delegate T AnonymousDeserializeFunc(object[] customFormatters, ref MessagePackReader reader, MessagePackSerializerOptions options); - var serialize = new DynamicMethod("Serialize", null, new[] { typeof(byte[][]), typeof(object[]), typeof(MessagePackWriter).MakeByRefType(), type, typeof(MessagePackSerializerOptions) }, type, true); - DynamicMethod deserialize = null; - - List stringByteKeysField = new List(); - List serializeCustomFormatters = new List(); - List deserializeCustomFormatters = new List(); - - if (serializationInfo.IsStringKey) - { - var i = 0; - foreach (ObjectSerializationInfo.EmittableMember item in serializationInfo.Members.Where(x => x.IsReadable)) - { - stringByteKeysField.Add(Utilities.GetWriterBytes(item.StringKey, (ref MessagePackWriter writer, string arg) => writer.Write(arg))); - i++; - } - } - - foreach (ObjectSerializationInfo.EmittableMember item in serializationInfo.Members.Where(x => x.IsReadable)) - { - MessagePackFormatterAttribute attr = item.GetMessagePackFormatterAttribute(); - if (attr != null) - { - var formatter = Activator.CreateInstance(attr.FormatterType, attr.Arguments); - serializeCustomFormatters.Add(formatter); - } - else - { - serializeCustomFormatters.Add(null); - } - } - - foreach (ObjectSerializationInfo.EmittableMember item in serializationInfo.Members) - { - // not only for writable because for use ctor. - MessagePackFormatterAttribute attr = item.GetMessagePackFormatterAttribute(); - if (attr != null) - { - var formatter = Activator.CreateInstance(attr.FormatterType, attr.Arguments); - deserializeCustomFormatters.Add(formatter); - } - else - { - deserializeCustomFormatters.Add(null); - } - } - - { - ILGenerator il = serialize.GetILGenerator(); - BuildSerialize( - type, - serializationInfo, - il, - () => - { - il.EmitLdarg(0); - }, - (index, member) => - { - if (serializeCustomFormatters.Count == 0) - { - return null; - } - - if (serializeCustomFormatters[index] == null) - { - return null; - } - - return () => - { - il.EmitLdarg(1); // read object[] - il.EmitLdc_I4(index); - il.Emit(OpCodes.Ldelem_Ref); // object - il.Emit(OpCodes.Castclass, serializeCustomFormatters[index].GetType()); - }; - }, - 2); // 0, 1 is parameter. - } - - if (serializationInfo.IsStruct || serializationInfo.BestmatchConstructor != null) - { - deserialize = new DynamicMethod("Deserialize", type, new[] { typeof(object[]), refMessagePackReader, typeof(MessagePackSerializerOptions) }, type, true); - - ILGenerator il = deserialize.GetILGenerator(); - BuildDeserialize( - type, - serializationInfo, - il, - (index, member) => - { - if (deserializeCustomFormatters.Count == 0) - { - return null; - } - - if (deserializeCustomFormatters[index] == null) - { - return null; - } - - return () => - { - il.EmitLdarg(0); // read object[] - il.EmitLdc_I4(index); - il.Emit(OpCodes.Ldelem_Ref); // object - il.Emit(OpCodes.Castclass, deserializeCustomFormatters[index].GetType()); - }; - }, - 1); - } - - object serializeDelegate = serialize.CreateDelegate(typeof(AnonymousSerializeFunc<>).MakeGenericType(type)); - object deserializeDelegate = (deserialize == null) - ? (object)null - : (object)deserialize.CreateDelegate(typeof(AnonymousDeserializeFunc<>).MakeGenericType(type)); - var resultFormatter = Activator.CreateInstance( - typeof(AnonymousSerializableFormatter<>).MakeGenericType(type), - new[] { stringByteKeysField.ToArray(), serializeCustomFormatters.ToArray(), deserializeCustomFormatters.ToArray(), serializeDelegate, deserializeDelegate }); - return resultFormatter; - } - - private static void BuildConstructor(Type type, ObjectSerializationInfo info, ConstructorInfo method, FieldBuilder stringByteKeysField, ILGenerator il) - { - il.EmitLoadThis(); - il.Emit(OpCodes.Call, objectCtor); - - var writeCount = info.Members.Count(x => x.IsReadable); - il.EmitLoadThis(); - il.EmitLdc_I4(writeCount); - il.Emit(OpCodes.Newarr, typeof(byte[])); - - var i = 0; - foreach (ObjectSerializationInfo.EmittableMember item in info.Members.Where(x => x.IsReadable)) - { - il.Emit(OpCodes.Dup); - il.EmitLdc_I4(i); - il.Emit(OpCodes.Ldstr, item.StringKey); - il.EmitCall(CodeGenHelpersTypeInfo.GetEncodedStringBytes); - il.Emit(OpCodes.Stelem_Ref); - i++; - } - - il.Emit(OpCodes.Stfld, stringByteKeysField); - } - - private static Dictionary BuildCustomFormatterField(TypeBuilder builder, ObjectSerializationInfo info, ILGenerator il) - { - Dictionary dict = new Dictionary(); - foreach (ObjectSerializationInfo.EmittableMember item in info.Members.Where(x => x.IsReadable || x.IsWritable)) - { - MessagePackFormatterAttribute attr = item.GetMessagePackFormatterAttribute(); - if (attr != null) - { - FieldBuilder f = builder.DefineField(item.Name + "_formatter", attr.FormatterType, FieldAttributes.Private | FieldAttributes.InitOnly); - - var bindingFlags = (int)(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - - LocalBuilder attrVar = il.DeclareLocal(typeof(MessagePackFormatterAttribute)); - - il.Emit(OpCodes.Ldtoken, info.Type); - il.EmitCall(EmitInfo.GetTypeFromHandle); - il.Emit(OpCodes.Ldstr, item.Name); - il.EmitLdc_I4(bindingFlags); - if (item.IsProperty) - { - il.EmitCall(EmitInfo.TypeGetProperty); - } - else - { - il.EmitCall(EmitInfo.TypeGetField); - } - - il.EmitTrue(); - il.EmitCall(EmitInfo.GetCustomAttributeMessagePackFormatterAttribute); - il.EmitStloc(attrVar); - - il.EmitLoadThis(); - - il.EmitLdloc(attrVar); - il.EmitCall(EmitInfo.MessagePackFormatterAttr.FormatterType); - il.EmitLdloc(attrVar); - il.EmitCall(EmitInfo.MessagePackFormatterAttr.Arguments); - il.EmitCall(EmitInfo.ActivatorCreateInstance); - - il.Emit(OpCodes.Castclass, attr.FormatterType); - il.Emit(OpCodes.Stfld, f); - - dict.Add(item, f); - } - } - - return dict; - } - - // void Serialize(ref [arg:1]MessagePackWriter writer, [arg:2]T value, [arg:3]MessagePackSerializerOptions options); - private static void BuildSerialize(Type type, ObjectSerializationInfo info, ILGenerator il, Action emitStringByteKeys, Func tryEmitLoadCustomFormatter, int firstArgIndex) - { - var argWriter = new ArgumentField(il, firstArgIndex); - var argValue = new ArgumentField(il, firstArgIndex + 1, type); - var argOptions = new ArgumentField(il, firstArgIndex + 2); - - // if(value == null) return WriteNil - if (type.GetTypeInfo().IsClass) - { - Label elseBody = il.DefineLabel(); - - argValue.EmitLoad(); - il.Emit(OpCodes.Brtrue_S, elseBody); - argWriter.EmitLoad(); - il.EmitCall(MessagePackWriterTypeInfo.WriteNil); - il.Emit(OpCodes.Ret); - - il.MarkLabel(elseBody); - } - - // IMessagePackSerializationCallbackReceiver.OnBeforeSerialize() - if (type.GetTypeInfo().ImplementedInterfaces.Any(x => x == typeof(IMessagePackSerializationCallbackReceiver))) - { - // call directly - MethodInfo[] runtimeMethods = type.GetRuntimeMethods().Where(x => x.Name == "OnBeforeSerialize").ToArray(); - if (runtimeMethods.Length == 1) - { - argValue.EmitLoad(); - il.Emit(OpCodes.Call, runtimeMethods[0]); // don't use EmitCall helper(must use 'Call') - } - else - { - argValue.EmitLdarg(); // force ldarg - il.EmitBoxOrDoNothing(type); - il.EmitCall(onBeforeSerialize); - } - } - - // IFormatterResolver resolver = options.Resolver; - LocalBuilder localResolver = il.DeclareLocal(typeof(IFormatterResolver)); - argOptions.EmitLoad(); - il.EmitCall(getResolverFromOptions); - il.EmitStloc(localResolver); - - if (info.IsIntKey) - { - // use Array - var maxKey = info.Members.Where(x => x.IsReadable).Select(x => x.IntKey).DefaultIfEmpty(-1).Max(); - var intKeyMap = info.Members.Where(x => x.IsReadable).ToDictionary(x => x.IntKey); - - var len = maxKey + 1; - argWriter.EmitLoad(); - il.EmitLdc_I4(len); - il.EmitCall(MessagePackWriterTypeInfo.WriteArrayHeader); - - var index = 0; - for (int i = 0; i <= maxKey; i++) - { - ObjectSerializationInfo.EmittableMember member; - if (intKeyMap.TryGetValue(i, out member)) - { - EmitSerializeValue(il, type.GetTypeInfo(), member, index++, tryEmitLoadCustomFormatter, argWriter, argValue, argOptions, localResolver); - } - else - { - // Write Nil as Blanc - argWriter.EmitLoad(); - il.EmitCall(MessagePackWriterTypeInfo.WriteNil); - } - } - } - else - { - // use Map - var writeCount = info.Members.Count(x => x.IsReadable); - - argWriter.EmitLoad(); - il.EmitLdc_I4(writeCount); - ////if (writeCount <= MessagePackRange.MaxFixMapCount) - ////{ - //// il.EmitCall(MessagePackWriterTypeInfo.WriteFixedMapHeaderUnsafe); - ////} - ////else - { - il.EmitCall(MessagePackWriterTypeInfo.WriteMapHeader); - } - - var index = 0; - foreach (ObjectSerializationInfo.EmittableMember item in info.Members.Where(x => x.IsReadable)) - { - argWriter.EmitLoad(); - emitStringByteKeys(); - il.EmitLdc_I4(index); - il.Emit(OpCodes.Ldelem_Ref); - il.Emit(OpCodes.Call, ReadOnlySpanFromByteArray); // convert byte[] to ReadOnlySpan - - // Optimize, WriteRaw(Unity, large) or UnsafeMemory32/64.WriteRawX -#if !UNITY_2018_3_OR_NEWER - var valueLen = CodeGenHelpers.GetEncodedStringBytes(item.StringKey).Length; - if (valueLen <= MessagePackRange.MaxFixStringLength) - { - if (UnsafeMemory.Is32Bit) - { - il.EmitCall(typeof(UnsafeMemory32).GetRuntimeMethod("WriteRaw" + valueLen, new[] { typeof(MessagePackWriter).MakeByRefType(), typeof(ReadOnlySpan) })); - } - else - { - il.EmitCall(typeof(UnsafeMemory64).GetRuntimeMethod("WriteRaw" + valueLen, new[] { typeof(MessagePackWriter).MakeByRefType(), typeof(ReadOnlySpan) })); - } - } - else -#endif - { - il.EmitCall(MessagePackWriterTypeInfo.WriteRaw); - } - - EmitSerializeValue(il, type.GetTypeInfo(), item, index, tryEmitLoadCustomFormatter, argWriter, argValue, argOptions, localResolver); - index++; - } - } - - il.Emit(OpCodes.Ret); - } - - private static void EmitSerializeValue(ILGenerator il, TypeInfo type, ObjectSerializationInfo.EmittableMember member, int index, Func tryEmitLoadCustomFormatter, ArgumentField argWriter, ArgumentField argValue, ArgumentField argOptions, LocalBuilder localResolver) - { - Label endLabel = il.DefineLabel(); - Type t = member.Type; - Action emitter = tryEmitLoadCustomFormatter(index, member); - if (emitter != null) - { - emitter(); - argWriter.EmitLoad(); - argValue.EmitLoad(); - member.EmitLoadValue(il); - argOptions.EmitLoad(); - il.EmitCall(getSerialize(t)); - } - else if (IsOptimizeTargetType(t)) - { - if (!t.GetTypeInfo().IsValueType) - { - // As a nullable type (e.g. byte[] and string) we need to call WriteNil for null values. - Label writeNonNilValueLabel = il.DefineLabel(); - LocalBuilder memberValue = il.DeclareLocal(t); - argValue.EmitLoad(); - member.EmitLoadValue(il); - il.Emit(OpCodes.Dup); - il.EmitStloc(memberValue); - il.Emit(OpCodes.Brtrue, writeNonNilValueLabel); - argWriter.EmitLoad(); - il.EmitCall(MessagePackWriterTypeInfo.WriteNil); - il.Emit(OpCodes.Br, endLabel); - - il.MarkLabel(writeNonNilValueLabel); - argWriter.EmitLoad(); - il.EmitLdloc(memberValue); - } - else - { - argWriter.EmitLoad(); - argValue.EmitLoad(); - member.EmitLoadValue(il); - } - - if (t == typeof(byte[])) - { - il.EmitCall(ReadOnlySpanFromByteArray); - il.EmitCall(MessagePackWriterTypeInfo.WriteBytes); - } - else - { - il.EmitCall(typeof(MessagePackWriter).GetRuntimeMethod("Write", new Type[] { t })); - } - } - else - { - il.EmitLdloc(localResolver); - il.Emit(OpCodes.Call, getFormatterWithVerify.MakeGenericMethod(t)); - - argWriter.EmitLoad(); - argValue.EmitLoad(); - member.EmitLoadValue(il); - argOptions.EmitLoad(); - il.EmitCall(getSerialize(t)); - } - - il.MarkLabel(endLabel); - } - - // T Deserialize([arg:1]ref MessagePackReader reader, [arg:2]MessagePackSerializerOptions options); - private static void BuildDeserialize(Type type, ObjectSerializationInfo info, ILGenerator il, Func tryEmitLoadCustomFormatter, int firstArgIndex) - { - var reader = new ArgumentField(il, firstArgIndex, @ref: true); - var argOptions = new ArgumentField(il, firstArgIndex + 1); - - // if(reader.TryReadNil()) { return null; } - Label falseLabel = il.DefineLabel(); - reader.EmitLdarg(); - il.EmitCall(MessagePackReaderTypeInfo.TryReadNil); - il.Emit(OpCodes.Brfalse_S, falseLabel); - if (type.GetTypeInfo().IsClass) - { - il.Emit(OpCodes.Ldnull); - il.Emit(OpCodes.Ret); - } - else - { - il.Emit(OpCodes.Ldstr, "typecode is null, struct not supported"); - il.Emit(OpCodes.Newobj, messagePackSerializationExceptionMessageOnlyConstructor); - il.Emit(OpCodes.Throw); - } - - il.MarkLabel(falseLabel); - - // options.Security.DepthStep(ref reader); - argOptions.EmitLoad(); - il.EmitCall(getSecurityFromOptions); - reader.EmitLdarg(); - il.EmitCall(securityDepthStep); - - // var length = ReadMapHeader(ref byteSequence); - LocalBuilder length = il.DeclareLocal(typeof(int)); // [loc:1] - reader.EmitLdarg(); - - if (info.IsIntKey) - { - il.EmitCall(MessagePackReaderTypeInfo.ReadArrayHeader); - } - else - { - il.EmitCall(MessagePackReaderTypeInfo.ReadMapHeader); - } - - il.EmitStloc(length); - - // make local fields - Label? gotoDefault = null; - DeserializeInfo[] infoList; - if (info.IsIntKey) - { - var maxKey = info.Members.Select(x => x.IntKey).DefaultIfEmpty(-1).Max(); - var len = maxKey + 1; - var intKeyMap = info.Members.ToDictionary(x => x.IntKey); - - infoList = Enumerable.Range(0, len) - .Select(x => - { - ObjectSerializationInfo.EmittableMember member; - if (intKeyMap.TryGetValue(x, out member)) - { - return new DeserializeInfo - { - MemberInfo = member, - LocalField = il.DeclareLocal(member.Type), - SwitchLabel = il.DefineLabel(), - }; - } - else - { - // return null MemberInfo, should filter null - if (gotoDefault == null) - { - gotoDefault = il.DefineLabel(); - } - - return new DeserializeInfo - { - MemberInfo = null, - LocalField = null, - SwitchLabel = gotoDefault.Value, - }; - } - }) - .ToArray(); - } - else - { - infoList = info.Members - .Select(item => new DeserializeInfo - { - MemberInfo = item, - LocalField = il.DeclareLocal(item.Type), - //// SwitchLabel = il.DefineLabel() - }) - .ToArray(); - } - - // IFormatterResolver resolver = options.Resolver; - LocalBuilder localResolver = il.DeclareLocal(typeof(IFormatterResolver)); - argOptions.EmitLoad(); - il.EmitCall(getResolverFromOptions); - il.EmitStloc(localResolver); - - // Read Loop(for var i = 0; i < length; i++) - if (info.IsStringKey) - { - var automata = new AutomataDictionary(); - for (int i = 0; i < info.Members.Length; i++) - { - automata.Add(info.Members[i].StringKey, i); - } - - LocalBuilder buffer = il.DeclareLocal(typeof(ReadOnlySpan)); - LocalBuilder longKey = il.DeclareLocal(typeof(ulong)); - - // for (int i = 0; i < len; i++) - il.EmitIncrementFor(length, forILocal => - { - Label readNext = il.DefineLabel(); - Label loopEnd = il.DefineLabel(); - - reader.EmitLdarg(); - il.EmitCall(ReadStringSpan); - il.EmitStloc(buffer); - - // gen automata name lookup - automata.EmitMatch( - il, - buffer, - longKey, - x => - { - var i = x.Value; - if (infoList[i].MemberInfo != null) - { - EmitDeserializeValue(il, infoList[i], i, tryEmitLoadCustomFormatter, reader, argOptions, localResolver); - il.Emit(OpCodes.Br, loopEnd); - } - else - { - il.Emit(OpCodes.Br, readNext); - } - }, - () => - { - il.Emit(OpCodes.Br, readNext); - }); - - il.MarkLabel(readNext); - reader.EmitLdarg(); - il.EmitCall(MessagePackReaderTypeInfo.Skip); - - il.MarkLabel(loopEnd); - }); - } - else - { - LocalBuilder key = il.DeclareLocal(typeof(int)); - Label switchDefault = il.DefineLabel(); - - il.EmitIncrementFor(length, forILocal => - { - Label loopEnd = il.DefineLabel(); - - il.EmitLdloc(forILocal); - il.EmitStloc(key); - - // switch... local = Deserialize - il.EmitLdloc(key); - - il.Emit(OpCodes.Switch, infoList.Select(x => x.SwitchLabel).ToArray()); - - il.MarkLabel(switchDefault); - - // default, only read. reader.ReadNextBlock(); - reader.EmitLdarg(); - il.EmitCall(MessagePackReaderTypeInfo.Skip); - il.Emit(OpCodes.Br, loopEnd); - - if (gotoDefault != null) - { - il.MarkLabel(gotoDefault.Value); - il.Emit(OpCodes.Br, switchDefault); - } - - var i = 0; - foreach (DeserializeInfo item in infoList) - { - if (item.MemberInfo != null) - { - il.MarkLabel(item.SwitchLabel); - EmitDeserializeValue(il, item, i++, tryEmitLoadCustomFormatter, reader, argOptions, localResolver); - il.Emit(OpCodes.Br, loopEnd); - } - } - - il.MarkLabel(loopEnd); - }); - } - - // create result object - LocalBuilder structLocal = EmitNewObject(il, type, info, infoList); - - // IMessagePackSerializationCallbackReceiver.OnAfterDeserialize() - if (type.GetTypeInfo().ImplementedInterfaces.Any(x => x == typeof(IMessagePackSerializationCallbackReceiver))) - { - // call directly - MethodInfo[] runtimeMethods = type.GetRuntimeMethods().Where(x => x.Name == "OnAfterDeserialize").ToArray(); - if (runtimeMethods.Length == 1) - { - if (info.IsClass) - { - il.Emit(OpCodes.Dup); - } - else - { - il.EmitLdloca(structLocal); - } - - il.Emit(OpCodes.Call, runtimeMethods[0]); // don't use EmitCall helper(must use 'Call') - } - else - { - if (info.IsStruct) - { - il.EmitLdloc(structLocal); - il.Emit(OpCodes.Box, type); - } - else - { - il.Emit(OpCodes.Dup); - } - - il.EmitCall(onAfterDeserialize); - } - } - - // reader.Depth--; - reader.EmitLdarg(); - il.Emit(OpCodes.Dup); - il.EmitCall(readerDepthGet); - il.Emit(OpCodes.Ldc_I4_1); - il.Emit(OpCodes.Sub_Ovf); - il.EmitCall(readerDepthSet); - - if (info.IsStruct) - { - il.Emit(OpCodes.Ldloc, structLocal); - } - - il.Emit(OpCodes.Ret); - } - - private static void EmitDeserializeValue(ILGenerator il, DeserializeInfo info, int index, Func tryEmitLoadCustomFormatter, ArgumentField argReader, ArgumentField argOptions, LocalBuilder localResolver) - { - Label storeLabel = il.DefineLabel(); - ObjectSerializationInfo.EmittableMember member = info.MemberInfo; - Type t = member.Type; - Action emitter = tryEmitLoadCustomFormatter(index, member); - if (emitter != null) - { - emitter(); - argReader.EmitLdarg(); - argOptions.EmitLoad(); - il.EmitCall(getDeserialize(t)); - } - else if (IsOptimizeTargetType(t)) - { - if (!t.GetTypeInfo().IsValueType) - { - // As a nullable type (e.g. byte[] and string) we need to first call TryReadNil - // if (reader.TryReadNil()) - Label readNonNilValueLabel = il.DefineLabel(); - argReader.EmitLdarg(); - il.EmitCall(MessagePackReaderTypeInfo.TryReadNil); - il.Emit(OpCodes.Brfalse_S, readNonNilValueLabel); - il.Emit(OpCodes.Ldnull); - il.Emit(OpCodes.Br, storeLabel); - - il.MarkLabel(readNonNilValueLabel); - } - - argReader.EmitLdarg(); - if (t == typeof(byte[])) - { - LocalBuilder local = il.DeclareLocal(typeof(ReadOnlySequence?)); - il.EmitCall(MessagePackReaderTypeInfo.ReadBytes); - il.EmitStloc(local); - il.EmitLdloca(local); - il.EmitCall(ArrayFromNullableReadOnlySequence); - } - else - { - il.EmitCall(MessagePackReaderTypeInfo.TypeInfo.GetDeclaredMethods("Read" + t.Name).First(x => x.GetParameters().Length == 0)); - } - } - else - { - il.EmitLdloc(localResolver); - il.EmitCall(getFormatterWithVerify.MakeGenericMethod(t)); - argReader.EmitLdarg(); - argOptions.EmitLoad(); - il.EmitCall(getDeserialize(t)); - } - - il.MarkLabel(storeLabel); - il.EmitStloc(info.LocalField); - } - - private static LocalBuilder EmitNewObject(ILGenerator il, Type type, ObjectSerializationInfo info, DeserializeInfo[] members) - { - if (info.IsClass) - { - foreach (ObjectSerializationInfo.EmittableMember item in info.ConstructorParameters) - { - DeserializeInfo local = members.First(x => x.MemberInfo == item); - il.EmitLdloc(local.LocalField); - } - - il.Emit(OpCodes.Newobj, info.BestmatchConstructor); - - foreach (DeserializeInfo item in members.Where(x => x.MemberInfo != null && x.MemberInfo.IsWritable)) - { - il.Emit(OpCodes.Dup); - il.EmitLdloc(item.LocalField); - item.MemberInfo.EmitStoreValue(il); - } - - return null; - } - else - { - LocalBuilder result = il.DeclareLocal(type); - if (info.BestmatchConstructor == null) - { - il.Emit(OpCodes.Ldloca, result); - il.Emit(OpCodes.Initobj, type); - } - else - { - foreach (ObjectSerializationInfo.EmittableMember item in info.ConstructorParameters) - { - DeserializeInfo local = members.First(x => x.MemberInfo == item); - il.EmitLdloc(local.LocalField); - } - - il.Emit(OpCodes.Newobj, info.BestmatchConstructor); - il.Emit(OpCodes.Stloc, result); - } - - foreach (DeserializeInfo item in members.Where(x => x.MemberInfo != null && x.MemberInfo.IsWritable)) - { - il.EmitLdloca(result); - il.EmitLdloc(item.LocalField); - item.MemberInfo.EmitStoreValue(il); - } - - return result; // struct returns local result field - } - } - - private static bool IsOptimizeTargetType(Type type) - { - return type == typeof(Int16) - || type == typeof(Int32) - || type == typeof(Int64) - || type == typeof(UInt16) - || type == typeof(UInt32) - || type == typeof(UInt64) - || type == typeof(Single) - || type == typeof(Double) - || type == typeof(bool) - || type == typeof(byte) - || type == typeof(sbyte) - || type == typeof(char) - || type == typeof(byte[]) - - // Do not include types that resolvers are allowed to modify. - ////|| type == typeof(DateTime) // OldSpec has no support, so for that and perf reasons a .NET native DateTime resolver exists. - ////|| type == typeof(string) // https://github.com/Cysharp/MasterMemory provides custom formatter for string interning. - ; - } - -#pragma warning disable SA1311 // Static readonly fields should begin with upper-case letter - - // EmitInfos... - private static readonly Type refMessagePackReader = typeof(MessagePackReader).MakeByRefType(); - - private static readonly MethodInfo ReadOnlySpanFromByteArray = typeof(ReadOnlySpan).GetRuntimeMethod("op_Implicit", new[] { typeof(byte[]) }); - private static readonly MethodInfo ReadStringSpan = typeof(CodeGenHelpers).GetRuntimeMethod(nameof(CodeGenHelpers.ReadStringSpan), new[] { typeof(MessagePackReader).MakeByRefType() }); - private static readonly MethodInfo ArrayFromNullableReadOnlySequence = typeof(CodeGenHelpers).GetRuntimeMethod(nameof(CodeGenHelpers.GetArrayFromNullableSequence), new[] { typeof(ReadOnlySequence?).MakeByRefType() }); - - private static readonly MethodInfo getFormatterWithVerify = typeof(FormatterResolverExtensions).GetRuntimeMethods().First(x => x.Name == nameof(FormatterResolverExtensions.GetFormatterWithVerify)); - private static readonly MethodInfo getResolverFromOptions = typeof(MessagePackSerializerOptions).GetRuntimeProperty(nameof(MessagePackSerializerOptions.Resolver)).GetMethod; - private static readonly MethodInfo getSecurityFromOptions = typeof(MessagePackSerializerOptions).GetRuntimeProperty(nameof(MessagePackSerializerOptions.Security)).GetMethod; - private static readonly MethodInfo securityDepthStep = typeof(MessagePackSecurity).GetRuntimeMethod(nameof(MessagePackSecurity.DepthStep), new[] { typeof(MessagePackReader).MakeByRefType() }); - private static readonly MethodInfo readerDepthGet = typeof(MessagePackReader).GetRuntimeProperty(nameof(MessagePackReader.Depth)).GetMethod; - private static readonly MethodInfo readerDepthSet = typeof(MessagePackReader).GetRuntimeProperty(nameof(MessagePackReader.Depth)).SetMethod; - private static readonly Func getSerialize = t => typeof(IMessagePackFormatter<>).MakeGenericType(t).GetRuntimeMethod(nameof(IMessagePackFormatter.Serialize), new[] { typeof(MessagePackWriter).MakeByRefType(), t, typeof(MessagePackSerializerOptions) }); - private static readonly Func getDeserialize = t => typeof(IMessagePackFormatter<>).MakeGenericType(t).GetRuntimeMethod(nameof(IMessagePackFormatter.Deserialize), new[] { refMessagePackReader, typeof(MessagePackSerializerOptions) }); - //// static readonly ConstructorInfo dictionaryConstructor = typeof(ByteArrayStringHashTable).GetTypeInfo().DeclaredConstructors.First(x => { var p = x.GetParameters(); return p.Length == 1 && p[0].ParameterType == typeof(int); }); - //// static readonly MethodInfo dictionaryAdd = typeof(ByteArrayStringHashTable).GetRuntimeMethod("Add", new[] { typeof(string), typeof(int) }); - //// static readonly MethodInfo dictionaryTryGetValue = typeof(ByteArrayStringHashTable).GetRuntimeMethod("TryGetValue", new[] { typeof(ArraySegment), refInt }); - private static readonly ConstructorInfo messagePackSerializationExceptionMessageOnlyConstructor = typeof(MessagePackSerializationException).GetTypeInfo().DeclaredConstructors.First(x => - { - ParameterInfo[] p = x.GetParameters(); - return p.Length == 1 && p[0].ParameterType == typeof(string); - }); - - private static readonly MethodInfo onBeforeSerialize = typeof(IMessagePackSerializationCallbackReceiver).GetRuntimeMethod(nameof(IMessagePackSerializationCallbackReceiver.OnBeforeSerialize), Type.EmptyTypes); - private static readonly MethodInfo onAfterDeserialize = typeof(IMessagePackSerializationCallbackReceiver).GetRuntimeMethod(nameof(IMessagePackSerializationCallbackReceiver.OnAfterDeserialize), Type.EmptyTypes); - - private static readonly ConstructorInfo objectCtor = typeof(object).GetTypeInfo().DeclaredConstructors.First(x => x.GetParameters().Length == 0); - -#pragma warning restore SA1311 // Static readonly fields should begin with upper-case letter - - /// - /// Helps match parameters when searching a method when the parameter is a generic type. - /// - private static bool Matches(MethodInfo m, int parameterIndex, Type desiredType) - { - ParameterInfo[] parameters = m.GetParameters(); - return parameters.Length > parameterIndex - ////&& parameters[0].ParameterType.IsGenericType // returns false for some bizarre reason - && parameters[parameterIndex].ParameterType.Name == desiredType.Name - && parameters[parameterIndex].ParameterType.Namespace == desiredType.Namespace; - } - - internal static class MessagePackWriterTypeInfo - { - internal static readonly TypeInfo TypeInfo = typeof(MessagePackWriter).GetTypeInfo(); - - internal static readonly MethodInfo WriteMapHeader = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.WriteMapHeader), new[] { typeof(int) }); - internal static readonly MethodInfo WriteArrayHeader = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.WriteArrayHeader), new[] { typeof(int) }); - internal static readonly MethodInfo WriteBytes = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.Write), new[] { typeof(ReadOnlySpan) }); - internal static readonly MethodInfo WriteNil = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.WriteNil), Type.EmptyTypes); - internal static readonly MethodInfo WriteRaw = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.WriteRaw), new[] { typeof(ReadOnlySpan) }); - } - - internal static class MessagePackReaderTypeInfo - { - internal static readonly TypeInfo TypeInfo = typeof(MessagePackReader).GetTypeInfo(); - - internal static readonly MethodInfo ReadArrayHeader = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadArrayHeader), Type.EmptyTypes); - internal static readonly MethodInfo ReadMapHeader = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadMapHeader), Type.EmptyTypes); - internal static readonly MethodInfo ReadBytes = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadBytes), Type.EmptyTypes); - internal static readonly MethodInfo TryReadNil = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.TryReadNil), Type.EmptyTypes); - internal static readonly MethodInfo Skip = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.Skip), Type.EmptyTypes); - } - - internal static class CodeGenHelpersTypeInfo - { - public static readonly MethodInfo GetEncodedStringBytes = typeof(CodeGenHelpers).GetRuntimeMethod(nameof(CodeGenHelpers.GetEncodedStringBytes), new[] { typeof(string) }); - } - - internal static class EmitInfo - { - public static readonly MethodInfo GetTypeFromHandle = ExpressionUtility.GetMethodInfo(() => Type.GetTypeFromHandle(default(RuntimeTypeHandle))); - public static readonly MethodInfo TypeGetProperty = ExpressionUtility.GetMethodInfo((Type t) => t.GetTypeInfo().GetProperty(default(string), default(BindingFlags))); - public static readonly MethodInfo TypeGetField = ExpressionUtility.GetMethodInfo((Type t) => t.GetTypeInfo().GetField(default(string), default(BindingFlags))); - public static readonly MethodInfo GetCustomAttributeMessagePackFormatterAttribute = ExpressionUtility.GetMethodInfo(() => CustomAttributeExtensions.GetCustomAttribute(default(MemberInfo), default(bool))); - public static readonly MethodInfo ActivatorCreateInstance = ExpressionUtility.GetMethodInfo(() => Activator.CreateInstance(default(Type), default(object[]))); - - internal static class MessagePackFormatterAttr - { - internal static readonly MethodInfo FormatterType = ExpressionUtility.GetPropertyInfo((MessagePackFormatterAttribute attr) => attr.FormatterType).GetGetMethod(); - internal static readonly MethodInfo Arguments = ExpressionUtility.GetPropertyInfo((MessagePackFormatterAttribute attr) => attr.Arguments).GetGetMethod(); - } - } - - private class DeserializeInfo - { - public ObjectSerializationInfo.EmittableMember MemberInfo { get; set; } - - public LocalBuilder LocalField { get; set; } - - public Label SwitchLabel { get; set; } - } - } - - internal delegate void AnonymousSerializeFunc(byte[][] stringByteKeysField, object[] customFormatters, ref MessagePackWriter writer, T value, MessagePackSerializerOptions options); - - internal delegate T AnonymousDeserializeFunc(object[] customFormatters, ref MessagePackReader reader, MessagePackSerializerOptions options); - - internal class AnonymousSerializableFormatter : IMessagePackFormatter - { - private readonly byte[][] stringByteKeysField; - private readonly object[] serializeCustomFormatters; - private readonly object[] deserializeCustomFormatters; - private readonly AnonymousSerializeFunc serialize; - private readonly AnonymousDeserializeFunc deserialize; - - public AnonymousSerializableFormatter(byte[][] stringByteKeysField, object[] serializeCustomFormatters, object[] deserializeCustomFormatters, AnonymousSerializeFunc serialize, AnonymousDeserializeFunc deserialize) - { - this.stringByteKeysField = stringByteKeysField; - this.serializeCustomFormatters = serializeCustomFormatters; - this.deserializeCustomFormatters = deserializeCustomFormatters; - this.serialize = serialize; - this.deserialize = deserialize; - } - - public void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options) - { - if (this.serialize == null) - { - throw new MessagePackSerializationException(this.GetType().Name + " does not support Serialize."); - } - - this.serialize(this.stringByteKeysField, this.serializeCustomFormatters, ref writer, value, options); - } - - public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (this.deserialize == null) - { - throw new MessagePackSerializationException(this.GetType().Name + " does not support Deserialize."); - } - - return this.deserialize(this.deserializeCustomFormatters, ref reader, options); - } - } - - internal class ObjectSerializationInfo - { - public Type Type { get; set; } - - public bool IsIntKey { get; set; } - - public bool IsStringKey - { - get { return !this.IsIntKey; } - } - - public bool IsClass { get; set; } - - public bool IsStruct - { - get { return !this.IsClass; } - } - - public ConstructorInfo BestmatchConstructor { get; set; } - - public EmittableMember[] ConstructorParameters { get; set; } - - public EmittableMember[] Members { get; set; } - - private ObjectSerializationInfo() - { - } - - public static ObjectSerializationInfo CreateOrNull(Type type, bool forceStringKey, bool contractless, bool allowPrivate) - { - TypeInfo ti = type.GetTypeInfo(); - var isClass = ti.IsClass || ti.IsInterface || ti.IsAbstract; - var isStruct = ti.IsValueType; - - MessagePackObjectAttribute contractAttr = ti.GetCustomAttributes().FirstOrDefault(); - DataContractAttribute dataContractAttr = ti.GetCustomAttribute(); - if (contractAttr == null && dataContractAttr == null && !forceStringKey && !contractless) - { - return null; - } - - var isIntKey = true; - var intMembers = new Dictionary(); - var stringMembers = new Dictionary(); - - if (forceStringKey || contractless || (contractAttr != null && contractAttr.KeyAsPropertyName)) - { - // All public members are serialize target except [Ignore] member. - isIntKey = !(forceStringKey || (contractAttr != null && contractAttr.KeyAsPropertyName)); - - var hiddenIntKey = 0; - - // Group the properties and fields by name to qualify members of the same name - // (declared with the 'new' keyword) with the declaring type. - IEnumerable> membersByName = type.GetRuntimeProperties() - .Concat(type.GetRuntimeFields().Cast()) - .OrderBy(m => m.DeclaringType, OrderBaseTypesBeforeDerivedTypes.Instance) - .GroupBy(m => m.Name); - foreach (var memberGroup in membersByName) - { - bool firstMemberByName = true; - foreach (MemberInfo item in memberGroup) - { - if (item.GetCustomAttribute(true) != null) - { - continue; - } - - if (item.GetCustomAttribute(true) != null) - { - continue; - } - - EmittableMember member; - if (item is PropertyInfo property) - { - if (property.IsIndexer()) - { - continue; - } - - MethodInfo getMethod = property.GetGetMethod(true); - MethodInfo setMethod = property.GetSetMethod(true); - - member = new EmittableMember - { - PropertyInfo = property, - IsReadable = (getMethod != null) && (allowPrivate || getMethod.IsPublic) && !getMethod.IsStatic, - IsWritable = (setMethod != null) && (allowPrivate || setMethod.IsPublic) && !setMethod.IsStatic, - StringKey = firstMemberByName ? item.Name : $"{item.DeclaringType.FullName}.{item.Name}", - }; - } - else if (item is FieldInfo field) - { - if (item.GetCustomAttribute(true) != null) - { - continue; - } - - if (field.IsStatic) - { - continue; - } - - member = new EmittableMember - { - FieldInfo = field, - IsReadable = allowPrivate || field.IsPublic, - IsWritable = allowPrivate || (field.IsPublic && !field.IsInitOnly), - StringKey = firstMemberByName ? item.Name : $"{item.DeclaringType.FullName}.{item.Name}", - }; - } - else - { - throw new MessagePackSerializationException("unexpected member type"); - } - - if (!member.IsReadable && !member.IsWritable) - { - continue; - } - - member.IntKey = hiddenIntKey++; - if (isIntKey) - { - intMembers.Add(member.IntKey, member); - } - else - { - stringMembers.Add(member.StringKey, member); - } - - firstMemberByName = false; - } - } - } - else - { - // Public members with KeyAttribute except [Ignore] member. - var searchFirst = true; - var hiddenIntKey = 0; - - foreach (PropertyInfo item in type.GetRuntimeProperties()) - { - if (item.GetCustomAttribute(true) != null) - { - continue; - } - - if (item.GetCustomAttribute(true) != null) - { - continue; - } - - if (item.IsIndexer()) - { - continue; - } - - MethodInfo getMethod = item.GetGetMethod(true); - MethodInfo setMethod = item.GetSetMethod(true); - - var member = new EmittableMember - { - PropertyInfo = item, - IsReadable = (getMethod != null) && (allowPrivate || getMethod.IsPublic) && !getMethod.IsStatic, - IsWritable = (setMethod != null) && (allowPrivate || setMethod.IsPublic) && !setMethod.IsStatic, - }; - if (!member.IsReadable && !member.IsWritable) - { - continue; - } - - KeyAttribute key; - if (contractAttr != null) - { - // MessagePackObjectAttribute - key = item.GetCustomAttribute(true); - if (key == null) - { - throw new MessagePackDynamicObjectResolverException("all public members must mark KeyAttribute or IgnoreMemberAttribute." + " type: " + type.FullName + " member:" + item.Name); - } - - member.IsExplicitContract = true; - if (key.IntKey == null && key.StringKey == null) - { - throw new MessagePackDynamicObjectResolverException("both IntKey and StringKey are null." + " type: " + type.FullName + " member:" + item.Name); - } - } - else - { - // DataContractAttribute - DataMemberAttribute pseudokey = item.GetCustomAttribute(true); - if (pseudokey == null) - { - // This member has no DataMemberAttribute nor IgnoreMemberAttribute. - // But the type *did* have a DataContractAttribute on it, so no attribute implies the member should not be serialized. - continue; - } - - member.IsExplicitContract = true; - - // use Order first - if (pseudokey.Order != -1) - { - key = new KeyAttribute(pseudokey.Order); - } - else if (pseudokey.Name != null) - { - key = new KeyAttribute(pseudokey.Name); - } - else - { - key = new KeyAttribute(item.Name); // use property name - } - } - - if (searchFirst) - { - searchFirst = false; - isIntKey = key.IntKey != null; - } - else - { - if ((isIntKey && key.IntKey == null) || (!isIntKey && key.StringKey == null)) - { - throw new MessagePackDynamicObjectResolverException("all members key type must be same." + " type: " + type.FullName + " member:" + item.Name); - } - } - - if (isIntKey) - { - member.IntKey = key.IntKey.Value; - if (intMembers.ContainsKey(member.IntKey)) - { - throw new MessagePackDynamicObjectResolverException("key is duplicated, all members key must be unique." + " type: " + type.FullName + " member:" + item.Name); - } - - intMembers.Add(member.IntKey, member); - } - else - { - member.StringKey = key.StringKey; - if (stringMembers.ContainsKey(member.StringKey)) - { - throw new MessagePackDynamicObjectResolverException("key is duplicated, all members key must be unique." + " type: " + type.FullName + " member:" + item.Name); - } - - member.IntKey = hiddenIntKey++; - stringMembers.Add(member.StringKey, member); - } - } - - foreach (FieldInfo item in type.GetRuntimeFields()) - { - if (item.GetCustomAttribute(true) != null) - { - continue; - } - - if (item.GetCustomAttribute(true) != null) - { - continue; - } - - if (item.GetCustomAttribute(true) != null) - { - continue; - } - - if (item.IsStatic) - { - continue; - } - - var member = new EmittableMember - { - FieldInfo = item, - IsReadable = allowPrivate || item.IsPublic, - IsWritable = allowPrivate || (item.IsPublic && !item.IsInitOnly), - }; - if (!member.IsReadable && !member.IsWritable) - { - continue; - } - - KeyAttribute key; - if (contractAttr != null) - { - // MessagePackObjectAttribute - key = item.GetCustomAttribute(true); - if (key == null) - { - throw new MessagePackDynamicObjectResolverException("all public members must mark KeyAttribute or IgnoreMemberAttribute." + " type: " + type.FullName + " member:" + item.Name); - } - - member.IsExplicitContract = true; - if (key.IntKey == null && key.StringKey == null) - { - throw new MessagePackDynamicObjectResolverException("both IntKey and StringKey are null." + " type: " + type.FullName + " member:" + item.Name); - } - } - else - { - // DataContractAttribute - DataMemberAttribute pseudokey = item.GetCustomAttribute(true); - if (pseudokey == null) - { - // This member has no DataMemberAttribute nor IgnoreMemberAttribute. - // But the type *did* have a DataContractAttribute on it, so no attribute implies the member should not be serialized. - continue; - } - - member.IsExplicitContract = true; - - // use Order first - if (pseudokey.Order != -1) - { - key = new KeyAttribute(pseudokey.Order); - } - else if (pseudokey.Name != null) - { - key = new KeyAttribute(pseudokey.Name); - } - else - { - key = new KeyAttribute(item.Name); // use property name - } - } - - if (searchFirst) - { - searchFirst = false; - isIntKey = key.IntKey != null; - } - else - { - if ((isIntKey && key.IntKey == null) || (!isIntKey && key.StringKey == null)) - { - throw new MessagePackDynamicObjectResolverException("all members key type must be same." + " type: " + type.FullName + " member:" + item.Name); - } - } - - if (isIntKey) - { - member.IntKey = key.IntKey.Value; - if (intMembers.ContainsKey(member.IntKey)) - { - throw new MessagePackDynamicObjectResolverException("key is duplicated, all members key must be unique." + " type: " + type.FullName + " member:" + item.Name); - } - - intMembers.Add(member.IntKey, member); - } - else - { - member.StringKey = key.StringKey; - if (stringMembers.ContainsKey(member.StringKey)) - { - throw new MessagePackDynamicObjectResolverException("key is duplicated, all members key must be unique." + " type: " + type.FullName + " member:" + item.Name); - } - - member.IntKey = hiddenIntKey++; - stringMembers.Add(member.StringKey, member); - } - } - } - - // GetConstructor - IEnumerator ctorEnumerator = null; - ConstructorInfo ctor = ti.DeclaredConstructors.SingleOrDefault(x => x.GetCustomAttribute(false) != null); - if (ctor == null) - { - ctorEnumerator = - ti.DeclaredConstructors.Where(x => x.IsPublic).OrderByDescending(x => x.GetParameters().Length) - .GetEnumerator(); - - if (ctorEnumerator.MoveNext()) - { - ctor = ctorEnumerator.Current; - } - } - - // struct allows null ctor - if (ctor == null && !isStruct) - { - throw new MessagePackDynamicObjectResolverException("can't find public constructor. type:" + type.FullName); - } - - var constructorParameters = new List(); - if (ctor != null) - { - ILookup> constructorLookupDictionary = stringMembers.ToLookup(x => x.Key, x => x, StringComparer.OrdinalIgnoreCase); - do - { - constructorParameters.Clear(); - var ctorParamIndex = 0; - foreach (ParameterInfo item in ctor.GetParameters()) - { - EmittableMember paramMember; - if (isIntKey) - { - if (intMembers.TryGetValue(ctorParamIndex, out paramMember)) - { - if ((item.ParameterType == paramMember.Type || - item.ParameterType.GetTypeInfo().IsAssignableFrom(paramMember.Type)) - && paramMember.IsReadable) - { - constructorParameters.Add(paramMember); - } - else - { - if (ctorEnumerator != null) - { - ctor = null; - continue; - } - else - { - throw new MessagePackDynamicObjectResolverException("can't find matched constructor parameter, parameterType mismatch. type:" + type.FullName + " parameterIndex:" + ctorParamIndex + " paramterType:" + item.ParameterType.Name); - } - } - } - else - { - if (ctorEnumerator != null) - { - ctor = null; - continue; - } - else - { - throw new MessagePackDynamicObjectResolverException("can't find matched constructor parameter, index not found. type:" + type.FullName + " parameterIndex:" + ctorParamIndex); - } - } - } - else - { - IEnumerable> hasKey = constructorLookupDictionary[item.Name]; - var len = hasKey.Count(); - if (len != 0) - { - if (len != 1) - { - if (ctorEnumerator != null) - { - ctor = null; - continue; - } - else - { - throw new MessagePackDynamicObjectResolverException("duplicate matched constructor parameter name:" + type.FullName + " parameterName:" + item.Name + " paramterType:" + item.ParameterType.Name); - } - } - - paramMember = hasKey.First().Value; - if (item.ParameterType == paramMember.Type && paramMember.IsReadable) - { - constructorParameters.Add(paramMember); - } - else - { - if (ctorEnumerator != null) - { - ctor = null; - continue; - } - else - { - throw new MessagePackDynamicObjectResolverException("can't find matched constructor parameter, parameterType mismatch. type:" + type.FullName + " parameterName:" + item.Name + " paramterType:" + item.ParameterType.Name); - } - } - } - else - { - if (ctorEnumerator != null) - { - ctor = null; - continue; - } - else - { - throw new MessagePackDynamicObjectResolverException("can't find matched constructor parameter, index not found. type:" + type.FullName + " parameterName:" + item.Name); - } - } - } - - ctorParamIndex++; - } - } - while (TryGetNextConstructor(ctorEnumerator, ref ctor)); - - if (ctor == null) - { - throw new MessagePackDynamicObjectResolverException("can't find matched constructor. type:" + type.FullName); - } - } - - EmittableMember[] members; - if (isIntKey) - { - members = intMembers.Values.OrderBy(x => x.IntKey).ToArray(); - } - else - { - members = stringMembers.Values - .OrderBy(x => - { - DataMemberAttribute attr = x.GetDataMemberAttribute(); - if (attr == null) - { - return int.MaxValue; - } - - return attr.Order; - }) - .ToArray(); - } - - return new ObjectSerializationInfo - { - Type = type, - IsClass = isClass, - BestmatchConstructor = ctor, - ConstructorParameters = constructorParameters.ToArray(), - IsIntKey = isIntKey, - Members = members.Where(m => m.IsExplicitContract || constructorParameters.Contains(m) || m.IsWritable).ToArray(), - }; - } - - private static bool TryGetNextConstructor(IEnumerator ctorEnumerator, ref ConstructorInfo ctor) - { - if (ctorEnumerator == null || ctor != null) - { - return false; - } - - if (ctorEnumerator.MoveNext()) - { - ctor = ctorEnumerator.Current; - return true; - } - else - { - ctor = null; - return false; - } - } - - public class EmittableMember - { - public bool IsProperty - { - get { return this.PropertyInfo != null; } - } - - public bool IsField - { - get { return this.FieldInfo != null; } - } - - public bool IsWritable { get; set; } - - public bool IsReadable { get; set; } - - public int IntKey { get; set; } - - public string StringKey { get; set; } - - public Type Type - { - get { return this.IsField ? this.FieldInfo.FieldType : this.PropertyInfo.PropertyType; } - } - - public FieldInfo FieldInfo { get; set; } - - public PropertyInfo PropertyInfo { get; set; } - - public string Name - { - get - { - return this.IsProperty ? this.PropertyInfo.Name : this.FieldInfo.Name; - } - } - - public bool IsValueType - { - get - { - MemberInfo mi = this.IsProperty ? (MemberInfo)this.PropertyInfo : this.FieldInfo; - return mi.DeclaringType.GetTypeInfo().IsValueType; - } - } - - /// - /// Gets or sets a value indicating whether this member is explicitly opted in with an attribute. - /// - public bool IsExplicitContract { get; set; } - - public MessagePackFormatterAttribute GetMessagePackFormatterAttribute() - { - if (this.IsProperty) - { - return (MessagePackFormatterAttribute)this.PropertyInfo.GetCustomAttribute(true); - } - else - { - return (MessagePackFormatterAttribute)this.FieldInfo.GetCustomAttribute(true); - } - } - - public DataMemberAttribute GetDataMemberAttribute() - { - if (this.IsProperty) - { - return (DataMemberAttribute)this.PropertyInfo.GetCustomAttribute(true); - } - else - { - return (DataMemberAttribute)this.FieldInfo.GetCustomAttribute(true); - } - } - - public void EmitLoadValue(ILGenerator il) - { - if (this.IsProperty) - { - il.EmitCall(this.PropertyInfo.GetGetMethod(true)); - } - else - { - il.Emit(OpCodes.Ldfld, this.FieldInfo); - } - } - - public void EmitStoreValue(ILGenerator il) - { - if (this.IsProperty) - { - il.EmitCall(this.PropertyInfo.GetSetMethod(true)); - } - else - { - il.Emit(OpCodes.Stfld, this.FieldInfo); - } - } - - ////public object ReflectionLoadValue(object value) - ////{ - //// if (IsProperty) - //// { - //// return PropertyInfo.GetValue(value, null); - //// } - //// else - //// { - //// return FieldInfo.GetValue(value); - //// } - ////} - - ////public void ReflectionStoreValue(object obj, object value) - ////{ - //// if (IsProperty) - //// { - //// PropertyInfo.SetValue(obj, value, null); - //// } - //// else - //// { - //// FieldInfo.SetValue(obj, value); - //// } - ////} - } - - private class OrderBaseTypesBeforeDerivedTypes : IComparer - { - internal static readonly OrderBaseTypesBeforeDerivedTypes Instance = new OrderBaseTypesBeforeDerivedTypes(); - - private OrderBaseTypesBeforeDerivedTypes() - { - } - - public int Compare(Type x, Type y) - { - return - x.IsEquivalentTo(y) ? 0 : - x.IsAssignableFrom(y) ? -1 : - y.IsAssignableFrom(x) ? 1 : - 0; - } - } - } - - internal class MessagePackDynamicObjectResolverException : MessagePackSerializationException - { - public MessagePackDynamicObjectResolverException(string message) - : base(message) - { - } - } -} - -#endif diff --git a/Assets/Plugins/MessagePack/Resolvers/DynamicObjectResolver.cs.meta b/Assets/Plugins/MessagePack/Resolvers/DynamicObjectResolver.cs.meta deleted file mode 100644 index b5c92ca2d..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/DynamicObjectResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 14db1290355a2f56a919749640cbcc7c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Resolvers/DynamicUnionResolver.cs b/Assets/Plugins/MessagePack/Resolvers/DynamicUnionResolver.cs deleted file mode 100644 index f5d33966e..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/DynamicUnionResolver.cs +++ /dev/null @@ -1,517 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if !(UNITY_2018_3_OR_NEWER && NET_STANDARD_2_0) - -using System; -using System.Buffers; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Reflection.Emit; -using System.Text.RegularExpressions; -using System.Threading; -using MessagePack.Formatters; -using MessagePack.Internal; - -#pragma warning disable SA1403 // File may only contain a single namespace -#pragma warning disable SA1509 // Opening braces should not be preceded by blank line - -namespace MessagePack.Resolvers -{ - /// - /// UnionResolver by dynamic code generation. - /// - public sealed class DynamicUnionResolver : IFormatterResolver - { - private const string ModuleName = "MessagePack.Resolvers.DynamicUnionResolver"; - - /// - /// The singleton instance that can be used. - /// - public static readonly DynamicUnionResolver Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - private static readonly DynamicAssembly DynamicAssembly; -#if !UNITY_2018_3_OR_NEWER - private static readonly Regex SubtractFullNameRegex = new Regex(@", Version=\d+.\d+.\d+.\d+, Culture=\w+, PublicKeyToken=\w+", RegexOptions.Compiled); -#else - private static readonly Regex SubtractFullNameRegex = new Regex(@", Version=\d+.\d+.\d+.\d+, Culture=\w+, PublicKeyToken=\w+"); -#endif - - private static int nameSequence = 0; - - static DynamicUnionResolver() - { - Instance = new DynamicUnionResolver(); - Options = new MessagePackSerializerOptions(Instance); - DynamicAssembly = new DynamicAssembly(ModuleName); - } - - private DynamicUnionResolver() - { - } - -#if NETFRAMEWORK - public AssemblyBuilder Save() - { - return DynamicAssembly.Save(); - } -#endif - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - TypeInfo ti = typeof(T).GetTypeInfo(); - if (ti.IsNullable()) - { - ti = ti.GenericTypeArguments[0].GetTypeInfo(); - - var innerFormatter = DynamicUnionResolver.Instance.GetFormatterDynamic(ti.AsType()); - if (innerFormatter == null) - { - return; - } - - Formatter = (IMessagePackFormatter)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); - return; - } - - TypeInfo formatterTypeInfo = BuildType(typeof(T)); - if (formatterTypeInfo == null) - { - return; - } - - Formatter = (IMessagePackFormatter)Activator.CreateInstance(formatterTypeInfo.AsType()); - } - } - - private static TypeInfo BuildType(Type type) - { - TypeInfo ti = type.GetTypeInfo(); - - // order by key(important for use jump-table of switch) - UnionAttribute[] unionAttrs = ti.GetCustomAttributes().OrderBy(x => x.Key).ToArray(); - - if (unionAttrs.Length == 0) - { - return null; - } - - if (!ti.IsInterface && !ti.IsAbstract) - { - throw new MessagePackDynamicUnionResolverException("Union can only be interface or abstract class. Type:" + type.Name); - } - - var checker1 = new HashSet(); - var checker2 = new HashSet(); - foreach (UnionAttribute item in unionAttrs) - { - if (!checker1.Add(item.Key)) - { - throw new MessagePackDynamicUnionResolverException("Same union key has found. Type:" + type.Name + " Key:" + item.Key); - } - - if (!checker2.Add(item.SubType)) - { - throw new MessagePackDynamicUnionResolverException("Same union subType has found. Type:" + type.Name + " SubType: " + item.SubType); - } - } - - Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(type); - TypeBuilder typeBuilder = DynamicAssembly.DefineType("MessagePack.Formatters." + SubtractFullNameRegex.Replace(type.FullName, string.Empty).Replace(".", "_") + "Formatter" + +Interlocked.Increment(ref nameSequence), TypeAttributes.Public | TypeAttributes.Sealed, null, new[] { formatterType }); - - FieldBuilder typeToKeyAndJumpMap = null; // Dictionary> - FieldBuilder keyToJumpMap = null; // Dictionary - - // create map dictionary - { - ConstructorBuilder method = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes); - typeToKeyAndJumpMap = typeBuilder.DefineField("typeToKeyAndJumpMap", typeof(Dictionary>), FieldAttributes.Private | FieldAttributes.InitOnly); - keyToJumpMap = typeBuilder.DefineField("keyToJumpMap", typeof(Dictionary), FieldAttributes.Private | FieldAttributes.InitOnly); - - ILGenerator il = method.GetILGenerator(); - BuildConstructor(type, unionAttrs, method, typeToKeyAndJumpMap, keyToJumpMap, il); - } - - { - MethodBuilder method = typeBuilder.DefineMethod( - "Serialize", - MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot, - null, - new Type[] { typeof(MessagePackWriter).MakeByRefType(), type, typeof(MessagePackSerializerOptions) }); - - ILGenerator il = method.GetILGenerator(); - BuildSerialize(type, unionAttrs, method, typeToKeyAndJumpMap, il); - } - - { - MethodBuilder method = typeBuilder.DefineMethod( - "Deserialize", - MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot, - type, - new Type[] { refMessagePackReader, typeof(MessagePackSerializerOptions) }); - - ILGenerator il = method.GetILGenerator(); - BuildDeserialize(type, unionAttrs, method, keyToJumpMap, il); - } - - return typeBuilder.CreateTypeInfo(); - } - - private static void BuildConstructor(Type type, UnionAttribute[] infos, ConstructorInfo method, FieldBuilder typeToKeyAndJumpMap, FieldBuilder keyToJumpMap, ILGenerator il) - { - il.EmitLdarg(0); - il.Emit(OpCodes.Call, objectCtor); - - { - il.EmitLdarg(0); - il.EmitLdc_I4(infos.Length); - il.Emit(OpCodes.Ldsfld, runtimeTypeHandleEqualityComparer); - il.Emit(OpCodes.Newobj, typeMapDictionaryConstructor); - - var index = 0; - foreach (UnionAttribute item in infos) - { - il.Emit(OpCodes.Dup); - il.Emit(OpCodes.Ldtoken, item.SubType); - il.EmitLdc_I4(item.Key); - il.EmitLdc_I4(index); - il.Emit(OpCodes.Newobj, intIntKeyValuePairConstructor); - il.EmitCall(typeMapDictionaryAdd); - - index++; - } - - il.Emit(OpCodes.Stfld, typeToKeyAndJumpMap); - } - - { - il.EmitLdarg(0); - il.EmitLdc_I4(infos.Length); - il.Emit(OpCodes.Newobj, keyMapDictionaryConstructor); - - var index = 0; - foreach (UnionAttribute item in infos) - { - il.Emit(OpCodes.Dup); - il.EmitLdc_I4(item.Key); - il.EmitLdc_I4(index); - il.EmitCall(keyMapDictionaryAdd); - - index++; - } - - il.Emit(OpCodes.Stfld, keyToJumpMap); - } - - il.Emit(OpCodes.Ret); - } - - // void Serialize([arg:1]MessagePackWriter writer, [arg:2]T value, [arg:3]MessagePackSerializerOptions options); - private static void BuildSerialize(Type type, UnionAttribute[] infos, MethodBuilder method, FieldBuilder typeToKeyAndJumpMap, ILGenerator il) - { - // if(value == null) return WriteNil - Label elseBody = il.DefineLabel(); - Label notFoundType = il.DefineLabel(); - - il.EmitLdarg(2); - il.Emit(OpCodes.Brtrue_S, elseBody); - il.Emit(OpCodes.Br, notFoundType); - il.MarkLabel(elseBody); - - // IFormatterResolver resolver = options.Resolver; - LocalBuilder localResolver = il.DeclareLocal(typeof(IFormatterResolver)); - il.EmitLdarg(3); - il.EmitCall(getResolverFromOptions); - il.EmitStloc(localResolver); - - LocalBuilder keyPair = il.DeclareLocal(typeof(KeyValuePair)); - - il.EmitLoadThis(); - il.EmitLdfld(typeToKeyAndJumpMap); - il.EmitLdarg(2); - il.EmitCall(objectGetType); - il.EmitCall(getTypeHandle); - il.EmitLdloca(keyPair); - il.EmitCall(typeMapDictionaryTryGetValue); - il.Emit(OpCodes.Brfalse, notFoundType); - - // writer.WriteArrayHeader(2, false); - il.EmitLdarg(1); - il.EmitLdc_I4(2); - il.EmitCall(MessagePackWriterTypeInfo.WriteArrayHeader); - - // writer.Write(keyPair.Key) - il.EmitLdarg(1); - il.EmitLdloca(keyPair); - il.EmitCall(intIntKeyValuePairGetKey); - il.EmitCall(MessagePackWriterTypeInfo.WriteInt32); - - Label loopEnd = il.DefineLabel(); - - // switch-case (offset += resolver.GetFormatter.Serialize(with cast) - var switchLabels = infos.Select(x => new { Label = il.DefineLabel(), Attr = x }).ToArray(); - il.EmitLdloca(keyPair); - il.EmitCall(intIntKeyValuePairGetValue); - il.Emit(OpCodes.Switch, switchLabels.Select(x => x.Label).ToArray()); - il.Emit(OpCodes.Br, loopEnd); // default - - foreach (var item in switchLabels) - { - il.MarkLabel(item.Label); - il.EmitLdloc(localResolver); - il.Emit(OpCodes.Call, getFormatterWithVerify.MakeGenericMethod(item.Attr.SubType)); - - il.EmitLdarg(1); - il.EmitLdarg(2); - if (item.Attr.SubType.GetTypeInfo().IsValueType) - { - il.Emit(OpCodes.Unbox_Any, item.Attr.SubType); - } - else - { - il.Emit(OpCodes.Castclass, item.Attr.SubType); - } - - il.EmitLdarg(3); - il.Emit(OpCodes.Callvirt, getSerialize(item.Attr.SubType)); - - il.Emit(OpCodes.Br, loopEnd); - } - - // return; - il.MarkLabel(loopEnd); - il.Emit(OpCodes.Ret); - - // else, return WriteNil - il.MarkLabel(notFoundType); - il.EmitLdarg(1); - il.EmitCall(MessagePackWriterTypeInfo.WriteNil); - il.Emit(OpCodes.Ret); - } - - // T Deserialize([arg:1]ref MessagePackReader reader, [arg:2]MessagePackSerializerOptions options); - private static void BuildDeserialize(Type type, UnionAttribute[] infos, MethodBuilder method, FieldBuilder keyToJumpMap, ILGenerator il) - { - // if(MessagePackBinary.TryReadNil()) { return null; } - Label falseLabel = il.DefineLabel(); - il.EmitLdarg(1); - il.EmitCall(MessagePackReaderTypeInfo.TryReadNil); - il.Emit(OpCodes.Brfalse_S, falseLabel); - - il.Emit(OpCodes.Ldnull); - il.Emit(OpCodes.Ret); - - il.MarkLabel(falseLabel); - - // IFormatterResolver resolver = options.Resolver; - LocalBuilder localResolver = il.DeclareLocal(typeof(IFormatterResolver)); - il.EmitLdarg(2); - il.EmitCall(getResolverFromOptions); - il.EmitStloc(localResolver); - - // read-array header and validate, reader.ReadArrayHeader() != 2) throw; - Label rightLabel = il.DefineLabel(); - var writer = new ArgumentField(il, 1); - writer.EmitLdarg(); - il.EmitCall(MessagePackReaderTypeInfo.ReadArrayHeader); - il.EmitLdc_I4(2); - il.Emit(OpCodes.Beq_S, rightLabel); - il.Emit(OpCodes.Ldstr, "Invalid Union data was detected. Type:" + type.FullName); - il.Emit(OpCodes.Newobj, invalidOperationExceptionConstructor); - il.Emit(OpCodes.Throw); - - il.MarkLabel(rightLabel); - - // read key - LocalBuilder key = il.DeclareLocal(typeof(int)); - writer.EmitLdarg(); - il.EmitCall(MessagePackReaderTypeInfo.ReadInt32); - il.EmitStloc(key); - - // is-sequential don't need else convert key to jump-table value - if (!IsZeroStartSequential(infos)) - { - Label endKeyMapGet = il.DefineLabel(); - il.EmitLdarg(0); - il.EmitLdfld(keyToJumpMap); - il.EmitLdloc(key); - il.EmitLdloca(key); - il.EmitCall(keyMapDictionaryTryGetValue); - il.Emit(OpCodes.Brtrue_S, endKeyMapGet); - il.EmitLdc_I4(-1); - il.EmitStloc(key); - - il.MarkLabel(endKeyMapGet); - } - - // switch->read - LocalBuilder result = il.DeclareLocal(type); - Label loopEnd = il.DefineLabel(); - il.Emit(OpCodes.Ldnull); - il.EmitStloc(result); - il.Emit(OpCodes.Ldloc, key); - - var switchLabels = infos.Select(x => new { Label = il.DefineLabel(), Attr = x }).ToArray(); - il.Emit(OpCodes.Switch, switchLabels.Select(x => x.Label).ToArray()); - - // default - writer.EmitLdarg(); - il.EmitCall(MessagePackReaderTypeInfo.Skip); - il.Emit(OpCodes.Br, loopEnd); - - foreach (var item in switchLabels) - { - il.MarkLabel(item.Label); - il.EmitLdloc(localResolver); - il.EmitCall(getFormatterWithVerify.MakeGenericMethod(item.Attr.SubType)); - il.EmitLdarg(1); - il.EmitLdarg(2); - il.EmitCall(getDeserialize(item.Attr.SubType)); - if (item.Attr.SubType.GetTypeInfo().IsValueType) - { - il.Emit(OpCodes.Box, item.Attr.SubType); - } - - il.Emit(OpCodes.Stloc, result); - il.Emit(OpCodes.Br, loopEnd); - } - - il.MarkLabel(loopEnd); - - il.Emit(OpCodes.Ldloc, result); - il.Emit(OpCodes.Ret); - } - - private static bool IsZeroStartSequential(UnionAttribute[] infos) - { - for (int i = 0; i < infos.Length; i++) - { - if (infos[i].Key != i) - { - return false; - } - } - - return true; - } - -#pragma warning disable SA1311 // Static readonly fields should begin with upper-case letter - - // EmitInfos... - private static readonly Type refMessagePackReader = typeof(MessagePackReader).MakeByRefType(); - private static readonly Type refKvp = typeof(KeyValuePair).MakeByRefType(); - private static readonly MethodInfo getFormatterWithVerify = typeof(FormatterResolverExtensions).GetRuntimeMethods().First(x => x.Name == "GetFormatterWithVerify"); - private static readonly MethodInfo getResolverFromOptions = typeof(MessagePackSerializerOptions).GetRuntimeProperty(nameof(MessagePackSerializerOptions.Resolver)).GetMethod; - - private static readonly Func getSerialize = t => typeof(IMessagePackFormatter<>).MakeGenericType(t).GetRuntimeMethod("Serialize", new[] { typeof(MessagePackWriter).MakeByRefType(), t, typeof(MessagePackSerializerOptions) }); - private static readonly Func getDeserialize = t => typeof(IMessagePackFormatter<>).MakeGenericType(t).GetRuntimeMethod("Deserialize", new[] { typeof(MessagePackReader).MakeByRefType(), typeof(MessagePackSerializerOptions) }); - - private static readonly FieldInfo runtimeTypeHandleEqualityComparer = typeof(RuntimeTypeHandleEqualityComparer).GetRuntimeField("Default"); - private static readonly ConstructorInfo intIntKeyValuePairConstructor = typeof(KeyValuePair).GetTypeInfo().DeclaredConstructors.First(x => x.GetParameters().Length == 2); - private static readonly ConstructorInfo typeMapDictionaryConstructor = typeof(Dictionary>).GetTypeInfo().DeclaredConstructors.First(x => - { - ParameterInfo[] p = x.GetParameters(); - return p.Length == 2 && p[0].ParameterType == typeof(int); - }); - - private static readonly MethodInfo typeMapDictionaryAdd = typeof(Dictionary>).GetRuntimeMethod("Add", new[] { typeof(RuntimeTypeHandle), typeof(KeyValuePair) }); - private static readonly MethodInfo typeMapDictionaryTryGetValue = typeof(Dictionary>).GetRuntimeMethod("TryGetValue", new[] { typeof(RuntimeTypeHandle), refKvp }); - - private static readonly ConstructorInfo keyMapDictionaryConstructor = typeof(Dictionary).GetTypeInfo().DeclaredConstructors.First(x => - { - ParameterInfo[] p = x.GetParameters(); - return p.Length == 1 && p[0].ParameterType == typeof(int); - }); - - private static readonly MethodInfo keyMapDictionaryAdd = typeof(Dictionary).GetRuntimeMethod("Add", new[] { typeof(int), typeof(int) }); - private static readonly MethodInfo keyMapDictionaryTryGetValue = typeof(Dictionary).GetRuntimeMethod("TryGetValue", new[] { typeof(int), typeof(int).MakeByRefType() }); - - private static readonly MethodInfo objectGetType = typeof(object).GetRuntimeMethod("GetType", Type.EmptyTypes); - private static readonly MethodInfo getTypeHandle = typeof(Type).GetRuntimeProperty("TypeHandle").GetGetMethod(); - - private static readonly MethodInfo intIntKeyValuePairGetKey = typeof(KeyValuePair).GetRuntimeProperty("Key").GetGetMethod(); - private static readonly MethodInfo intIntKeyValuePairGetValue = typeof(KeyValuePair).GetRuntimeProperty("Value").GetGetMethod(); - - private static readonly ConstructorInfo invalidOperationExceptionConstructor = typeof(System.InvalidOperationException).GetTypeInfo().DeclaredConstructors.First( - x => - { - ParameterInfo[] p = x.GetParameters(); - return p.Length == 1 && p[0].ParameterType == typeof(string); - }); - - private static readonly ConstructorInfo objectCtor = typeof(object).GetTypeInfo().DeclaredConstructors.First(x => x.GetParameters().Length == 0); - -#pragma warning restore SA1311 // Static readonly fields should begin with upper-case letter - - private static class MessagePackReaderTypeInfo - { - internal static readonly TypeInfo ReaderTypeInfo = typeof(MessagePackReader).GetTypeInfo(); - - internal static readonly MethodInfo ReadBytes = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadBytes), Type.EmptyTypes); - internal static readonly MethodInfo ReadInt32 = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadInt32), Type.EmptyTypes); - internal static readonly MethodInfo ReadString = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadString), Type.EmptyTypes); - internal static readonly MethodInfo TryReadNil = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.TryReadNil), Type.EmptyTypes); - internal static readonly MethodInfo Skip = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.Skip), Type.EmptyTypes); - internal static readonly MethodInfo ReadArrayHeader = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadArrayHeader), Type.EmptyTypes); - internal static readonly MethodInfo ReadMapHeader = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadMapHeader), Type.EmptyTypes); - } - - private static class MessagePackWriterTypeInfo - { - internal static readonly TypeInfo WriterTypeInfo = typeof(MessagePackWriter).GetTypeInfo(); - - internal static readonly MethodInfo WriteArrayHeader = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.WriteArrayHeader), new[] { typeof(int) }); - internal static readonly MethodInfo WriteInt32 = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.Write), new[] { typeof(int) }); - internal static readonly MethodInfo WriteNil = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.WriteNil), Type.EmptyTypes); - } - } -} - -namespace MessagePack.Internal -{ - // RuntimeTypeHandle can embed directly by OpCodes.Ldtoken - // It does not implements IEquatable(but GetHashCode and Equals is implemented) so needs this to avoid boxing. - public class RuntimeTypeHandleEqualityComparer : IEqualityComparer - { - public static readonly IEqualityComparer Default = new RuntimeTypeHandleEqualityComparer(); - - private RuntimeTypeHandleEqualityComparer() - { - } - - public bool Equals(RuntimeTypeHandle x, RuntimeTypeHandle y) - { - return x.Equals(y); - } - - public int GetHashCode(RuntimeTypeHandle obj) - { - return obj.GetHashCode(); - } - } - - internal class MessagePackDynamicUnionResolverException : MessagePackSerializationException - { - public MessagePackDynamicUnionResolverException(string message) - : base(message) - { - } - } -} - -#endif diff --git a/Assets/Plugins/MessagePack/Resolvers/DynamicUnionResolver.cs.meta b/Assets/Plugins/MessagePack/Resolvers/DynamicUnionResolver.cs.meta deleted file mode 100644 index 17bfde860..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/DynamicUnionResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 90ad303c7072b2339bba5b667f71b34c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Resolvers/NativeDateTimeResolver.cs b/Assets/Plugins/MessagePack/Resolvers/NativeDateTimeResolver.cs deleted file mode 100644 index 4e236314e..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/NativeDateTimeResolver.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using MessagePack.Formatters; -using MessagePack.Internal; - -#pragma warning disable SA1403 // File may only contain a single namespace - -namespace MessagePack.Resolvers -{ - public sealed class NativeDateTimeResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly NativeDateTimeResolver Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - static NativeDateTimeResolver() - { - Instance = new NativeDateTimeResolver(); - Options = new MessagePackSerializerOptions(Instance); - } - - private NativeDateTimeResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - Formatter = (IMessagePackFormatter)NativeDateTimeResolverGetFormatterHelper.GetFormatter(typeof(T)); - } - } - } -} - -namespace MessagePack.Internal -{ - internal static class NativeDateTimeResolverGetFormatterHelper - { - internal static object GetFormatter(Type t) - { - if (t == typeof(DateTime)) - { - return NativeDateTimeFormatter.Instance; - } - else if (t == typeof(DateTime?)) - { - return new StaticNullableFormatter(NativeDateTimeFormatter.Instance); - } - else if (t == typeof(DateTime[])) - { - return NativeDateTimeArrayFormatter.Instance; - } - - return null; - } - } -} diff --git a/Assets/Plugins/MessagePack/Resolvers/NativeDateTimeResolver.cs.meta b/Assets/Plugins/MessagePack/Resolvers/NativeDateTimeResolver.cs.meta deleted file mode 100644 index 74ee705c9..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/NativeDateTimeResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bee453915d14c4376a4cf68b338f7f4a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Resolvers/NativeDecimalResolver.cs b/Assets/Plugins/MessagePack/Resolvers/NativeDecimalResolver.cs deleted file mode 100644 index 725fba1f1..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/NativeDecimalResolver.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using MessagePack.Formatters; - -namespace MessagePack.Resolvers -{ - public sealed class NativeDecimalResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly NativeDecimalResolver Instance = new NativeDecimalResolver(); - - private NativeDecimalResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static object GetFormatterHelper(Type t) - { - if (t == typeof(Decimal)) - { - return NativeDecimalFormatter.Instance; - } - else if (t == typeof(Decimal?)) - { - return new StaticNullableFormatter(NativeDecimalFormatter.Instance); - } - - return null; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - Formatter = (IMessagePackFormatter)GetFormatterHelper(typeof(T)); - } - } - } -} diff --git a/Assets/Plugins/MessagePack/Resolvers/NativeDecimalResolver.cs.meta b/Assets/Plugins/MessagePack/Resolvers/NativeDecimalResolver.cs.meta deleted file mode 100644 index 204a97639..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/NativeDecimalResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 058b6071c8115560499afd0cc97e2fbd -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Resolvers/NativeGuidResolver.cs b/Assets/Plugins/MessagePack/Resolvers/NativeGuidResolver.cs deleted file mode 100644 index 34081b1f8..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/NativeGuidResolver.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using MessagePack.Formatters; - -namespace MessagePack.Resolvers -{ - public sealed class NativeGuidResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly NativeGuidResolver Instance = new NativeGuidResolver(); - - private NativeGuidResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static object GetFormatterHelper(Type t) - { - if (t == typeof(Guid)) - { - return NativeGuidFormatter.Instance; - } - else if (t == typeof(Guid?)) - { - return new StaticNullableFormatter(NativeGuidFormatter.Instance); - } - - return null; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - Formatter = (IMessagePackFormatter)GetFormatterHelper(typeof(T)); - } - } - } -} diff --git a/Assets/Plugins/MessagePack/Resolvers/NativeGuidResolver.cs.meta b/Assets/Plugins/MessagePack/Resolvers/NativeGuidResolver.cs.meta deleted file mode 100644 index f790df07f..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/NativeGuidResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a800419f557b36754a52fca66a1ed462 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Resolvers/PrimitiveObjectResolver.cs b/Assets/Plugins/MessagePack/Resolvers/PrimitiveObjectResolver.cs deleted file mode 100644 index 5c2859996..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/PrimitiveObjectResolver.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using MessagePack.Formatters; - -namespace MessagePack.Resolvers -{ - public sealed class PrimitiveObjectResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly PrimitiveObjectResolver Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - static PrimitiveObjectResolver() - { - Instance = new PrimitiveObjectResolver(); - Options = new MessagePackSerializerOptions(Instance); - } - - private PrimitiveObjectResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - Formatter = (typeof(T) == typeof(object)) - ? (IMessagePackFormatter)(object)PrimitiveObjectFormatter.Instance - : null; - } - } - } - - ////#if !UNITY_2018_3_OR_NEWER - - //// /// - //// /// In `object`, when serializing resolve by concrete type and when deserializing use primitive. - //// /// - //// public sealed class DynamicObjectTypeFallbackResolver : IFormatterResolver - //// { - //// public static readonly DynamicObjectTypeFallbackResolver Instance = new DynamicObjectTypeFallbackResolver(); - - //// DynamicObjectTypeFallbackResolver() - //// { - - //// } - - //// public IMessagePackFormatter GetFormatter() - //// { - //// return FormatterCache.formatter; - //// } - - //// static class FormatterCache - //// { - //// public static readonly IMessagePackFormatter formatter; - - //// static FormatterCache() - //// { - //// formatter = (typeof(T) == typeof(object)) - //// ? (IMessagePackFormatter)(object)DynamicObjectTypeFallbackFormatter.Instance - //// : null; - //// } - //// } - //// } - - ////#endif -} diff --git a/Assets/Plugins/MessagePack/Resolvers/PrimitiveObjectResolver.cs.meta b/Assets/Plugins/MessagePack/Resolvers/PrimitiveObjectResolver.cs.meta deleted file mode 100644 index 4b805b067..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/PrimitiveObjectResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 5b5a40f7f1c67953c8b8066277e196f6 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Resolvers/StandardResolver.cs b/Assets/Plugins/MessagePack/Resolvers/StandardResolver.cs deleted file mode 100644 index e67cefef6..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/StandardResolver.cs +++ /dev/null @@ -1,305 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Linq; -using MessagePack.Formatters; -using MessagePack.Internal; -using MessagePack.Resolvers; - -#pragma warning disable SA1403 // File may only contain a single namespace - -namespace MessagePack.Resolvers -{ - /// - /// Default composited resolver, builtin -> attribute -> dynamic enum -> dynamic generic -> dynamic union -> dynamic object -> primitive. - /// - public sealed class StandardResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly StandardResolver Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - private static readonly IFormatterResolver[] Resolvers = StandardResolverHelper.DefaultResolvers.Concat(new IFormatterResolver[] - { -#if !ENABLE_IL2CPP && !NET_STANDARD_2_0 - DynamicObjectResolver.Instance, // Try Object -#endif - }).ToArray(); - - static StandardResolver() - { - Instance = new StandardResolver(); - Options = new MessagePackSerializerOptions(Instance); - } - - private StandardResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - if (typeof(T) == typeof(object)) - { - // final fallback -#if !ENABLE_IL2CPP - Formatter = (IMessagePackFormatter)DynamicObjectTypeFallbackFormatter.Instance; -#else - Formatter = PrimitiveObjectResolver.Instance.GetFormatter(); -#endif - } - else - { - foreach (IFormatterResolver item in Resolvers) - { - IMessagePackFormatter f = item.GetFormatter(); - if (f != null) - { - Formatter = f; - return; - } - } - } - } - } - } - - public sealed class ContractlessStandardResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly ContractlessStandardResolver Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - private static readonly IFormatterResolver[] Resolvers = StandardResolverHelper.DefaultResolvers.Concat(new IFormatterResolver[] - { -#if !ENABLE_IL2CPP && !NET_STANDARD_2_0 - DynamicObjectResolver.Instance, // Try Object - DynamicContractlessObjectResolver.Instance, // Serializes keys as strings -#endif - }).ToArray(); - - static ContractlessStandardResolver() - { - Instance = new ContractlessStandardResolver(); - Options = new MessagePackSerializerOptions(Instance); - } - - private ContractlessStandardResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - if (typeof(T) == typeof(object)) - { - // final fallback -#if !ENABLE_IL2CPP - Formatter = (IMessagePackFormatter)DynamicObjectTypeFallbackFormatter.Instance; -#else - Formatter = PrimitiveObjectResolver.Instance.GetFormatter(); -#endif - } - else - { - foreach (IFormatterResolver item in Resolvers) - { - IMessagePackFormatter f = item.GetFormatter(); - if (f != null) - { - Formatter = f; - return; - } - } - } - } - } - } - - public sealed class StandardResolverAllowPrivate : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly StandardResolverAllowPrivate Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - private static readonly IFormatterResolver[] Resolvers = StandardResolverHelper.DefaultResolvers.Concat(new IFormatterResolver[] - { -#if !ENABLE_IL2CPP && !NET_STANDARD_2_0 - DynamicObjectResolverAllowPrivate.Instance, // Try Object -#endif - }).ToArray(); - - static StandardResolverAllowPrivate() - { - Instance = new StandardResolverAllowPrivate(); - Options = new MessagePackSerializerOptions(Instance); - } - - private StandardResolverAllowPrivate() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - if (typeof(T) == typeof(object)) - { - // final fallback -#if !ENABLE_IL2CPP - Formatter = (IMessagePackFormatter)DynamicObjectTypeFallbackFormatter.Instance; -#else - Formatter = PrimitiveObjectResolver.Instance.GetFormatter(); -#endif - } - else - { - foreach (IFormatterResolver item in Resolvers) - { - IMessagePackFormatter f = item.GetFormatter(); - if (f != null) - { - Formatter = f; - return; - } - } - } - } - } - } - - public sealed class ContractlessStandardResolverAllowPrivate : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly ContractlessStandardResolverAllowPrivate Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - private static readonly IFormatterResolver[] Resolvers = StandardResolverHelper.DefaultResolvers.Concat(new IFormatterResolver[] - { -#if !ENABLE_IL2CPP && !NET_STANDARD_2_0 - DynamicObjectResolverAllowPrivate.Instance, // Try Object - DynamicContractlessObjectResolverAllowPrivate.Instance, // Serializes keys as strings -#endif - }).ToArray(); - - static ContractlessStandardResolverAllowPrivate() - { - Instance = new ContractlessStandardResolverAllowPrivate(); - Options = new MessagePackSerializerOptions(Instance); - } - - private ContractlessStandardResolverAllowPrivate() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - if (typeof(T) == typeof(object)) - { - // final fallback -#if !ENABLE_IL2CPP - Formatter = (IMessagePackFormatter)DynamicObjectTypeFallbackFormatter.Instance; -#else - Formatter = PrimitiveObjectResolver.Instance.GetFormatter(); -#endif - } - else - { - foreach (IFormatterResolver item in Resolvers) - { - IMessagePackFormatter f = item.GetFormatter(); - if (f != null) - { - Formatter = f; - return; - } - } - } - } - } - } -} - -namespace MessagePack.Internal -{ - internal static class StandardResolverHelper - { - public static readonly IFormatterResolver[] DefaultResolvers = new IFormatterResolver[] - { - BuiltinResolver.Instance, // Try Builtin - AttributeFormatterResolver.Instance, // Try use [MessagePackFormatter] - -#if UNITY_2018_3_OR_NEWER - MessagePack.Unity.UnityResolver.Instance, -#endif - -#if !ENABLE_IL2CPP && !NET_STANDARD_2_0 - DynamicEnumResolver.Instance, // Try Enum -#endif - -#if !ENABLE_IL2CPP - DynamicGenericResolver.Instance, // Try Array, Tuple, Collection, Enum(Generic Fallback) -#endif - -#if !ENABLE_IL2CPP && !NET_STANDARD_2_0 - DynamicUnionResolver.Instance, // Try Union(Interface) -#endif - }; - } -} diff --git a/Assets/Plugins/MessagePack/Resolvers/StandardResolver.cs.meta b/Assets/Plugins/MessagePack/Resolvers/StandardResolver.cs.meta deleted file mode 100644 index a2d232750..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/StandardResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2273a153a02536bb1809f799fbfb2ceb -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Resolvers/StaticCompositeResolver.cs b/Assets/Plugins/MessagePack/Resolvers/StaticCompositeResolver.cs deleted file mode 100644 index ba0084c59..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/StaticCompositeResolver.cs +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using MessagePack.Formatters; - -namespace MessagePack.Resolvers -{ - /// - /// Singleton version of CompositeResolver, which be able to register a collection of formatters and resolvers to a single instance. - /// - public class StaticCompositeResolver : IFormatterResolver - { - public static readonly StaticCompositeResolver Instance = new StaticCompositeResolver(); - - private bool freezed; - private IReadOnlyList formatters; - private IReadOnlyList resolvers; - - private StaticCompositeResolver() - { - formatters = Array.Empty(); - resolvers = Array.Empty(); - } - - /// - /// Initializes a singleton instance with the specified formatters. - /// This method can only call before use StaticCompositeResolver.Instance.GetFormatter. - /// If call twice in the Register methods, registered formatters and resolvers will be overridden. - /// - /// - /// A list of instances of . - /// The formatters are searched in the order given, so if two formatters support serializing the same type, the first one is used. - /// - public void Register(params IMessagePackFormatter[] formatters) - { - if (this.freezed) - { - throw new InvalidOperationException("Register must call on startup(before use GetFormatter)."); - } - - if (this.formatters is null) - { - throw new ArgumentNullException(nameof(formatters)); - } - - this.formatters = formatters; - this.resolvers = Array.Empty(); - } - - /// - /// Initializes a singleton instance with the specified formatters and sub-resolvers. - /// This method can only call before use StaticCompositeResolver.Instance.GetFormatter. - /// If call twice in the Register methods, registered formatters and resolvers will be overridden. - /// - /// - /// A list of resolvers to use for serializing types. - /// The resolvers are searched in the order given, so if two resolvers support serializing the same type, the first one is used. - /// - public void Register(params IFormatterResolver[] resolvers) - { - if (this.freezed) - { - throw new InvalidOperationException("Register must call on startup(before use GetFormatter)."); - } - - if (resolvers is null) - { - throw new ArgumentNullException(nameof(resolvers)); - } - - this.formatters = Array.Empty(); - this.resolvers = resolvers; - } - - /// - /// Initializes a singleton instance with the specified formatters and sub-resolvers. - /// This method can only call before use StaticCompositeResolver.Instance.GetFormatter. - /// If call twice in the Register methods, registered formatters and resolvers will be overridden. - /// - /// - /// A list of instances of . - /// The formatters are searched in the order given, so if two formatters support serializing the same type, the first one is used. - /// - /// - /// A list of resolvers to use for serializing types for which does not include a formatter. - /// The resolvers are searched in the order given, so if two resolvers support serializing the same type, the first one is used. - /// - public void Register(IReadOnlyList formatters, IReadOnlyList resolvers) - { - if (this.freezed) - { - throw new InvalidOperationException("Register must call on startup(before use GetFormatter)."); - } - - if (formatters is null) - { - throw new ArgumentNullException(nameof(formatters)); - } - - if (resolvers is null) - { - throw new ArgumentNullException(nameof(resolvers)); - } - - this.formatters = formatters; - this.resolvers = resolvers; - } - - /// - /// Gets an instance that can serialize or deserialize some type . - /// - /// The type of value to be serialized or deserialized. - /// A formatter, if this resolver supplies one for type ; otherwise null. - public IMessagePackFormatter GetFormatter() - { - return Cache.Formatter; - } - - private static class Cache - { - public static readonly IMessagePackFormatter Formatter; - - static Cache() - { - Instance.freezed = true; - foreach (var item in Instance.formatters) - { - if (item is IMessagePackFormatter f) - { - Formatter = f; - return; - } - } - - foreach (var item in Instance.resolvers) - { - var f = item.GetFormatter(); - if (f != null) - { - Formatter = f; - return; - } - } - } - } - } -} diff --git a/Assets/Plugins/MessagePack/Resolvers/StaticCompositeResolver.cs.meta b/Assets/Plugins/MessagePack/Resolvers/StaticCompositeResolver.cs.meta deleted file mode 100644 index 62d918ea8..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/StaticCompositeResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 26c258a5a36d7dbf99caf4e98a7cbd53 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Resolvers/TypelessContractlessStandardResolver.cs b/Assets/Plugins/MessagePack/Resolvers/TypelessContractlessStandardResolver.cs deleted file mode 100644 index 0c8167bab..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/TypelessContractlessStandardResolver.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using MessagePack.Formatters; -using MessagePack.Internal; - -namespace MessagePack.Resolvers -{ - /// - /// Embeds the full name of .NET types for typed fields/collection items - /// Preserves .NET timezone. - /// - public sealed class TypelessContractlessStandardResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly TypelessContractlessStandardResolver Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - /// - /// A *private* list of resolvers. If we ever want to expose any of these (so the user can adjust settings, etc.) - /// then we must make this an instance collection instead of a static collection so that each consumer can have their own settings. - /// - private static readonly IReadOnlyList Resolvers = new IFormatterResolver[] - { - NativeDateTimeResolver.Instance, // Native c# DateTime format, preserving timezone - ForceSizePrimitiveObjectResolver.Instance, // Preserve particular integer types - BuiltinResolver.Instance, // Try Builtin - AttributeFormatterResolver.Instance, // Try use [MessagePackFormatter] -#if !ENABLE_IL2CPP - DynamicEnumResolver.Instance, // Try Enum - DynamicGenericResolver.Instance, // Try Array, Tuple, Collection - DynamicUnionResolver.Instance, // Try Union(Interface) - DynamicObjectResolver.Instance, // Try Object -#endif - DynamicContractlessObjectResolverAllowPrivate.Instance, // Serializes keys as strings - TypelessObjectResolver.Instance, - }; - - static TypelessContractlessStandardResolver() - { - Instance = new TypelessContractlessStandardResolver(); - Options = new MessagePackSerializerOptions(Instance); - } - - private readonly ResolverCache resolverCache = new ResolverCache(Resolvers); - - public IMessagePackFormatter GetFormatter() => this.resolverCache.GetFormatter(); - - private class ResolverCache : CachingFormatterResolver - { - private readonly IReadOnlyList resolvers; - - internal ResolverCache(IReadOnlyList resolvers) - { - this.resolvers = resolvers ?? throw new ArgumentNullException(nameof(resolvers)); - } - - protected override IMessagePackFormatter GetFormatterCore() - { - foreach (IFormatterResolver item in this.resolvers) - { - IMessagePackFormatter f = item.GetFormatter(); - if (f != null) - { - return f; - } - } - - return null; - } - } - } -} diff --git a/Assets/Plugins/MessagePack/Resolvers/TypelessContractlessStandardResolver.cs.meta b/Assets/Plugins/MessagePack/Resolvers/TypelessContractlessStandardResolver.cs.meta deleted file mode 100644 index 5b44fb822..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/TypelessContractlessStandardResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d4b1e4648b37d6308ac35a0e31148ab0 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Resolvers/TypelessObjectResolver.cs b/Assets/Plugins/MessagePack/Resolvers/TypelessObjectResolver.cs deleted file mode 100644 index 1be055857..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/TypelessObjectResolver.cs +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using MessagePack.Formatters; -using MessagePack.Internal; - -namespace MessagePack.Resolvers -{ - - /// - /// Used for `object` fields/collections, ex: var arr = new object[] { 1, "a", new Model() }; - /// The runtime type of value in object field, should be covered by one of resolvers in complex/standard resolver. - /// should be placed before DynamicObjectTypeFallbackResolver and in resolvers list. - /// Deserializer uses Namespace.TypeName, AssemblyName to get runtime type in destination app, so that combination must be present in destination app. - /// Serialized binary is valid MessagePack binary used ext-format and custom typecode(100). - /// Inside ext - assembly qualified type name, and serialized object. - /// - public sealed class TypelessObjectResolver : IFormatterResolver - { - public static readonly IFormatterResolver Instance = new TypelessObjectResolver(); - - private static readonly IFormatterResolver[] Resolvers = new IFormatterResolver[] - { - ForceSizePrimitiveObjectResolver.Instance, - ContractlessStandardResolverAllowPrivate.Instance, - }; - - private TypelessObjectResolver() - { - } - - /// - public IMessagePackFormatter GetFormatter() - { - if (typeof(T) == typeof(object)) - { - return (IMessagePackFormatter)TypelessFormatter.Instance; - } - else - { - foreach (IFormatterResolver item in Resolvers) - { - IMessagePackFormatter f = item.GetFormatter(); - if (f != null) - { - return f; - } - } - - return null; - } - } - } - - /* helpers for TypelessFormatter */ - - internal sealed class ForceSizePrimitiveObjectResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly ForceSizePrimitiveObjectResolver Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - static ForceSizePrimitiveObjectResolver() - { - Instance = new ForceSizePrimitiveObjectResolver(); - Options = new MessagePackSerializerOptions(Instance); - } - - private ForceSizePrimitiveObjectResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - Formatter = (IMessagePackFormatter)Helper.GetFormatter(typeof(T)); - } - } - - private static class Helper - { - private static readonly Dictionary FormatterMap = new Dictionary() - { - // Primitive - { typeof(Int16), ForceInt16BlockFormatter.Instance }, - { typeof(Int32), ForceInt32BlockFormatter.Instance }, - { typeof(Int64), ForceInt64BlockFormatter.Instance }, - { typeof(UInt16), ForceUInt16BlockFormatter.Instance }, - { typeof(UInt32), ForceUInt32BlockFormatter.Instance }, - { typeof(UInt64), ForceUInt64BlockFormatter.Instance }, - { typeof(byte), ForceByteBlockFormatter.Instance }, - { typeof(sbyte), ForceSByteBlockFormatter.Instance }, - - // Nullable Primitive - { typeof(Int16?), NullableForceInt16BlockFormatter.Instance }, - { typeof(Int32?), NullableForceInt32BlockFormatter.Instance }, - { typeof(Int64?), NullableForceInt64BlockFormatter.Instance }, - { typeof(UInt16?), NullableForceUInt16BlockFormatter.Instance }, - { typeof(UInt32?), NullableForceUInt32BlockFormatter.Instance }, - { typeof(UInt64?), NullableForceUInt64BlockFormatter.Instance }, - { typeof(byte?), NullableForceByteBlockFormatter.Instance }, - { typeof(sbyte?), NullableForceSByteBlockFormatter.Instance }, - - // optimized primitive array formatter - { typeof(Int16[]), ForceInt16BlockArrayFormatter.Instance }, - { typeof(Int32[]), ForceInt32BlockArrayFormatter.Instance }, - { typeof(Int64[]), ForceInt64BlockArrayFormatter.Instance }, - { typeof(UInt16[]), ForceUInt16BlockArrayFormatter.Instance }, - { typeof(UInt32[]), ForceUInt32BlockArrayFormatter.Instance }, - { typeof(UInt64[]), ForceUInt64BlockArrayFormatter.Instance }, - { typeof(SByte[]), ForceSByteBlockArrayFormatter.Instance }, - }; - - public static object GetFormatter(Type type) - { - object formatter; - return FormatterMap.TryGetValue(type, out formatter) - ? formatter - : null; - } - } - } - -} diff --git a/Assets/Plugins/MessagePack/Resolvers/TypelessObjectResolver.cs.meta b/Assets/Plugins/MessagePack/Resolvers/TypelessObjectResolver.cs.meta deleted file mode 100644 index 870673c62..000000000 --- a/Assets/Plugins/MessagePack/Resolvers/TypelessObjectResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 857aa0d32f3e2955491df1c9d5bb6f5d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/SequencePool.cs b/Assets/Plugins/MessagePack/SequencePool.cs deleted file mode 100644 index 7c95391a3..000000000 --- a/Assets/Plugins/MessagePack/SequencePool.cs +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections.Generic; -using Nerdbank.Streams; - -namespace MessagePack -{ - /// - /// A thread-safe, alloc-free reusable object pool. - /// - internal class SequencePool - { - /// - /// A thread-safe pool of reusable objects. - /// - /// - /// We use a that allows every processor to be involved in messagepack serialization concurrently, - /// plus one nested serialization per processor (since LZ4 and sometimes other nested serializations may exist). - /// - internal static readonly SequencePool Shared = new SequencePool(Environment.ProcessorCount * 2); - - /// - /// The value to use for . - /// - /// - /// Individual users that want a different value for this can modify the setting on the rented - /// or by supplying their own . - /// - /// - /// We use 32KB so that when LZ4Codec.MaximumOutputLength is used on this length it does not require a - /// buffer that would require the Large Object Heap. - /// - private const int MinimumSpanLength = 32 * 1024; - - private readonly int maxSize; - private readonly Stack> pool = new Stack>(); - - /// - /// The array pool which we share with all objects created by this instance. - /// - /// - /// We allow 100 arrays to be shared (instead of the default 50) and reduce the max array length from the default 1MB to something more reasonable for our expected use. - /// - private readonly ArrayPool arrayPool = ArrayPool.Create(80 * 1024, 100); - - /// - /// Initializes a new instance of the class. - /// - /// The maximum size to allow the pool to grow. - internal SequencePool(int maxSize) - { - this.maxSize = maxSize; - } - - /// - /// Gets an instance of - /// This is taken from the recycled pool if one is available; otherwise a new one is created. - /// - /// The rental tracker that provides access to the object as well as a means to return it. - internal Rental Rent() - { - lock (this.pool) - { - if (this.pool.Count > 0) - { - return new Rental(this, this.pool.Pop()); - } - } - - // Configure the newly created object to share a common array pool with the other instances, - // otherwise each one will have its own ArrayPool which would likely waste a lot of memory. - return new Rental(this, new Sequence(this.arrayPool) { MinimumSpanLength = MinimumSpanLength }); - } - - private void Return(Sequence value) - { - value.Reset(); - lock (this.pool) - { - if (this.pool.Count < this.maxSize) - { - // Reset to preferred settings in case the renter changed them. - value.MinimumSpanLength = MinimumSpanLength; - - this.pool.Push(value); - } - } - } - - internal struct Rental : IDisposable - { - private readonly SequencePool owner; - - internal Rental(SequencePool owner, Sequence value) - { - this.owner = owner; - this.Value = value; - } - - /// - /// Gets the recyclable object. - /// - public Sequence Value { get; } - - /// - /// Returns the recyclable object to the pool. - /// - /// - /// The instance is cleaned first, if a clean delegate was provided. - /// It is dropped instead of being returned to the pool if the pool is already at its maximum size. - /// - public void Dispose() - { - this.owner.Return(this.Value); - } - } - } -} diff --git a/Assets/Plugins/MessagePack/SequencePool.cs.meta b/Assets/Plugins/MessagePack/SequencePool.cs.meta deleted file mode 100644 index 3c898c9cb..000000000 --- a/Assets/Plugins/MessagePack/SequencePool.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: cd6feadb8ef11ef71b6f41d1dda885d7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/SequenceReader.cs b/Assets/Plugins/MessagePack/SequenceReader.cs deleted file mode 100644 index 7dde28695..000000000 --- a/Assets/Plugins/MessagePack/SequenceReader.cs +++ /dev/null @@ -1,495 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -/* Licensed to the .NET Foundation under one or more agreements. - * The .NET Foundation licenses this file to you under the MIT license. - * See the LICENSE file in the project root for more information. */ - -using System.Diagnostics; -using System.Runtime.CompilerServices; - -namespace System.Buffers -{ - internal ref partial struct SequenceReader - where T : unmanaged, IEquatable - { - /// - /// A value indicating whether we're using (as opposed to . - /// - private bool usingSequence; - - /// - /// Backing for the entire sequence when we're not using . - /// - private ReadOnlySequence sequence; - - /// - /// The position at the start of the . - /// - private SequencePosition currentPosition; - - /// - /// The position at the end of the . - /// - private SequencePosition nextPosition; - - /// - /// Backing for the entire sequence when we're not using . - /// - private ReadOnlyMemory memory; - - /// - /// A value indicating whether there is unread data remaining. - /// - private bool moreData; - - /// - /// The total number of elements in the sequence. - /// - private long length; - - /// - /// Initializes a new instance of the struct - /// over the given . - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public SequenceReader(in ReadOnlySequence sequence) - { - this.usingSequence = true; - this.CurrentSpanIndex = 0; - this.Consumed = 0; - this.sequence = sequence; - this.memory = default; - this.currentPosition = sequence.Start; - this.length = -1; - - ReadOnlySpan first = sequence.First.Span; - this.nextPosition = sequence.GetPosition(first.Length); - this.CurrentSpan = first; - this.moreData = first.Length > 0; - - if (!this.moreData && !sequence.IsSingleSegment) - { - this.moreData = true; - this.GetNextSpan(); - } - } - - /// - /// Initializes a new instance of the struct - /// over the given . - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public SequenceReader(ReadOnlyMemory memory) - { - this.usingSequence = false; - this.CurrentSpanIndex = 0; - this.Consumed = 0; - this.memory = memory; - this.CurrentSpan = memory.Span; - this.length = memory.Length; - this.moreData = memory.Length > 0; - - this.currentPosition = default; - this.nextPosition = default; - this.sequence = default; - } - - /// - /// Gets a value indicating whether there is no more data in the . - /// - public bool End => !this.moreData; - - /// - /// Gets the underlying for the reader. - /// - public ReadOnlySequence Sequence - { - get - { - if (this.sequence.IsEmpty && !this.memory.IsEmpty) - { - // We're in memory mode (instead of sequence mode). - // Lazily fill in the sequence data. - this.sequence = new ReadOnlySequence(this.memory); - this.currentPosition = this.sequence.Start; - this.nextPosition = this.sequence.End; - } - - return this.sequence; - } - } - - /// - /// Gets the current position in the . - /// - public SequencePosition Position - => this.Sequence.GetPosition(this.CurrentSpanIndex, this.currentPosition); - - /// - /// Gets the current segment in the as a span. - /// - public ReadOnlySpan CurrentSpan { get; private set; } - - /// - /// Gets the index in the . - /// - public int CurrentSpanIndex { get; private set; } - - /// - /// Gets the unread portion of the . - /// - public ReadOnlySpan UnreadSpan - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => this.CurrentSpan.Slice(this.CurrentSpanIndex); - } - - /// - /// Gets the total number of 's processed by the reader. - /// - public long Consumed { get; private set; } - - /// - /// Gets remaining 's in the reader's . - /// - public long Remaining => this.Length - this.Consumed; - - /// - /// Gets count of in the reader's . - /// - public long Length - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get - { - if (this.length < 0) - { - // Cache the length - this.length = this.Sequence.Length; - } - - return this.length; - } - } - - /// - /// Peeks at the next value without advancing the reader. - /// - /// The next value or default if at the end. - /// False if at the end of the reader. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool TryPeek(out T value) - { - if (this.moreData) - { - value = this.CurrentSpan[this.CurrentSpanIndex]; - return true; - } - else - { - value = default; - return false; - } - } - - /// - /// Read the next value and advance the reader. - /// - /// The next value or default if at the end. - /// False if at the end of the reader. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool TryRead(out T value) - { - if (this.End) - { - value = default; - return false; - } - - value = this.CurrentSpan[this.CurrentSpanIndex]; - this.CurrentSpanIndex++; - this.Consumed++; - - if (this.CurrentSpanIndex >= this.CurrentSpan.Length) - { - if (this.usingSequence) - { - this.GetNextSpan(); - } - else - { - this.moreData = false; - } - } - - return true; - } - - /// - /// Move the reader back the specified number of items. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Rewind(long count) - { - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - - this.Consumed -= count; - - if (this.CurrentSpanIndex >= count) - { - this.CurrentSpanIndex -= (int)count; - this.moreData = true; - } - else if (this.usingSequence) - { - // Current segment doesn't have enough data, scan backward through segments - this.RetreatToPreviousSpan(this.Consumed); - } - else - { - throw new ArgumentOutOfRangeException("Rewind went past the start of the memory."); - } - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private void RetreatToPreviousSpan(long consumed) - { - Debug.Assert(this.usingSequence, "usingSequence"); - this.ResetReader(); - this.Advance(consumed); - } - - private void ResetReader() - { - Debug.Assert(this.usingSequence, "usingSequence"); - this.CurrentSpanIndex = 0; - this.Consumed = 0; - this.currentPosition = this.Sequence.Start; - this.nextPosition = this.currentPosition; - - if (this.Sequence.TryGet(ref this.nextPosition, out ReadOnlyMemory memory, advance: true)) - { - this.moreData = true; - - if (memory.Length == 0) - { - this.CurrentSpan = default; - - // No data in the first span, move to one with data - this.GetNextSpan(); - } - else - { - this.CurrentSpan = memory.Span; - } - } - else - { - // No data in any spans and at end of sequence - this.moreData = false; - this.CurrentSpan = default; - } - } - - /// - /// Get the next segment with available data, if any. - /// - private void GetNextSpan() - { - Debug.Assert(this.usingSequence, "usingSequence"); - if (!this.Sequence.IsSingleSegment) - { - SequencePosition previousNextPosition = this.nextPosition; - while (this.Sequence.TryGet(ref this.nextPosition, out ReadOnlyMemory memory, advance: true)) - { - this.currentPosition = previousNextPosition; - if (memory.Length > 0) - { - this.CurrentSpan = memory.Span; - this.CurrentSpanIndex = 0; - return; - } - else - { - this.CurrentSpan = default; - this.CurrentSpanIndex = 0; - previousNextPosition = this.nextPosition; - } - } - } - - this.moreData = false; - } - - /// - /// Move the reader ahead the specified number of items. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Advance(long count) - { - const long TooBigOrNegative = unchecked((long)0xFFFFFFFF80000000); - if ((count & TooBigOrNegative) == 0 && this.CurrentSpan.Length - this.CurrentSpanIndex > (int)count) - { - this.CurrentSpanIndex += (int)count; - this.Consumed += count; - } - else if (this.usingSequence) - { - // Can't satisfy from the current span - this.AdvanceToNextSpan(count); - } - else if (this.CurrentSpan.Length - this.CurrentSpanIndex == (int)count) - { - this.CurrentSpanIndex += (int)count; - this.Consumed += count; - this.moreData = false; - } - else - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - } - - /// - /// Unchecked helper to avoid unnecessary checks where you know count is valid. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal void AdvanceCurrentSpan(long count) - { - Debug.Assert(count >= 0, "count >= 0"); - - this.Consumed += count; - this.CurrentSpanIndex += (int)count; - if (this.usingSequence && this.CurrentSpanIndex >= this.CurrentSpan.Length) - { - this.GetNextSpan(); - } - } - - /// - /// Only call this helper if you know that you are advancing in the current span - /// with valid count and there is no need to fetch the next one. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal void AdvanceWithinSpan(long count) - { - Debug.Assert(count >= 0, "count >= 0"); - - this.Consumed += count; - this.CurrentSpanIndex += (int)count; - - Debug.Assert(this.CurrentSpanIndex < this.CurrentSpan.Length, "this.CurrentSpanIndex < this.CurrentSpan.Length"); - } - - /// - /// Move the reader ahead the specified number of items - /// if there are enough elements remaining in the sequence. - /// - /// true if there were enough elements to advance; otherwise false. - internal bool TryAdvance(long count) - { - if (this.Remaining < count) - { - return false; - } - - this.Advance(count); - return true; - } - - private void AdvanceToNextSpan(long count) - { - Debug.Assert(this.usingSequence, "usingSequence"); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - - this.Consumed += count; - while (this.moreData) - { - int remaining = this.CurrentSpan.Length - this.CurrentSpanIndex; - - if (remaining > count) - { - this.CurrentSpanIndex += (int)count; - count = 0; - break; - } - - // As there may not be any further segments we need to - // push the current index to the end of the span. - this.CurrentSpanIndex += remaining; - count -= remaining; - Debug.Assert(count >= 0, "count >= 0"); - - this.GetNextSpan(); - - if (count == 0) - { - break; - } - } - - if (count != 0) - { - // Not enough data left- adjust for where we actually ended and throw - this.Consumed -= count; - throw new ArgumentOutOfRangeException(nameof(count)); - } - } - - /// - /// Copies data from the current to the given span. - /// - /// Destination to copy to. - /// True if there is enough data to copy to the . - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool TryCopyTo(Span destination) - { - ReadOnlySpan firstSpan = this.UnreadSpan; - if (firstSpan.Length >= destination.Length) - { - firstSpan.Slice(0, destination.Length).CopyTo(destination); - return true; - } - - return this.TryCopyMultisegment(destination); - } - - internal bool TryCopyMultisegment(Span destination) - { - if (this.Remaining < destination.Length) - { - return false; - } - - ReadOnlySpan firstSpan = this.UnreadSpan; - Debug.Assert(firstSpan.Length < destination.Length, "firstSpan.Length < destination.Length"); - firstSpan.CopyTo(destination); - int copied = firstSpan.Length; - - SequencePosition next = this.nextPosition; - while (this.Sequence.TryGet(ref next, out ReadOnlyMemory nextSegment, true)) - { - if (nextSegment.Length > 0) - { - ReadOnlySpan nextSpan = nextSegment.Span; - int toCopy = Math.Min(nextSpan.Length, destination.Length - copied); - nextSpan.Slice(0, toCopy).CopyTo(destination.Slice(copied)); - copied += toCopy; - if (copied >= destination.Length) - { - break; - } - } - } - - return true; - } - } -} diff --git a/Assets/Plugins/MessagePack/SequenceReader.cs.meta b/Assets/Plugins/MessagePack/SequenceReader.cs.meta deleted file mode 100644 index 9a2303305..000000000 --- a/Assets/Plugins/MessagePack/SequenceReader.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: cbb8a87bafcd3e0c9ad1efa790e7943c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/SequenceReaderExtensions.cs b/Assets/Plugins/MessagePack/SequenceReaderExtensions.cs deleted file mode 100644 index e56275ac1..000000000 --- a/Assets/Plugins/MessagePack/SequenceReaderExtensions.cs +++ /dev/null @@ -1,300 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -/* Licensed to the .NET Foundation under one or more agreements. - * The .NET Foundation licenses this file to you under the MIT license. - * See the LICENSE file in the project root for more information. */ - -using System.Buffers.Binary; -using System.Diagnostics; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace System.Buffers -{ - internal static partial class SequenceReaderExtensions - { - /// - /// Try to read the given type out of the buffer if possible. Warning: this is dangerous to use with arbitrary - /// structs- see remarks for full details. - /// - /// - /// IMPORTANT: The read is a straight copy of bits. If a struct depends on specific state of its members to - /// behave correctly this can lead to exceptions, etc. If reading endian specific integers, use the explicit - /// overloads such as . - /// - /// - /// True if successful. will be default if failed (due to lack of space). - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static unsafe bool TryRead(ref this SequenceReader reader, out T value) - where T : unmanaged - { - ReadOnlySpan span = reader.UnreadSpan; - if (span.Length < sizeof(T)) - { - return TryReadMultisegment(ref reader, out value); - } - - value = Unsafe.ReadUnaligned(ref MemoryMarshal.GetReference(span)); - reader.Advance(sizeof(T)); - return true; - } - -#if UNITY_ANDROID - - /// - /// In Android 32bit device(armv7) + IL2CPP does not work correctly on Unsafe.ReadUnaligned. - /// Perhaps it is about memory alignment bug of Unity's IL2CPP VM. - /// For a workaround, read memory manually. - /// https://github.com/neuecc/MessagePack-CSharp/issues/748 - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static unsafe bool TryRead(ref this SequenceReader reader, out long value) - { - ReadOnlySpan span = reader.UnreadSpan; - if (span.Length < sizeof(long)) - { - return TryReadMultisegment(ref reader, out value); - } - - value = BitConverterToInt64(span); - reader.Advance(sizeof(long)); - return true; - } - - private static unsafe long BitConverterToInt64(ReadOnlySpan value) - { - if (BitConverter.IsLittleEndian) - { - int i1 = value[0] | (value[1] << 8) | (value[2] << 16) | (value[3] << 24); - int i2 = value[4] | (value[5] << 8) | (value[6] << 16) | (value[7] << 24); - return (uint)i1 | ((long)i2 << 32); - } - else - { - int i1 = (value[0] << 24) | (value[1] << 16) | (value[2] << 8) | value[3]; - int i2 = (value[4] << 24) | (value[5] << 16) | (value[6] << 8) | value[7]; - return (uint)i2 | ((long)i1 << 32); - } - } - -#endif - - private static unsafe bool TryReadMultisegment(ref SequenceReader reader, out T value) - where T : unmanaged - { - Debug.Assert(reader.UnreadSpan.Length < sizeof(T), "reader.UnreadSpan.Length < sizeof(T)"); - - // Not enough data in the current segment, try to peek for the data we need. - T buffer = default; - Span tempSpan = new Span(&buffer, sizeof(T)); - - if (!reader.TryCopyTo(tempSpan)) - { - value = default; - return false; - } - - value = Unsafe.ReadUnaligned(ref MemoryMarshal.GetReference(tempSpan)); - reader.Advance(sizeof(T)); - return true; - } - -#if UNITY_ANDROID - - private static unsafe bool TryReadMultisegment(ref SequenceReader reader, out long value) - { - Debug.Assert(reader.UnreadSpan.Length < sizeof(long), "reader.UnreadSpan.Length < sizeof(long)"); - - // Not enough data in the current segment, try to peek for the data we need. - long buffer = default; - Span tempSpan = new Span(&buffer, sizeof(long)); - - if (!reader.TryCopyTo(tempSpan)) - { - value = default; - return false; - } - - value = BitConverterToInt64(tempSpan); - reader.Advance(sizeof(long)); - return true; - } - -#endif - - /// - /// Reads an from the next position in the sequence. - /// - /// The reader to read from. - /// Receives the value read. - /// true if there was another byte in the sequence; false otherwise. - public static bool TryRead(ref this SequenceReader reader, out sbyte value) - { - if (TryRead(ref reader, out byte byteValue)) - { - value = unchecked((sbyte)byteValue); - return true; - } - - value = default; - return false; - } - - /// - /// Reads an as big endian. - /// - /// False if there wasn't enough data for an . - public static bool TryReadBigEndian(ref this SequenceReader reader, out short value) - { - if (!BitConverter.IsLittleEndian) - { - return reader.TryRead(out value); - } - - return TryReadReverseEndianness(ref reader, out value); - } - - /// - /// Reads an as big endian. - /// - /// False if there wasn't enough data for an . - public static bool TryReadBigEndian(ref this SequenceReader reader, out ushort value) - { - if (TryReadBigEndian(ref reader, out short shortValue)) - { - value = unchecked((ushort)shortValue); - return true; - } - - value = default; - return false; - } - - private static bool TryReadReverseEndianness(ref SequenceReader reader, out short value) - { - if (reader.TryRead(out value)) - { - value = BinaryPrimitives.ReverseEndianness(value); - return true; - } - - return false; - } - - /// - /// Reads an as big endian. - /// - /// False if there wasn't enough data for an . - public static bool TryReadBigEndian(ref this SequenceReader reader, out int value) - { - if (!BitConverter.IsLittleEndian) - { - return reader.TryRead(out value); - } - - return TryReadReverseEndianness(ref reader, out value); - } - - /// - /// Reads an as big endian. - /// - /// False if there wasn't enough data for an . - public static bool TryReadBigEndian(ref this SequenceReader reader, out uint value) - { - if (TryReadBigEndian(ref reader, out int intValue)) - { - value = unchecked((uint)intValue); - return true; - } - - value = default; - return false; - } - - private static bool TryReadReverseEndianness(ref SequenceReader reader, out int value) - { - if (reader.TryRead(out value)) - { - value = BinaryPrimitives.ReverseEndianness(value); - return true; - } - - return false; - } - - /// - /// Reads an as big endian. - /// - /// False if there wasn't enough data for an . - public static bool TryReadBigEndian(ref this SequenceReader reader, out long value) - { - if (!BitConverter.IsLittleEndian) - { - return reader.TryRead(out value); - } - - return TryReadReverseEndianness(ref reader, out value); - } - - /// - /// Reads an as big endian. - /// - /// False if there wasn't enough data for an . - public static bool TryReadBigEndian(ref this SequenceReader reader, out ulong value) - { - if (TryReadBigEndian(ref reader, out long longValue)) - { - value = unchecked((ulong)longValue); - return true; - } - - value = default; - return false; - } - - private static bool TryReadReverseEndianness(ref SequenceReader reader, out long value) - { - if (reader.TryRead(out value)) - { - value = BinaryPrimitives.ReverseEndianness(value); - return true; - } - - return false; - } - - /// - /// Reads a as big endian. - /// - /// False if there wasn't enough data for a . - public static unsafe bool TryReadBigEndian(ref this SequenceReader reader, out float value) - { - if (TryReadBigEndian(ref reader, out int intValue)) - { - value = *(float*)&intValue; - return true; - } - - value = default; - return false; - } - - /// - /// Reads a as big endian. - /// - /// False if there wasn't enough data for a . - public static unsafe bool TryReadBigEndian(ref this SequenceReader reader, out double value) - { - if (TryReadBigEndian(ref reader, out long longValue)) - { - value = *(double*)&longValue; - return true; - } - - value = default; - return false; - } - } -} diff --git a/Assets/Plugins/MessagePack/SequenceReaderExtensions.cs.meta b/Assets/Plugins/MessagePack/SequenceReaderExtensions.cs.meta deleted file mode 100644 index 6c54f4468..000000000 --- a/Assets/Plugins/MessagePack/SequenceReaderExtensions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 7badd702e46d7aef6ad8c347e9c0d0cf -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/StreamPolyfillExtensions.cs b/Assets/Plugins/MessagePack/StreamPolyfillExtensions.cs deleted file mode 100644 index 2b6222c89..000000000 --- a/Assets/Plugins/MessagePack/StreamPolyfillExtensions.cs +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections.Generic; -using System.IO; -using System.Runtime.InteropServices; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Microsoft; - -namespace MessagePack -{ -#if !SPAN_BUILTIN - internal static class StreamPolyfillExtensions - { - /// - /// Reads from the stream into a memory buffer. - /// - /// The stream to read from. - /// The buffer to read directly into. - /// The number of bytes actually read. - internal static int Read(this Stream stream, Span buffer) - { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - byte[] array = ArrayPool.Shared.Rent(buffer.Length); - try - { - int bytesRead = stream.Read(array, 0, buffer.Length); - new Span(array, 0, bytesRead).CopyTo(buffer); - return bytesRead; - } - finally - { - ArrayPool.Shared.Return(array); - } - } - - /// - /// Reads from the stream into a memory buffer. - /// - /// The stream to read from. - /// The buffer to read directly into. - /// A cancellation token. - /// The number of bytes actually read. - /// - /// This method shamelessly copied from the .NET Core 2.1 Stream class: https://github.com/dotnet/coreclr/blob/a113b1c803783c9d64f1f0e946ff9a853e3bc140/src/System.Private.CoreLib/shared/System/IO/Stream.cs#L366-L391. - /// - internal static ValueTask ReadAsync(this Stream stream, Memory buffer, CancellationToken cancellationToken = default) - { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (MemoryMarshal.TryGetArray(buffer, out ArraySegment array)) - { - return new ValueTask(stream.ReadAsync(array.Array, array.Offset, array.Count, cancellationToken)); - } - else - { - byte[] sharedBuffer = ArrayPool.Shared.Rent(buffer.Length); - return FinishReadAsync(stream.ReadAsync(sharedBuffer, 0, buffer.Length, cancellationToken), sharedBuffer, buffer); - - async ValueTask FinishReadAsync(Task readTask, byte[] localBuffer, Memory localDestination) - { - try - { - int result = await readTask.ConfigureAwait(false); - new Span(localBuffer, 0, result).CopyTo(localDestination.Span); - return result; - } - finally - { - ArrayPool.Shared.Return(localBuffer); - } - } - } - } - - /// - /// Writes a span to the stream. - /// - /// The stream to write to. - /// The buffer to write. - internal static void Write(this Stream stream, ReadOnlySpan buffer) - { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - var sharedBuffer = ArrayPool.Shared.Rent(buffer.Length); - try - { - buffer.CopyTo(sharedBuffer); - stream.Write(sharedBuffer, 0, buffer.Length); - } - finally - { - ArrayPool.Shared.Return(sharedBuffer); - } - } - - /// - /// Writes a span to the stream. - /// - /// The stream to write to. - /// The buffer to write. - /// A cancellation token. - internal static async ValueTask WriteAsync(this Stream stream, ReadOnlyMemory buffer, CancellationToken cancellationToken) - { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - var sharedBuffer = ArrayPool.Shared.Rent(buffer.Length); - try - { - buffer.CopyTo(sharedBuffer); - await stream.WriteAsync(sharedBuffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); - } - finally - { - ArrayPool.Shared.Return(sharedBuffer); - } - } - } -#endif -} diff --git a/Assets/Plugins/MessagePack/StreamPolyfillExtensions.cs.meta b/Assets/Plugins/MessagePack/StreamPolyfillExtensions.cs.meta deleted file mode 100644 index e015fd12e..000000000 --- a/Assets/Plugins/MessagePack/StreamPolyfillExtensions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ac9db623f6c6eb2f3aa9b726e830686f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/StringEncoding.cs b/Assets/Plugins/MessagePack/StringEncoding.cs deleted file mode 100644 index db8115a39..000000000 --- a/Assets/Plugins/MessagePack/StringEncoding.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Diagnostics; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Text; - -namespace MessagePack -{ - internal static class StringEncoding - { - internal static readonly Encoding UTF8 = new UTF8Encoding(false); - -#if !NETCOREAPP2_1 // Define the extension method only where an instance method does not already exist. - internal static unsafe string GetString(this Encoding encoding, ReadOnlySpan bytes) - { - if (bytes.Length == 0) - { - return string.Empty; - } - - fixed (byte* pBytes = bytes) - { - return encoding.GetString(pBytes, bytes.Length); - } - } -#endif - } -} diff --git a/Assets/Plugins/MessagePack/StringEncoding.cs.meta b/Assets/Plugins/MessagePack/StringEncoding.cs.meta deleted file mode 100644 index 1f29e6947..000000000 --- a/Assets/Plugins/MessagePack/StringEncoding.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d113f4a9f2be39b9cb4d38521393fd3e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/T4.meta b/Assets/Plugins/MessagePack/T4.meta deleted file mode 100644 index 204dd8b11..000000000 --- a/Assets/Plugins/MessagePack/T4.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 61b9a85cd8f85c2449c3fb3fdcc85f70 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/T4/ForceSizePrimitiveFormatter.cs b/Assets/Plugins/MessagePack/T4/ForceSizePrimitiveFormatter.cs deleted file mode 100644 index fe05ab152..000000000 --- a/Assets/Plugins/MessagePack/T4/ForceSizePrimitiveFormatter.cs +++ /dev/null @@ -1,793 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -/* THIS (.cs) FILE IS GENERATED. DO NOT CHANGE IT. - * CHANGE THE .tt FILE INSTEAD. */ - -using System; -using System.Buffers; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - public sealed class ForceInt16BlockFormatter : IMessagePackFormatter - { - public static readonly ForceInt16BlockFormatter Instance = new ForceInt16BlockFormatter(); - - private ForceInt16BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int16 value, MessagePackSerializerOptions options) - { - writer.WriteInt16(value); - } - - public Int16 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadInt16(); - } - } - - public sealed class NullableForceInt16BlockFormatter : IMessagePackFormatter - { - public static readonly NullableForceInt16BlockFormatter Instance = new NullableForceInt16BlockFormatter(); - - private NullableForceInt16BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int16? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteInt16(value.Value); - } - } - - public Int16? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadInt16(); - } - } - } - - public sealed class ForceInt16BlockArrayFormatter : IMessagePackFormatter - { - public static readonly ForceInt16BlockArrayFormatter Instance = new ForceInt16BlockArrayFormatter(); - - private ForceInt16BlockArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int16[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.WriteInt16(value[i]); - } - } - } - - public Int16[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var len = reader.ReadArrayHeader(); - var array = new Int16[len]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadInt16(); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } - } - - public sealed class ForceInt32BlockFormatter : IMessagePackFormatter - { - public static readonly ForceInt32BlockFormatter Instance = new ForceInt32BlockFormatter(); - - private ForceInt32BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int32 value, MessagePackSerializerOptions options) - { - writer.WriteInt32(value); - } - - public Int32 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadInt32(); - } - } - - public sealed class NullableForceInt32BlockFormatter : IMessagePackFormatter - { - public static readonly NullableForceInt32BlockFormatter Instance = new NullableForceInt32BlockFormatter(); - - private NullableForceInt32BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int32? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteInt32(value.Value); - } - } - - public Int32? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadInt32(); - } - } - } - - public sealed class ForceInt32BlockArrayFormatter : IMessagePackFormatter - { - public static readonly ForceInt32BlockArrayFormatter Instance = new ForceInt32BlockArrayFormatter(); - - private ForceInt32BlockArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int32[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.WriteInt32(value[i]); - } - } - } - - public Int32[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var len = reader.ReadArrayHeader(); - var array = new Int32[len]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadInt32(); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } - } - - public sealed class ForceInt64BlockFormatter : IMessagePackFormatter - { - public static readonly ForceInt64BlockFormatter Instance = new ForceInt64BlockFormatter(); - - private ForceInt64BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int64 value, MessagePackSerializerOptions options) - { - writer.WriteInt64(value); - } - - public Int64 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadInt64(); - } - } - - public sealed class NullableForceInt64BlockFormatter : IMessagePackFormatter - { - public static readonly NullableForceInt64BlockFormatter Instance = new NullableForceInt64BlockFormatter(); - - private NullableForceInt64BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int64? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteInt64(value.Value); - } - } - - public Int64? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadInt64(); - } - } - } - - public sealed class ForceInt64BlockArrayFormatter : IMessagePackFormatter - { - public static readonly ForceInt64BlockArrayFormatter Instance = new ForceInt64BlockArrayFormatter(); - - private ForceInt64BlockArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int64[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.WriteInt64(value[i]); - } - } - } - - public Int64[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var len = reader.ReadArrayHeader(); - var array = new Int64[len]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadInt64(); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } - } - - public sealed class ForceUInt16BlockFormatter : IMessagePackFormatter - { - public static readonly ForceUInt16BlockFormatter Instance = new ForceUInt16BlockFormatter(); - - private ForceUInt16BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt16 value, MessagePackSerializerOptions options) - { - writer.WriteUInt16(value); - } - - public UInt16 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadUInt16(); - } - } - - public sealed class NullableForceUInt16BlockFormatter : IMessagePackFormatter - { - public static readonly NullableForceUInt16BlockFormatter Instance = new NullableForceUInt16BlockFormatter(); - - private NullableForceUInt16BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt16? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteUInt16(value.Value); - } - } - - public UInt16? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadUInt16(); - } - } - } - - public sealed class ForceUInt16BlockArrayFormatter : IMessagePackFormatter - { - public static readonly ForceUInt16BlockArrayFormatter Instance = new ForceUInt16BlockArrayFormatter(); - - private ForceUInt16BlockArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt16[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.WriteUInt16(value[i]); - } - } - } - - public UInt16[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var len = reader.ReadArrayHeader(); - var array = new UInt16[len]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadUInt16(); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } - } - - public sealed class ForceUInt32BlockFormatter : IMessagePackFormatter - { - public static readonly ForceUInt32BlockFormatter Instance = new ForceUInt32BlockFormatter(); - - private ForceUInt32BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt32 value, MessagePackSerializerOptions options) - { - writer.WriteUInt32(value); - } - - public UInt32 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadUInt32(); - } - } - - public sealed class NullableForceUInt32BlockFormatter : IMessagePackFormatter - { - public static readonly NullableForceUInt32BlockFormatter Instance = new NullableForceUInt32BlockFormatter(); - - private NullableForceUInt32BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt32? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteUInt32(value.Value); - } - } - - public UInt32? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadUInt32(); - } - } - } - - public sealed class ForceUInt32BlockArrayFormatter : IMessagePackFormatter - { - public static readonly ForceUInt32BlockArrayFormatter Instance = new ForceUInt32BlockArrayFormatter(); - - private ForceUInt32BlockArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt32[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.WriteUInt32(value[i]); - } - } - } - - public UInt32[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var len = reader.ReadArrayHeader(); - var array = new UInt32[len]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadUInt32(); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } - } - - public sealed class ForceUInt64BlockFormatter : IMessagePackFormatter - { - public static readonly ForceUInt64BlockFormatter Instance = new ForceUInt64BlockFormatter(); - - private ForceUInt64BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt64 value, MessagePackSerializerOptions options) - { - writer.WriteUInt64(value); - } - - public UInt64 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadUInt64(); - } - } - - public sealed class NullableForceUInt64BlockFormatter : IMessagePackFormatter - { - public static readonly NullableForceUInt64BlockFormatter Instance = new NullableForceUInt64BlockFormatter(); - - private NullableForceUInt64BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt64? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteUInt64(value.Value); - } - } - - public UInt64? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadUInt64(); - } - } - } - - public sealed class ForceUInt64BlockArrayFormatter : IMessagePackFormatter - { - public static readonly ForceUInt64BlockArrayFormatter Instance = new ForceUInt64BlockArrayFormatter(); - - private ForceUInt64BlockArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt64[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.WriteUInt64(value[i]); - } - } - } - - public UInt64[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var len = reader.ReadArrayHeader(); - var array = new UInt64[len]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadUInt64(); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } - } - - public sealed class ForceByteBlockFormatter : IMessagePackFormatter - { - public static readonly ForceByteBlockFormatter Instance = new ForceByteBlockFormatter(); - - private ForceByteBlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Byte value, MessagePackSerializerOptions options) - { - writer.WriteUInt8(value); - } - - public Byte Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadByte(); - } - } - - public sealed class NullableForceByteBlockFormatter : IMessagePackFormatter - { - public static readonly NullableForceByteBlockFormatter Instance = new NullableForceByteBlockFormatter(); - - private NullableForceByteBlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Byte? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteUInt8(value.Value); - } - } - - public Byte? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadByte(); - } - } - } - - public sealed class ForceSByteBlockFormatter : IMessagePackFormatter - { - public static readonly ForceSByteBlockFormatter Instance = new ForceSByteBlockFormatter(); - - private ForceSByteBlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, SByte value, MessagePackSerializerOptions options) - { - writer.WriteInt8(value); - } - - public SByte Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadSByte(); - } - } - - public sealed class NullableForceSByteBlockFormatter : IMessagePackFormatter - { - public static readonly NullableForceSByteBlockFormatter Instance = new NullableForceSByteBlockFormatter(); - - private NullableForceSByteBlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, SByte? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteInt8(value.Value); - } - } - - public SByte? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadSByte(); - } - } - } - - public sealed class ForceSByteBlockArrayFormatter : IMessagePackFormatter - { - public static readonly ForceSByteBlockArrayFormatter Instance = new ForceSByteBlockArrayFormatter(); - - private ForceSByteBlockArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, SByte[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.WriteInt8(value[i]); - } - } - } - - public SByte[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var len = reader.ReadArrayHeader(); - var array = new SByte[len]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadSByte(); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } - } -} diff --git a/Assets/Plugins/MessagePack/T4/ForceSizePrimitiveFormatter.cs.meta b/Assets/Plugins/MessagePack/T4/ForceSizePrimitiveFormatter.cs.meta deleted file mode 100644 index 55915a259..000000000 --- a/Assets/Plugins/MessagePack/T4/ForceSizePrimitiveFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 7eebcdcfb5f87535cb2728f1c21072c2 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/T4/MessagePackReader.Integers.cs b/Assets/Plugins/MessagePack/T4/MessagePackReader.Integers.cs deleted file mode 100644 index d74c394cf..000000000 --- a/Assets/Plugins/MessagePack/T4/MessagePackReader.Integers.cs +++ /dev/null @@ -1,440 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -/* THIS (.cs) FILE IS GENERATED. DO NOT CHANGE IT. - * CHANGE THE .tt FILE INSTEAD. */ - -using System; -using System.Buffers; - -namespace MessagePack -{ -#pragma warning disable SA1205 // Partial elements should declare access - ref partial struct MessagePackReader -#pragma warning restore SA1205 // Partial elements should declare access - { - /// - /// Reads an value from: - /// Some value between and , - /// Some value between and , - /// or any of the other MsgPack integer types. - /// - /// The value. - /// Thrown when the value exceeds what can be stored in the returned type. - public Byte ReadByte() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - switch (code) - { - case MessagePackCode.UInt8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteResult)); - return checked((Byte)byteResult); - case MessagePackCode.Int8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out sbyte sbyteResult)); - return checked((Byte)sbyteResult); - case MessagePackCode.UInt16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ushort ushortResult)); - return checked((Byte)ushortResult); - case MessagePackCode.Int16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortResult)); - return checked((Byte)shortResult); - case MessagePackCode.UInt32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out uint uintResult)); - return checked((Byte)uintResult); - case MessagePackCode.Int32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intResult)); - return checked((Byte)intResult); - case MessagePackCode.UInt64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ulong ulongResult)); - return checked((Byte)ulongResult); - case MessagePackCode.Int64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longResult)); - return checked((Byte)longResult); - default: - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return checked((Byte)unchecked((sbyte)code)); - } - - if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return (Byte)code; - } - - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads an value from: - /// Some value between and , - /// Some value between and , - /// or any of the other MsgPack integer types. - /// - /// The value. - /// Thrown when the value exceeds what can be stored in the returned type. - public UInt16 ReadUInt16() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - switch (code) - { - case MessagePackCode.UInt8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteResult)); - return checked((UInt16)byteResult); - case MessagePackCode.Int8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out sbyte sbyteResult)); - return checked((UInt16)sbyteResult); - case MessagePackCode.UInt16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ushort ushortResult)); - return checked((UInt16)ushortResult); - case MessagePackCode.Int16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortResult)); - return checked((UInt16)shortResult); - case MessagePackCode.UInt32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out uint uintResult)); - return checked((UInt16)uintResult); - case MessagePackCode.Int32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intResult)); - return checked((UInt16)intResult); - case MessagePackCode.UInt64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ulong ulongResult)); - return checked((UInt16)ulongResult); - case MessagePackCode.Int64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longResult)); - return checked((UInt16)longResult); - default: - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return checked((UInt16)unchecked((sbyte)code)); - } - - if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return (UInt16)code; - } - - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads an value from: - /// Some value between and , - /// Some value between and , - /// or any of the other MsgPack integer types. - /// - /// The value. - /// Thrown when the value exceeds what can be stored in the returned type. - public UInt32 ReadUInt32() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - switch (code) - { - case MessagePackCode.UInt8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteResult)); - return checked((UInt32)byteResult); - case MessagePackCode.Int8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out sbyte sbyteResult)); - return checked((UInt32)sbyteResult); - case MessagePackCode.UInt16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ushort ushortResult)); - return checked((UInt32)ushortResult); - case MessagePackCode.Int16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortResult)); - return checked((UInt32)shortResult); - case MessagePackCode.UInt32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out uint uintResult)); - return checked((UInt32)uintResult); - case MessagePackCode.Int32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intResult)); - return checked((UInt32)intResult); - case MessagePackCode.UInt64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ulong ulongResult)); - return checked((UInt32)ulongResult); - case MessagePackCode.Int64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longResult)); - return checked((UInt32)longResult); - default: - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return checked((UInt32)unchecked((sbyte)code)); - } - - if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return (UInt32)code; - } - - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads an value from: - /// Some value between and , - /// Some value between and , - /// or any of the other MsgPack integer types. - /// - /// The value. - /// Thrown when the value exceeds what can be stored in the returned type. - public UInt64 ReadUInt64() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - switch (code) - { - case MessagePackCode.UInt8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteResult)); - return checked((UInt64)byteResult); - case MessagePackCode.Int8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out sbyte sbyteResult)); - return checked((UInt64)sbyteResult); - case MessagePackCode.UInt16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ushort ushortResult)); - return checked((UInt64)ushortResult); - case MessagePackCode.Int16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortResult)); - return checked((UInt64)shortResult); - case MessagePackCode.UInt32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out uint uintResult)); - return checked((UInt64)uintResult); - case MessagePackCode.Int32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intResult)); - return checked((UInt64)intResult); - case MessagePackCode.UInt64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ulong ulongResult)); - return checked((UInt64)ulongResult); - case MessagePackCode.Int64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longResult)); - return checked((UInt64)longResult); - default: - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return checked((UInt64)unchecked((sbyte)code)); - } - - if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return (UInt64)code; - } - - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads an value from: - /// Some value between and , - /// Some value between and , - /// or any of the other MsgPack integer types. - /// - /// The value. - /// Thrown when the value exceeds what can be stored in the returned type. - public SByte ReadSByte() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - switch (code) - { - case MessagePackCode.UInt8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteResult)); - return checked((SByte)byteResult); - case MessagePackCode.Int8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out sbyte sbyteResult)); - return checked((SByte)sbyteResult); - case MessagePackCode.UInt16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ushort ushortResult)); - return checked((SByte)ushortResult); - case MessagePackCode.Int16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortResult)); - return checked((SByte)shortResult); - case MessagePackCode.UInt32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out uint uintResult)); - return checked((SByte)uintResult); - case MessagePackCode.Int32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intResult)); - return checked((SByte)intResult); - case MessagePackCode.UInt64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ulong ulongResult)); - return checked((SByte)ulongResult); - case MessagePackCode.Int64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longResult)); - return checked((SByte)longResult); - default: - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return checked((SByte)unchecked((sbyte)code)); - } - - if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return (SByte)code; - } - - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads an value from: - /// Some value between and , - /// Some value between and , - /// or any of the other MsgPack integer types. - /// - /// The value. - /// Thrown when the value exceeds what can be stored in the returned type. - public Int16 ReadInt16() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - switch (code) - { - case MessagePackCode.UInt8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteResult)); - return checked((Int16)byteResult); - case MessagePackCode.Int8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out sbyte sbyteResult)); - return checked((Int16)sbyteResult); - case MessagePackCode.UInt16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ushort ushortResult)); - return checked((Int16)ushortResult); - case MessagePackCode.Int16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortResult)); - return checked((Int16)shortResult); - case MessagePackCode.UInt32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out uint uintResult)); - return checked((Int16)uintResult); - case MessagePackCode.Int32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intResult)); - return checked((Int16)intResult); - case MessagePackCode.UInt64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ulong ulongResult)); - return checked((Int16)ulongResult); - case MessagePackCode.Int64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longResult)); - return checked((Int16)longResult); - default: - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return checked((Int16)unchecked((sbyte)code)); - } - - if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return (Int16)code; - } - - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads an value from: - /// Some value between and , - /// Some value between and , - /// or any of the other MsgPack integer types. - /// - /// The value. - /// Thrown when the value exceeds what can be stored in the returned type. - public Int32 ReadInt32() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - switch (code) - { - case MessagePackCode.UInt8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteResult)); - return checked((Int32)byteResult); - case MessagePackCode.Int8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out sbyte sbyteResult)); - return checked((Int32)sbyteResult); - case MessagePackCode.UInt16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ushort ushortResult)); - return checked((Int32)ushortResult); - case MessagePackCode.Int16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortResult)); - return checked((Int32)shortResult); - case MessagePackCode.UInt32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out uint uintResult)); - return checked((Int32)uintResult); - case MessagePackCode.Int32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intResult)); - return checked((Int32)intResult); - case MessagePackCode.UInt64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ulong ulongResult)); - return checked((Int32)ulongResult); - case MessagePackCode.Int64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longResult)); - return checked((Int32)longResult); - default: - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return checked((Int32)unchecked((sbyte)code)); - } - - if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return (Int32)code; - } - - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads an value from: - /// Some value between and , - /// Some value between and , - /// or any of the other MsgPack integer types. - /// - /// The value. - /// Thrown when the value exceeds what can be stored in the returned type. - public Int64 ReadInt64() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - switch (code) - { - case MessagePackCode.UInt8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteResult)); - return checked((Int64)byteResult); - case MessagePackCode.Int8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out sbyte sbyteResult)); - return checked((Int64)sbyteResult); - case MessagePackCode.UInt16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ushort ushortResult)); - return checked((Int64)ushortResult); - case MessagePackCode.Int16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortResult)); - return checked((Int64)shortResult); - case MessagePackCode.UInt32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out uint uintResult)); - return checked((Int64)uintResult); - case MessagePackCode.Int32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intResult)); - return checked((Int64)intResult); - case MessagePackCode.UInt64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ulong ulongResult)); - return checked((Int64)ulongResult); - case MessagePackCode.Int64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longResult)); - return checked((Int64)longResult); - default: - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return checked((Int64)unchecked((sbyte)code)); - } - - if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return (Int64)code; - } - - throw ThrowInvalidCode(code); - } - } - } -} diff --git a/Assets/Plugins/MessagePack/T4/MessagePackReader.Integers.cs.meta b/Assets/Plugins/MessagePack/T4/MessagePackReader.Integers.cs.meta deleted file mode 100644 index 2ed3587af..000000000 --- a/Assets/Plugins/MessagePack/T4/MessagePackReader.Integers.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9c9a5153765d7dad39b4cc6d78e16f2c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/T4/PrimitiveFormatter.cs b/Assets/Plugins/MessagePack/T4/PrimitiveFormatter.cs deleted file mode 100644 index 94a3a1f9a..000000000 --- a/Assets/Plugins/MessagePack/T4/PrimitiveFormatter.cs +++ /dev/null @@ -1,1217 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -/* THIS (.cs) FILE IS GENERATED. DO NOT CHANGE IT. - * CHANGE THE .tt FILE INSTEAD. */ - -using System; -using System.Buffers; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - public sealed class Int16Formatter : IMessagePackFormatter - { - public static readonly Int16Formatter Instance = new Int16Formatter(); - - private Int16Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int16 value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public Int16 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadInt16(); - } - } - - public sealed class NullableInt16Formatter : IMessagePackFormatter - { - public static readonly NullableInt16Formatter Instance = new NullableInt16Formatter(); - - private NullableInt16Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int16? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public Int16? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadInt16(); - } - } - } - - public sealed class Int16ArrayFormatter : IMessagePackFormatter - { - public static readonly Int16ArrayFormatter Instance = new Int16ArrayFormatter(); - - private Int16ArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int16[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public Int16[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var len = reader.ReadArrayHeader(); - var array = new Int16[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadInt16(); - } - - return array; - } - } - } - - public sealed class Int32Formatter : IMessagePackFormatter - { - public static readonly Int32Formatter Instance = new Int32Formatter(); - - private Int32Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int32 value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public Int32 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadInt32(); - } - } - - public sealed class NullableInt32Formatter : IMessagePackFormatter - { - public static readonly NullableInt32Formatter Instance = new NullableInt32Formatter(); - - private NullableInt32Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int32? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public Int32? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadInt32(); - } - } - } - - public sealed class Int32ArrayFormatter : IMessagePackFormatter - { - public static readonly Int32ArrayFormatter Instance = new Int32ArrayFormatter(); - - private Int32ArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int32[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public Int32[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var len = reader.ReadArrayHeader(); - var array = new Int32[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadInt32(); - } - - return array; - } - } - } - - public sealed class Int64Formatter : IMessagePackFormatter - { - public static readonly Int64Formatter Instance = new Int64Formatter(); - - private Int64Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int64 value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public Int64 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadInt64(); - } - } - - public sealed class NullableInt64Formatter : IMessagePackFormatter - { - public static readonly NullableInt64Formatter Instance = new NullableInt64Formatter(); - - private NullableInt64Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int64? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public Int64? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadInt64(); - } - } - } - - public sealed class Int64ArrayFormatter : IMessagePackFormatter - { - public static readonly Int64ArrayFormatter Instance = new Int64ArrayFormatter(); - - private Int64ArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int64[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public Int64[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var len = reader.ReadArrayHeader(); - var array = new Int64[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadInt64(); - } - - return array; - } - } - } - - public sealed class UInt16Formatter : IMessagePackFormatter - { - public static readonly UInt16Formatter Instance = new UInt16Formatter(); - - private UInt16Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt16 value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public UInt16 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadUInt16(); - } - } - - public sealed class NullableUInt16Formatter : IMessagePackFormatter - { - public static readonly NullableUInt16Formatter Instance = new NullableUInt16Formatter(); - - private NullableUInt16Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt16? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public UInt16? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadUInt16(); - } - } - } - - public sealed class UInt16ArrayFormatter : IMessagePackFormatter - { - public static readonly UInt16ArrayFormatter Instance = new UInt16ArrayFormatter(); - - private UInt16ArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt16[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public UInt16[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var len = reader.ReadArrayHeader(); - var array = new UInt16[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadUInt16(); - } - - return array; - } - } - } - - public sealed class UInt32Formatter : IMessagePackFormatter - { - public static readonly UInt32Formatter Instance = new UInt32Formatter(); - - private UInt32Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt32 value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public UInt32 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadUInt32(); - } - } - - public sealed class NullableUInt32Formatter : IMessagePackFormatter - { - public static readonly NullableUInt32Formatter Instance = new NullableUInt32Formatter(); - - private NullableUInt32Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt32? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public UInt32? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadUInt32(); - } - } - } - - public sealed class UInt32ArrayFormatter : IMessagePackFormatter - { - public static readonly UInt32ArrayFormatter Instance = new UInt32ArrayFormatter(); - - private UInt32ArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt32[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public UInt32[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var len = reader.ReadArrayHeader(); - var array = new UInt32[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadUInt32(); - } - - return array; - } - } - } - - public sealed class UInt64Formatter : IMessagePackFormatter - { - public static readonly UInt64Formatter Instance = new UInt64Formatter(); - - private UInt64Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt64 value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public UInt64 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadUInt64(); - } - } - - public sealed class NullableUInt64Formatter : IMessagePackFormatter - { - public static readonly NullableUInt64Formatter Instance = new NullableUInt64Formatter(); - - private NullableUInt64Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt64? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public UInt64? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadUInt64(); - } - } - } - - public sealed class UInt64ArrayFormatter : IMessagePackFormatter - { - public static readonly UInt64ArrayFormatter Instance = new UInt64ArrayFormatter(); - - private UInt64ArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt64[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public UInt64[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var len = reader.ReadArrayHeader(); - var array = new UInt64[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadUInt64(); - } - - return array; - } - } - } - - public sealed class SingleFormatter : IMessagePackFormatter - { - public static readonly SingleFormatter Instance = new SingleFormatter(); - - private SingleFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Single value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public Single Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadSingle(); - } - } - - public sealed class NullableSingleFormatter : IMessagePackFormatter - { - public static readonly NullableSingleFormatter Instance = new NullableSingleFormatter(); - - private NullableSingleFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Single? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public Single? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadSingle(); - } - } - } - - public sealed class SingleArrayFormatter : IMessagePackFormatter - { - public static readonly SingleArrayFormatter Instance = new SingleArrayFormatter(); - - private SingleArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Single[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public Single[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var len = reader.ReadArrayHeader(); - var array = new Single[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadSingle(); - } - - return array; - } - } - } - - public sealed class DoubleFormatter : IMessagePackFormatter - { - public static readonly DoubleFormatter Instance = new DoubleFormatter(); - - private DoubleFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Double value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public Double Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadDouble(); - } - } - - public sealed class NullableDoubleFormatter : IMessagePackFormatter - { - public static readonly NullableDoubleFormatter Instance = new NullableDoubleFormatter(); - - private NullableDoubleFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Double? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public Double? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadDouble(); - } - } - } - - public sealed class DoubleArrayFormatter : IMessagePackFormatter - { - public static readonly DoubleArrayFormatter Instance = new DoubleArrayFormatter(); - - private DoubleArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Double[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public Double[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var len = reader.ReadArrayHeader(); - var array = new Double[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadDouble(); - } - - return array; - } - } - } - - public sealed class BooleanFormatter : IMessagePackFormatter - { - public static readonly BooleanFormatter Instance = new BooleanFormatter(); - - private BooleanFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Boolean value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public Boolean Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadBoolean(); - } - } - - public sealed class NullableBooleanFormatter : IMessagePackFormatter - { - public static readonly NullableBooleanFormatter Instance = new NullableBooleanFormatter(); - - private NullableBooleanFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Boolean? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public Boolean? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadBoolean(); - } - } - } - - public sealed class BooleanArrayFormatter : IMessagePackFormatter - { - public static readonly BooleanArrayFormatter Instance = new BooleanArrayFormatter(); - - private BooleanArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Boolean[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public Boolean[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var len = reader.ReadArrayHeader(); - var array = new Boolean[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadBoolean(); - } - - return array; - } - } - } - - public sealed class ByteFormatter : IMessagePackFormatter - { - public static readonly ByteFormatter Instance = new ByteFormatter(); - - private ByteFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Byte value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public Byte Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadByte(); - } - } - - public sealed class NullableByteFormatter : IMessagePackFormatter - { - public static readonly NullableByteFormatter Instance = new NullableByteFormatter(); - - private NullableByteFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Byte? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public Byte? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadByte(); - } - } - } - - public sealed class SByteFormatter : IMessagePackFormatter - { - public static readonly SByteFormatter Instance = new SByteFormatter(); - - private SByteFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, SByte value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public SByte Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadSByte(); - } - } - - public sealed class NullableSByteFormatter : IMessagePackFormatter - { - public static readonly NullableSByteFormatter Instance = new NullableSByteFormatter(); - - private NullableSByteFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, SByte? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public SByte? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadSByte(); - } - } - } - - public sealed class SByteArrayFormatter : IMessagePackFormatter - { - public static readonly SByteArrayFormatter Instance = new SByteArrayFormatter(); - - private SByteArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, SByte[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public SByte[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var len = reader.ReadArrayHeader(); - var array = new SByte[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadSByte(); - } - - return array; - } - } - } - - public sealed class CharFormatter : IMessagePackFormatter - { - public static readonly CharFormatter Instance = new CharFormatter(); - - private CharFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Char value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public Char Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadChar(); - } - } - - public sealed class NullableCharFormatter : IMessagePackFormatter - { - public static readonly NullableCharFormatter Instance = new NullableCharFormatter(); - - private NullableCharFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Char? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public Char? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadChar(); - } - } - } - - public sealed class CharArrayFormatter : IMessagePackFormatter - { - public static readonly CharArrayFormatter Instance = new CharArrayFormatter(); - - private CharArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Char[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public Char[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var len = reader.ReadArrayHeader(); - var array = new Char[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadChar(); - } - - return array; - } - } - } - - public sealed class DateTimeFormatter : IMessagePackFormatter - { - public static readonly DateTimeFormatter Instance = new DateTimeFormatter(); - - private DateTimeFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, DateTime value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public DateTime Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadDateTime(); - } - } - - public sealed class NullableDateTimeFormatter : IMessagePackFormatter - { - public static readonly NullableDateTimeFormatter Instance = new NullableDateTimeFormatter(); - - private NullableDateTimeFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, DateTime? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public DateTime? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadDateTime(); - } - } - } - - public sealed class DateTimeArrayFormatter : IMessagePackFormatter - { - public static readonly DateTimeArrayFormatter Instance = new DateTimeArrayFormatter(); - - private DateTimeArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, DateTime[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public DateTime[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var len = reader.ReadArrayHeader(); - var array = new DateTime[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadDateTime(); - } - - return array; - } - } - } -} diff --git a/Assets/Plugins/MessagePack/T4/PrimitiveFormatter.cs.meta b/Assets/Plugins/MessagePack/T4/PrimitiveFormatter.cs.meta deleted file mode 100644 index cf10f757f..000000000 --- a/Assets/Plugins/MessagePack/T4/PrimitiveFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1fcb53a5d362d2e38b66d0a88d35d78f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/T4/TupleFormatter.cs b/Assets/Plugins/MessagePack/T4/TupleFormatter.cs deleted file mode 100644 index e9a17419b..000000000 --- a/Assets/Plugins/MessagePack/T4/TupleFormatter.cs +++ /dev/null @@ -1,445 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -/* THIS (.cs) FILE IS GENERATED. DO NOT CHANGE IT. - * CHANGE THE .tt FILE INSTEAD. */ - -using System; -using System.Buffers; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - public sealed class TupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, Tuple value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(1); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - } - } - - public Tuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 1) - { - throw new MessagePackSerializationException("Invalid Tuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new Tuple(item1); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class TupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, Tuple value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(2); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - } - } - - public Tuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 2) - { - throw new MessagePackSerializationException("Invalid Tuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new Tuple(item1, item2); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class TupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, Tuple value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(3); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - } - } - - public Tuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 3) - { - throw new MessagePackSerializationException("Invalid Tuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new Tuple(item1, item2, item3); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class TupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, Tuple value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(4); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item4, options); - } - } - - public Tuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 4) - { - throw new MessagePackSerializationException("Invalid Tuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T4 item4 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new Tuple(item1, item2, item3, item4); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class TupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, Tuple value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(5); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item4, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item5, options); - } - } - - public Tuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 5) - { - throw new MessagePackSerializationException("Invalid Tuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T4 item4 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T5 item5 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new Tuple(item1, item2, item3, item4, item5); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class TupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, Tuple value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(6); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item4, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item5, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item6, options); - } - } - - public Tuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 6) - { - throw new MessagePackSerializationException("Invalid Tuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T4 item4 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T5 item5 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T6 item6 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new Tuple(item1, item2, item3, item4, item5, item6); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class TupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, Tuple value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(7); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item4, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item5, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item6, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item7, options); - } - } - - public Tuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 7) - { - throw new MessagePackSerializationException("Invalid Tuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T4 item4 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T5 item5 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T6 item6 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T7 item7 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new Tuple(item1, item2, item3, item4, item5, item6, item7); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class TupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, Tuple value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(8); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item4, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item5, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item6, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item7, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Rest, options); - } - } - - public Tuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 8) - { - throw new MessagePackSerializationException("Invalid Tuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T4 item4 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T5 item5 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T6 item6 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T7 item7 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - TRest item8 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new Tuple(item1, item2, item3, item4, item5, item6, item7, item8); - } - finally - { - reader.Depth--; - } - } - } - } -} diff --git a/Assets/Plugins/MessagePack/T4/TupleFormatter.cs.meta b/Assets/Plugins/MessagePack/T4/TupleFormatter.cs.meta deleted file mode 100644 index 70eeea793..000000000 --- a/Assets/Plugins/MessagePack/T4/TupleFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 21aa85f0a0973185698eec9b4ef8f3ba -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/T4/UnsafeMemory.cs b/Assets/Plugins/MessagePack/T4/UnsafeMemory.cs deleted file mode 100644 index d986575f2..000000000 --- a/Assets/Plugins/MessagePack/T4/UnsafeMemory.cs +++ /dev/null @@ -1,901 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -/* THIS (.cs) FILE IS GENERATED. DO NOT CHANGE IT. - * CHANGE THE .tt FILE INSTEAD. */ - -#if !UNITY_2018_3_OR_NEWER - -using System; -using System.Buffers; -using System.Runtime.CompilerServices; -using MessagePack.Formatters; - -namespace MessagePack.Internal -{ - public static partial class UnsafeMemory32 - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw4(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw5(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 1) = *(int*)(pSrc + 1); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw6(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 2) = *(int*)(pSrc + 2); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw7(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 3) = *(int*)(pSrc + 3); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw8(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw9(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 5) = *(int*)(pSrc + 5); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw10(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 6) = *(int*)(pSrc + 6); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw11(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 7) = *(int*)(pSrc + 7); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw12(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw13(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 9) = *(int*)(pSrc + 9); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw14(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 10) = *(int*)(pSrc + 10); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw15(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 11) = *(int*)(pSrc + 11); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw16(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw17(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 13) = *(int*)(pSrc + 13); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw18(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 14) = *(int*)(pSrc + 14); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw19(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 15) = *(int*)(pSrc + 15); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw20(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw21(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 17) = *(int*)(pSrc + 17); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw22(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 18) = *(int*)(pSrc + 18); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw23(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 19) = *(int*)(pSrc + 19); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw24(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 20) = *(int*)(pSrc + 20); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw25(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 20) = *(int*)(pSrc + 20); - *(int*)(pDst + 21) = *(int*)(pSrc + 21); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw26(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 20) = *(int*)(pSrc + 20); - *(int*)(pDst + 22) = *(int*)(pSrc + 22); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw27(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 20) = *(int*)(pSrc + 20); - *(int*)(pDst + 23) = *(int*)(pSrc + 23); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw28(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 20) = *(int*)(pSrc + 20); - *(int*)(pDst + 24) = *(int*)(pSrc + 24); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw29(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 20) = *(int*)(pSrc + 20); - *(int*)(pDst + 24) = *(int*)(pSrc + 24); - *(int*)(pDst + 25) = *(int*)(pSrc + 25); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw30(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 20) = *(int*)(pSrc + 20); - *(int*)(pDst + 24) = *(int*)(pSrc + 24); - *(int*)(pDst + 26) = *(int*)(pSrc + 26); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw31(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 20) = *(int*)(pSrc + 20); - *(int*)(pDst + 24) = *(int*)(pSrc + 24); - *(int*)(pDst + 27) = *(int*)(pSrc + 27); - } - - writer.Advance(src.Length); - } - } - - public static partial class UnsafeMemory64 - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw8(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw9(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 1) = *(long*)(pSrc + 1); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw10(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 2) = *(long*)(pSrc + 2); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw11(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 3) = *(long*)(pSrc + 3); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw12(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 4) = *(long*)(pSrc + 4); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw13(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 5) = *(long*)(pSrc + 5); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw14(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 6) = *(long*)(pSrc + 6); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw15(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 7) = *(long*)(pSrc + 7); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw16(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw17(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 9) = *(long*)(pSrc + 9); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw18(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 10) = *(long*)(pSrc + 10); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw19(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 11) = *(long*)(pSrc + 11); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw20(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 12) = *(long*)(pSrc + 12); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw21(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 13) = *(long*)(pSrc + 13); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw22(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 14) = *(long*)(pSrc + 14); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw23(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 15) = *(long*)(pSrc + 15); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw24(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 16) = *(long*)(pSrc + 16); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw25(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 16) = *(long*)(pSrc + 16); - *(long*)(pDst + 17) = *(long*)(pSrc + 17); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw26(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 16) = *(long*)(pSrc + 16); - *(long*)(pDst + 18) = *(long*)(pSrc + 18); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw27(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 16) = *(long*)(pSrc + 16); - *(long*)(pDst + 19) = *(long*)(pSrc + 19); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw28(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 16) = *(long*)(pSrc + 16); - *(long*)(pDst + 20) = *(long*)(pSrc + 20); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw29(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 16) = *(long*)(pSrc + 16); - *(long*)(pDst + 21) = *(long*)(pSrc + 21); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw30(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 16) = *(long*)(pSrc + 16); - *(long*)(pDst + 22) = *(long*)(pSrc + 22); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw31(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 16) = *(long*)(pSrc + 16); - *(long*)(pDst + 23) = *(long*)(pSrc + 23); - } - - writer.Advance(src.Length); - } - } -} - -#endif diff --git a/Assets/Plugins/MessagePack/T4/UnsafeMemory.cs.meta b/Assets/Plugins/MessagePack/T4/UnsafeMemory.cs.meta deleted file mode 100644 index fa04ad76d..000000000 --- a/Assets/Plugins/MessagePack/T4/UnsafeMemory.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ba8adf167b655e2a5a091ac6af276bb3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/T4/ValueTupleFormatter.cs b/Assets/Plugins/MessagePack/T4/ValueTupleFormatter.cs deleted file mode 100644 index cf78e8b01..000000000 --- a/Assets/Plugins/MessagePack/T4/ValueTupleFormatter.cs +++ /dev/null @@ -1,390 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -/* THIS (.cs) FILE IS GENERATED. DO NOT CHANGE IT. - * CHANGE THE .tt FILE INSTEAD. */ - -using System; -using System.Buffers; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - public sealed class ValueTupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, ValueTuple value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(1); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - } - - public ValueTuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new MessagePackSerializationException("Data is Nil, ValueTuple can not be null."); - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 1) - { - throw new MessagePackSerializationException("Invalid ValueTuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new ValueTuple(item1); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class ValueTupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, ValueTuple value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(2); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - } - - public ValueTuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new MessagePackSerializationException("Data is Nil, ValueTuple can not be null."); - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 2) - { - throw new MessagePackSerializationException("Invalid ValueTuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new ValueTuple(item1, item2); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class ValueTupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, ValueTuple value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(3); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - } - - public ValueTuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new MessagePackSerializationException("Data is Nil, ValueTuple can not be null."); - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 3) - { - throw new MessagePackSerializationException("Invalid ValueTuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new ValueTuple(item1, item2, item3); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class ValueTupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, ValueTuple value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(4); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item4, options); - } - - public ValueTuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new MessagePackSerializationException("Data is Nil, ValueTuple can not be null."); - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 4) - { - throw new MessagePackSerializationException("Invalid ValueTuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T4 item4 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new ValueTuple(item1, item2, item3, item4); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class ValueTupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, ValueTuple value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(5); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item4, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item5, options); - } - - public ValueTuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new MessagePackSerializationException("Data is Nil, ValueTuple can not be null."); - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 5) - { - throw new MessagePackSerializationException("Invalid ValueTuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T4 item4 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T5 item5 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new ValueTuple(item1, item2, item3, item4, item5); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class ValueTupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, ValueTuple value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(6); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item4, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item5, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item6, options); - } - - public ValueTuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new MessagePackSerializationException("Data is Nil, ValueTuple can not be null."); - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 6) - { - throw new MessagePackSerializationException("Invalid ValueTuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T4 item4 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T5 item5 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T6 item6 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new ValueTuple(item1, item2, item3, item4, item5, item6); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class ValueTupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, ValueTuple value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(7); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item4, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item5, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item6, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item7, options); - } - - public ValueTuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new MessagePackSerializationException("Data is Nil, ValueTuple can not be null."); - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 7) - { - throw new MessagePackSerializationException("Invalid ValueTuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T4 item4 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T5 item5 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T6 item6 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T7 item7 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new ValueTuple(item1, item2, item3, item4, item5, item6, item7); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class ValueTupleFormatter : IMessagePackFormatter> - where TRest : struct - { - public void Serialize(ref MessagePackWriter writer, ValueTuple value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(8); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item4, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item5, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item6, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item7, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Rest, options); - } - - public ValueTuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new MessagePackSerializationException("Data is Nil, ValueTuple can not be null."); - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 8) - { - throw new MessagePackSerializationException("Invalid ValueTuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T4 item4 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T5 item5 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T6 item6 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T7 item7 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - TRest item8 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new ValueTuple(item1, item2, item3, item4, item5, item6, item7, item8); - } - finally - { - reader.Depth--; - } - } - } - } -} diff --git a/Assets/Plugins/MessagePack/T4/ValueTupleFormatter.cs.meta b/Assets/Plugins/MessagePack/T4/ValueTupleFormatter.cs.meta deleted file mode 100644 index eb86b6bd3..000000000 --- a/Assets/Plugins/MessagePack/T4/ValueTupleFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 7dd3287be759a5f388a0a1f53b283b7d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/ThisLibraryExtensionTypeCodes.cs b/Assets/Plugins/MessagePack/ThisLibraryExtensionTypeCodes.cs deleted file mode 100644 index a9620bdc2..000000000 --- a/Assets/Plugins/MessagePack/ThisLibraryExtensionTypeCodes.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -namespace MessagePack -{ - /// - /// The extension type codes that this library defines for just this library. - /// - internal static class ThisLibraryExtensionTypeCodes - { - /// - /// For Unity's UnsafeBlitFormatter. - /// - internal const sbyte UnityVector2 = 30; - - /// - /// For Unity's UnsafeBlitFormatter. - /// - internal const sbyte UnityVector3 = 31; - - /// - /// For Unity's UnsafeBlitFormatter. - /// - internal const sbyte UnityVector4 = 32; - - /// - /// For Unity's UnsafeBlitFormatter. - /// - internal const sbyte UnityQuaternion = 33; - - /// - /// For Unity's UnsafeBlitFormatter. - /// - internal const sbyte UnityColor = 34; - - /// - /// For Unity's UnsafeBlitFormatter. - /// - internal const sbyte UnityBounds = 35; - - /// - /// For Unity's UnsafeBlitFormatter. - /// - internal const sbyte UnityRect = 36; - - /// - /// For Unity's UnsafeBlitFormatter. - /// - internal const sbyte UnityInt = 37; - - /// - /// For Unity's UnsafeBlitFormatter. - /// - internal const sbyte UnityFloat = 38; - - /// - /// For Unity's UnsafeBlitFormatter. - /// - internal const sbyte UnityDouble = 39; - - /// - /// The LZ4 array block compression extension. - /// - internal const sbyte Lz4BlockArray = 98; - - /// - /// The LZ4 single block compression extension. - /// - internal const sbyte Lz4Block = 99; - - /// - /// For the . - /// - internal const sbyte TypelessFormatter = 100; - } -} diff --git a/Assets/Plugins/MessagePack/ThisLibraryExtensionTypeCodes.cs.meta b/Assets/Plugins/MessagePack/ThisLibraryExtensionTypeCodes.cs.meta deleted file mode 100644 index b1f008edb..000000000 --- a/Assets/Plugins/MessagePack/ThisLibraryExtensionTypeCodes.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 7117971732be36a9da8f6a510364b4e5 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Unity.meta b/Assets/Plugins/MessagePack/Unity.meta deleted file mode 100644 index 277cc7122..000000000 --- a/Assets/Plugins/MessagePack/Unity.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: a4ac8e04487a20a4f8cb5b66eee5524c -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Unity/Extension.meta b/Assets/Plugins/MessagePack/Unity/Extension.meta deleted file mode 100644 index 6ef30848d..000000000 --- a/Assets/Plugins/MessagePack/Unity/Extension.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: da809bc2e70ea85429f483b800355d89 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Unity/Extension/UnityBlitResolver.cs b/Assets/Plugins/MessagePack/Unity/Extension/UnityBlitResolver.cs deleted file mode 100644 index f846da838..000000000 --- a/Assets/Plugins/MessagePack/Unity/Extension/UnityBlitResolver.cs +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using MessagePack.Formatters; -using UnityEngine; - -namespace MessagePack.Unity.Extension -{ - /// - /// Special Resolver for Vector2[], Vector3[], Vector4[], Quaternion[], Color[], Bounds[], Rect[]. - /// - public class UnityBlitResolver : IFormatterResolver - { - public static readonly UnityBlitResolver Instance = new UnityBlitResolver(); - - private UnityBlitResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - Formatter = (IMessagePackFormatter)UnityBlitResolverGetFormatterHelper.GetFormatter(typeof(T)); - } - } - } - - /// - /// Special Resolver for Vector2[], Vector3[], Vector4[], Quaternion[], Color[], Bounds[], Rect[] + int[], float[], double[]. - /// - public class UnityBlitWithPrimitiveArrayResolver : IFormatterResolver - { - public static readonly UnityBlitWithPrimitiveArrayResolver Instance = new UnityBlitWithPrimitiveArrayResolver(); - - private UnityBlitWithPrimitiveArrayResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - internal static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - Formatter = (IMessagePackFormatter)UnityBlitWithPrimitiveResolverGetFormatterHelper.GetFormatter(typeof(T)); - if (Formatter == null) - { - Formatter = UnityBlitResolver.Instance.GetFormatter(); - } - } - } - } - - internal static class UnityBlitResolverGetFormatterHelper - { - private static readonly Dictionary FormatterMap = new Dictionary() - { - { typeof(Vector2[]), typeof(Vector2ArrayBlitFormatter) }, - { typeof(Vector3[]), typeof(Vector3ArrayBlitFormatter) }, - { typeof(Vector4[]), typeof(Vector4ArrayBlitFormatter) }, - { typeof(Quaternion[]), typeof(QuaternionArrayBlitFormatter) }, - { typeof(Color[]), typeof(ColorArrayBlitFormatter) }, - { typeof(Bounds[]), typeof(BoundsArrayBlitFormatter) }, - { typeof(Rect[]), typeof(RectArrayBlitFormatter) }, - }; - - internal static object GetFormatter(Type t) - { - Type formatterType; - if (FormatterMap.TryGetValue(t, out formatterType)) - { - return Activator.CreateInstance(formatterType); - } - - return null; - } - } - - internal static class UnityBlitWithPrimitiveResolverGetFormatterHelper - { - private static readonly Dictionary FormatterMap = new Dictionary() - { - { typeof(int[]), typeof(IntArrayBlitFormatter) }, - { typeof(float[]), typeof(FloatArrayBlitFormatter) }, - { typeof(double[]), typeof(DoubleArrayBlitFormatter) }, - }; - - internal static object GetFormatter(Type t) - { - Type formatterType; - if (FormatterMap.TryGetValue(t, out formatterType)) - { - return Activator.CreateInstance(formatterType); - } - - return null; - } - } -} diff --git a/Assets/Plugins/MessagePack/Unity/Extension/UnityBlitResolver.cs.meta b/Assets/Plugins/MessagePack/Unity/Extension/UnityBlitResolver.cs.meta deleted file mode 100644 index 0f641f434..000000000 --- a/Assets/Plugins/MessagePack/Unity/Extension/UnityBlitResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ef834ed39aa3bf457860be80e97a5d9c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Unity/Extension/UnsafeBlitFormatter.cs b/Assets/Plugins/MessagePack/Unity/Extension/UnsafeBlitFormatter.cs deleted file mode 100644 index 3682b032d..000000000 --- a/Assets/Plugins/MessagePack/Unity/Extension/UnsafeBlitFormatter.cs +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Text; -using MessagePack.Formatters; -using UnityEngine; - -#pragma warning disable SA1402 // multiple types in a file -#pragma warning disable SA1649 // file name matches type name - -namespace MessagePack.Unity.Extension -{ - // use ext instead of ArrayFormatter to extremely boost up performance. - // Layout: [extHeader, byteSize(integer), isLittleEndian(bool), bytes()] - // Used Ext:30~36 - public abstract class UnsafeBlitFormatterBase : IMessagePackFormatter - where T : struct - { - protected abstract sbyte TypeCode { get; } - - protected void CopyDeserializeUnsafe(ReadOnlySpan src, Span dest) => src.CopyTo(MemoryMarshal.Cast(dest)); - - public void Serialize(ref MessagePackWriter writer, T[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - var byteLen = value.Length * Marshal.SizeOf(); - - writer.WriteExtensionFormatHeader(new ExtensionHeader(this.TypeCode, byteLen)); - writer.Write(byteLen); // write original header(not array header) - writer.Write(BitConverter.IsLittleEndian); - writer.WriteRaw(MemoryMarshal.Cast(value)); - } - - public T[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - ExtensionHeader header = reader.ReadExtensionFormatHeader(); - if (header.TypeCode != this.TypeCode) - { - throw new InvalidOperationException("Invalid typeCode."); - } - - var byteLength = reader.ReadInt32(); - var isLittleEndian = reader.ReadBoolean(); - - // Allocate a T[] that we will return. We'll then cast the T[] as byte[] so we can copy the byte sequence directly into it. - var result = new T[byteLength / Marshal.SizeOf()]; - Span resultAsBytes = MemoryMarshal.Cast(result); - reader.ReadRaw(byteLength).CopyTo(resultAsBytes); - - // Reverse the byte order if necessary. - if (isLittleEndian != BitConverter.IsLittleEndian) - { - for (int i = 0, j = resultAsBytes.Length - 1; i < j; i++, j--) - { - byte tmp = resultAsBytes[i]; - resultAsBytes[i] = resultAsBytes[j]; - resultAsBytes[j] = tmp; - } - } - - return result; - } - } - - public class Vector2ArrayBlitFormatter : UnsafeBlitFormatterBase - { - protected override sbyte TypeCode - { - get - { - return ThisLibraryExtensionTypeCodes.UnityVector2; - } - } - } - - public class Vector3ArrayBlitFormatter : UnsafeBlitFormatterBase - { - protected override sbyte TypeCode - { - get - { - return ThisLibraryExtensionTypeCodes.UnityVector3; - } - } - } - - public class Vector4ArrayBlitFormatter : UnsafeBlitFormatterBase - { - protected override sbyte TypeCode - { - get - { - return ThisLibraryExtensionTypeCodes.UnityVector4; - } - } - } - - public class QuaternionArrayBlitFormatter : UnsafeBlitFormatterBase - { - protected override sbyte TypeCode - { - get - { - return ThisLibraryExtensionTypeCodes.UnityQuaternion; - } - } - } - - public class ColorArrayBlitFormatter : UnsafeBlitFormatterBase - { - protected override sbyte TypeCode - { - get - { - return ThisLibraryExtensionTypeCodes.UnityColor; - } - } - } - - public class BoundsArrayBlitFormatter : UnsafeBlitFormatterBase - { - protected override sbyte TypeCode - { - get - { - return ThisLibraryExtensionTypeCodes.UnityBounds; - } - } - } - - public class RectArrayBlitFormatter : UnsafeBlitFormatterBase - { - protected override sbyte TypeCode - { - get - { - return ThisLibraryExtensionTypeCodes.UnityRect; - } - } - } - - public class IntArrayBlitFormatter : UnsafeBlitFormatterBase - { - protected override sbyte TypeCode - { - get { return ThisLibraryExtensionTypeCodes.UnityInt; } - } - } - - public class FloatArrayBlitFormatter : UnsafeBlitFormatterBase - { - protected override sbyte TypeCode - { - get { return ThisLibraryExtensionTypeCodes.UnityFloat; } - } - } - - public class DoubleArrayBlitFormatter : UnsafeBlitFormatterBase - { - protected override sbyte TypeCode - { - get { return ThisLibraryExtensionTypeCodes.UnityDouble; } - } - } -} diff --git a/Assets/Plugins/MessagePack/Unity/Extension/UnsafeBlitFormatter.cs.meta b/Assets/Plugins/MessagePack/Unity/Extension/UnsafeBlitFormatter.cs.meta deleted file mode 100644 index 6265e2a99..000000000 --- a/Assets/Plugins/MessagePack/Unity/Extension/UnsafeBlitFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2955ae5d4f31948548df2c805124f4c6 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Unity/Formatters.cs b/Assets/Plugins/MessagePack/Unity/Formatters.cs deleted file mode 100644 index e3b0876fe..000000000 --- a/Assets/Plugins/MessagePack/Unity/Formatters.cs +++ /dev/null @@ -1,1135 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using MessagePack; -using MessagePack.Formatters; - -#pragma warning disable SA1312 // variable naming -#pragma warning disable SA1402 // one type per file -#pragma warning disable SA1649 // file name matches type name - -namespace MessagePack.Unity -{ - public sealed class Vector2Formatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Vector2 value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(2); - writer.Write(value.x); - writer.Write(value.y); - } - - public global::UnityEngine.Vector2 Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var x = default(float); - var y = default(float); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - x = reader.ReadSingle(); - break; - case 1: - y = reader.ReadSingle(); - break; - default: - reader.Skip(); - break; - } - } - - var result = new global::UnityEngine.Vector2(x, y); - return result; - } - } - - public sealed class Vector3Formatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Vector3 value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(3); - writer.Write(value.x); - writer.Write(value.y); - writer.Write(value.z); - } - - public global::UnityEngine.Vector3 Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var x = default(float); - var y = default(float); - var z = default(float); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - x = reader.ReadSingle(); - break; - case 1: - y = reader.ReadSingle(); - break; - case 2: - z = reader.ReadSingle(); - break; - default: - reader.Skip(); - break; - } - } - - var result = new global::UnityEngine.Vector3(x, y, z); - return result; - } - } - - public sealed class Vector4Formatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Vector4 value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(4); - writer.Write(value.x); - writer.Write(value.y); - writer.Write(value.z); - writer.Write(value.w); - } - - public global::UnityEngine.Vector4 Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var x = default(float); - var y = default(float); - var z = default(float); - var w = default(float); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - x = reader.ReadSingle(); - break; - case 1: - y = reader.ReadSingle(); - break; - case 2: - z = reader.ReadSingle(); - break; - case 3: - w = reader.ReadSingle(); - break; - default: - reader.Skip(); - break; - } - } - - var result = new global::UnityEngine.Vector4(x, y, z, w); - return result; - } - } - - public sealed class QuaternionFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Quaternion value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(4); - writer.Write(value.x); - writer.Write(value.y); - writer.Write(value.z); - writer.Write(value.w); - } - - public global::UnityEngine.Quaternion Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var x = default(float); - var y = default(float); - var z = default(float); - var w = default(float); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - x = reader.ReadSingle(); - break; - case 1: - y = reader.ReadSingle(); - break; - case 2: - z = reader.ReadSingle(); - break; - case 3: - w = reader.ReadSingle(); - break; - default: - reader.Skip(); - break; - } - } - - var result = new global::UnityEngine.Quaternion(x, y, z, w); - return result; - } - } - - public sealed class ColorFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Color value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(4); - writer.Write(value.r); - writer.Write(value.g); - writer.Write(value.b); - writer.Write(value.a); - } - - public global::UnityEngine.Color Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var r = default(float); - var g = default(float); - var b = default(float); - var a = default(float); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - r = reader.ReadSingle(); - break; - case 1: - g = reader.ReadSingle(); - break; - case 2: - b = reader.ReadSingle(); - break; - case 3: - a = reader.ReadSingle(); - break; - default: - reader.Skip(); - break; - } - } - - var result = new global::UnityEngine.Color(r, g, b, a); - return result; - } - } - - public sealed class BoundsFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Bounds value, global::MessagePack.MessagePackSerializerOptions options) - { - IFormatterResolver resolver = options.Resolver; - writer.WriteArrayHeader(2); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.center, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.size, options); - } - - public global::UnityEngine.Bounds Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - IFormatterResolver resolver = options.Resolver; - var length = reader.ReadArrayHeader(); - var center = default(global::UnityEngine.Vector3); - var size = default(global::UnityEngine.Vector3); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - center = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 1: - size = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - default: - reader.Skip(); - break; - } - } - - var result = new global::UnityEngine.Bounds(center, size); - return result; - } - } - - public sealed class RectFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Rect value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(4); - writer.Write(value.x); - writer.Write(value.y); - writer.Write(value.width); - writer.Write(value.height); - } - - public global::UnityEngine.Rect Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var x = default(float); - var y = default(float); - var width = default(float); - var height = default(float); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - x = reader.ReadSingle(); - break; - case 1: - y = reader.ReadSingle(); - break; - case 2: - width = reader.ReadSingle(); - break; - case 3: - height = reader.ReadSingle(); - break; - default: - reader.Skip(); - break; - } - } - - var result = new global::UnityEngine.Rect(x, y, width, height); - return result; - } - } - - // additional - public sealed class WrapModeFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.WrapMode value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.Write((int)value); - } - - public global::UnityEngine.WrapMode Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - return (global::UnityEngine.WrapMode)reader.ReadInt32(); - } - } - - public sealed class GradientModeFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.GradientMode value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.Write((int)value); - } - - public global::UnityEngine.GradientMode Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - return (global::UnityEngine.GradientMode)reader.ReadInt32(); - } - } - - public sealed class KeyframeFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Keyframe value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(4); - writer.Write(value.time); - writer.Write(value.value); - writer.Write(value.inTangent); - writer.Write(value.outTangent); - } - - public global::UnityEngine.Keyframe Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var __time__ = default(float); - var __value__ = default(float); - var __inTangent__ = default(float); - var __outTangent__ = default(float); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __time__ = reader.ReadSingle(); - break; - case 1: - __value__ = reader.ReadSingle(); - break; - case 2: - __inTangent__ = reader.ReadSingle(); - break; - case 3: - __outTangent__ = reader.ReadSingle(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.Keyframe(__time__, __value__, __inTangent__, __outTangent__); - ____result.time = __time__; - ____result.value = __value__; - ____result.inTangent = __inTangent__; - ____result.outTangent = __outTangent__; - return ____result; - } - } - - public sealed class AnimationCurveFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.AnimationCurve value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver resolver = options.Resolver; - writer.WriteArrayHeader(3); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.keys, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.postWrapMode, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.preWrapMode, options); - } - - public global::UnityEngine.AnimationCurve Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - return null; - } - - IFormatterResolver resolver = options.Resolver; - var length = reader.ReadArrayHeader(); - var __keys__ = default(global::UnityEngine.Keyframe[]); - var __postWrapMode__ = default(global::UnityEngine.WrapMode); - var __preWrapMode__ = default(global::UnityEngine.WrapMode); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __keys__ = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 1: - __postWrapMode__ = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 2: - __preWrapMode__ = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.AnimationCurve(); - ____result.keys = __keys__; - ____result.postWrapMode = __postWrapMode__; - ____result.preWrapMode = __preWrapMode__; - return ____result; - } - } - - public sealed class Matrix4x4Formatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Matrix4x4 value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(16); - writer.Write(value.m00); - writer.Write(value.m10); - writer.Write(value.m20); - writer.Write(value.m30); - writer.Write(value.m01); - writer.Write(value.m11); - writer.Write(value.m21); - writer.Write(value.m31); - writer.Write(value.m02); - writer.Write(value.m12); - writer.Write(value.m22); - writer.Write(value.m32); - writer.Write(value.m03); - writer.Write(value.m13); - writer.Write(value.m23); - writer.Write(value.m33); - } - - public global::UnityEngine.Matrix4x4 Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var __m00__ = default(float); - var __m10__ = default(float); - var __m20__ = default(float); - var __m30__ = default(float); - var __m01__ = default(float); - var __m11__ = default(float); - var __m21__ = default(float); - var __m31__ = default(float); - var __m02__ = default(float); - var __m12__ = default(float); - var __m22__ = default(float); - var __m32__ = default(float); - var __m03__ = default(float); - var __m13__ = default(float); - var __m23__ = default(float); - var __m33__ = default(float); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __m00__ = reader.ReadSingle(); - break; - case 1: - __m10__ = reader.ReadSingle(); - break; - case 2: - __m20__ = reader.ReadSingle(); - break; - case 3: - __m30__ = reader.ReadSingle(); - break; - case 4: - __m01__ = reader.ReadSingle(); - break; - case 5: - __m11__ = reader.ReadSingle(); - break; - case 6: - __m21__ = reader.ReadSingle(); - break; - case 7: - __m31__ = reader.ReadSingle(); - break; - case 8: - __m02__ = reader.ReadSingle(); - break; - case 9: - __m12__ = reader.ReadSingle(); - break; - case 10: - __m22__ = reader.ReadSingle(); - break; - case 11: - __m32__ = reader.ReadSingle(); - break; - case 12: - __m03__ = reader.ReadSingle(); - break; - case 13: - __m13__ = reader.ReadSingle(); - break; - case 14: - __m23__ = reader.ReadSingle(); - break; - case 15: - __m33__ = reader.ReadSingle(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = default(global::UnityEngine.Matrix4x4); - ____result.m00 = __m00__; - ____result.m10 = __m10__; - ____result.m20 = __m20__; - ____result.m30 = __m30__; - ____result.m01 = __m01__; - ____result.m11 = __m11__; - ____result.m21 = __m21__; - ____result.m31 = __m31__; - ____result.m02 = __m02__; - ____result.m12 = __m12__; - ____result.m22 = __m22__; - ____result.m32 = __m32__; - ____result.m03 = __m03__; - ____result.m13 = __m13__; - ____result.m23 = __m23__; - ____result.m33 = __m33__; - return ____result; - } - } - - public sealed class GradientColorKeyFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.GradientColorKey value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(2); - options.Resolver.GetFormatterWithVerify().Serialize(ref writer, value.color, options); - writer.Write(value.time); - } - - public global::UnityEngine.GradientColorKey Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var __color__ = default(global::UnityEngine.Color); - var __time__ = default(float); - IFormatterResolver resolver = options.Resolver; - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __color__ = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 1: - __time__ = reader.ReadSingle(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.GradientColorKey(__color__, __time__); - ____result.color = __color__; - ____result.time = __time__; - return ____result; - } - } - - public sealed class GradientAlphaKeyFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.GradientAlphaKey value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(2); - writer.Write(value.alpha); - writer.Write(value.time); - } - - public global::UnityEngine.GradientAlphaKey Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var __alpha__ = default(float); - var __time__ = default(float); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __alpha__ = reader.ReadSingle(); - break; - case 1: - __time__ = reader.ReadSingle(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.GradientAlphaKey(__alpha__, __time__); - ____result.alpha = __alpha__; - ____result.time = __time__; - return ____result; - } - } - - public sealed class GradientFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Gradient value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver resolver = options.Resolver; - writer.WriteArrayHeader(3); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.colorKeys, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.alphaKeys, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.mode, options); - } - - public global::UnityEngine.Gradient Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - return null; - } - - IFormatterResolver resolver = options.Resolver; - var length = reader.ReadArrayHeader(); - var __colorKeys__ = default(global::UnityEngine.GradientColorKey[]); - var __alphaKeys__ = default(global::UnityEngine.GradientAlphaKey[]); - var __mode__ = default(global::UnityEngine.GradientMode); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __colorKeys__ = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 1: - __alphaKeys__ = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 2: - __mode__ = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.Gradient(); - ____result.colorKeys = __colorKeys__; - ____result.alphaKeys = __alphaKeys__; - ____result.mode = __mode__; - return ____result; - } - } - - public sealed class Color32Formatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Color32 value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(4); - writer.Write(value.r); - writer.Write(value.g); - writer.Write(value.b); - writer.Write(value.a); - } - - public global::UnityEngine.Color32 Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var __r__ = default(byte); - var __g__ = default(byte); - var __b__ = default(byte); - var __a__ = default(byte); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __r__ = reader.ReadByte(); - break; - case 1: - __g__ = reader.ReadByte(); - break; - case 2: - __b__ = reader.ReadByte(); - break; - case 3: - __a__ = reader.ReadByte(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.Color32(__r__, __g__, __b__, __a__); - ____result.r = __r__; - ____result.g = __g__; - ____result.b = __b__; - ____result.a = __a__; - return ____result; - } - } - - public sealed class RectOffsetFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.RectOffset value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - writer.WriteArrayHeader(4); - writer.Write(value.left); - writer.Write(value.right); - writer.Write(value.top); - writer.Write(value.bottom); - } - - public global::UnityEngine.RectOffset Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - return null; - } - - var length = reader.ReadArrayHeader(); - var __left__ = default(int); - var __right__ = default(int); - var __top__ = default(int); - var __bottom__ = default(int); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __left__ = reader.ReadInt32(); - break; - case 1: - __right__ = reader.ReadInt32(); - break; - case 2: - __top__ = reader.ReadInt32(); - break; - case 3: - __bottom__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.RectOffset(); - ____result.left = __left__; - ____result.right = __right__; - ____result.top = __top__; - ____result.bottom = __bottom__; - return ____result; - } - } - - public sealed class LayerMaskFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.LayerMask value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(1); - writer.Write(value.value); - } - - public global::UnityEngine.LayerMask Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var __value__ = default(int); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __value__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = default(global::UnityEngine.LayerMask); - ____result.value = __value__; - return ____result; - } - } -#if UNITY_2017_2_OR_NEWER - public sealed class Vector2IntFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Vector2Int value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(2); - writer.WriteInt32(value.x); - writer.WriteInt32(value.y); - } - public global::UnityEngine.Vector2Int Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - var length = reader.ReadArrayHeader(); - var __x__ = default(int); - var __y__ = default(int); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __x__ = reader.ReadInt32(); - break; - case 1: - __y__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.Vector2Int(__x__, __y__); - ____result.x = __x__; - ____result.y = __y__; - return ____result; - } - } - - public sealed class Vector3IntFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Vector3Int value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(3); - writer.WriteInt32(value.x); - writer.WriteInt32(value.y); - writer.WriteInt32(value.z); - } - public global::UnityEngine.Vector3Int Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - var length = reader.ReadArrayHeader(); - var __x__ = default(int); - var __y__ = default(int); - var __z__ = default(int); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __x__ = reader.ReadInt32(); - break; - case 1: - __y__ = reader.ReadInt32(); - break; - case 2: - __z__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.Vector3Int(__x__, __y__, __z__); - ____result.x = __x__; - ____result.y = __y__; - ____result.z = __z__; - return ____result; - } - } - - public sealed class RangeIntFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.RangeInt value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(2); - writer.WriteInt32(value.start); - writer.WriteInt32(value.length); - } - public global::UnityEngine.RangeInt Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - var length = reader.ReadArrayHeader(); - var __start__ = default(int); - var __length__ = default(int); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __start__ = reader.ReadInt32(); - break; - case 1: - __length__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.RangeInt(__start__, __length__); - ____result.start = __start__; - ____result.length = __length__; - return ____result; - } - } - - public sealed class RectIntFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.RectInt value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(4); - writer.WriteInt32(value.x); - writer.WriteInt32(value.y); - writer.WriteInt32(value.width); - writer.WriteInt32(value.height); - } - public global::UnityEngine.RectInt Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - var length = reader.ReadArrayHeader(); - var __x__ = default(int); - var __y__ = default(int); - var __width__ = default(int); - var __height__ = default(int); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __x__ = reader.ReadInt32(); - break; - case 1: - __y__ = reader.ReadInt32(); - break; - case 2: - __width__ = reader.ReadInt32(); - break; - case 3: - __height__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.RectInt(__x__, __y__, __width__, __height__); - ____result.x = __x__; - ____result.y = __y__; - ____result.width = __width__; - ____result.height = __height__; - return ____result; - } - } - - public sealed class BoundsIntFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.BoundsInt value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(2); - options.Resolver.GetFormatterWithVerify().Serialize(ref writer, value.position, options); - options.Resolver.GetFormatterWithVerify().Serialize(ref writer, value.size, options); - } - public global::UnityEngine.BoundsInt Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - var length = reader.ReadArrayHeader(); - var __position__ = default(global::UnityEngine.Vector3Int); - var __size__ = default(global::UnityEngine.Vector3Int); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __position__ = options.Resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 1: - __size__ = options.Resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.BoundsInt(__position__, __size__); - ____result.position = __position__; - ____result.size = __size__; - return ____result; - } - } -#endif -} diff --git a/Assets/Plugins/MessagePack/Unity/Formatters.cs.meta b/Assets/Plugins/MessagePack/Unity/Formatters.cs.meta deleted file mode 100644 index 84c94b20d..000000000 --- a/Assets/Plugins/MessagePack/Unity/Formatters.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bccce8bedf4b84bfd8a5b74edf3f232f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Unity/MessagePackWindow.cs b/Assets/Plugins/MessagePack/Unity/MessagePackWindow.cs deleted file mode 100644 index 99a58c1b3..000000000 --- a/Assets/Plugins/MessagePack/Unity/MessagePackWindow.cs +++ /dev/null @@ -1,314 +0,0 @@ -#if UNITY_EDITOR - -using System; -using System.Diagnostics; -using System.Text; -using System.Threading.Tasks; -using UnityEditor; -using UnityEngine; - -namespace MessagePack.Unity.Editor -{ - internal class MessagePackWindow : EditorWindow - { - static MessagePackWindow window; - - bool processInitialized; - - bool isDotnetInstalled; - string dotnetVersion; - - bool isInstalledMpc; - bool installingMpc; - bool invokingMpc; - - MpcArgument mpcArgument; - - [MenuItem("Window/MessagePack/CodeGenerator")] - public static void OpenWindow() - { - if (window != null) - { - window.Close(); - } - - // will called OnEnable(singleton instance will be set). - GetWindow("MessagePack CodeGen").Show(); - } - - async void OnEnable() - { - window = this; // set singleton. - try - { - var dotnet = await ProcessHelper.FindDotnetAsync(); - isDotnetInstalled = dotnet.found; - dotnetVersion = dotnet.version; - - if (isDotnetInstalled) - { - isInstalledMpc = await ProcessHelper.IsInstalledMpc(); - } - } - finally - { - mpcArgument = MpcArgument.Restore(); - processInitialized = true; - } - } - - async void OnGUI() - { - if (!processInitialized) - { - GUILayout.Label("Check .NET Core SDK/CodeGen install status."); - return; - } - if (mpcArgument == null) - { - return; - } - - if (!isDotnetInstalled) - { - GUILayout.Label(".NET Core SDK not found."); - GUILayout.Label("MessagePack CodeGen requires .NET Core Runtime."); - if (GUILayout.Button("Open .NET Core install page.")) - { - Application.OpenURL("https://dotnet.microsoft.com/download"); - } - return; - } - - if (!isInstalledMpc) - { - GUILayout.Label("MessagePack CodeGen does not instaled."); - EditorGUI.BeginDisabledGroup(installingMpc); - - if (GUILayout.Button("Install MessagePack CodeGen.")) - { - installingMpc = true; - try - { - var log = await ProcessHelper.InstallMpc(); - if (!string.IsNullOrWhiteSpace(log)) - { - UnityEngine.Debug.Log(log); - } - if (log != null && log.Contains("error")) - { - isInstalledMpc = false; - } - else - { - isInstalledMpc = true; - } - } - finally - { - installingMpc = false; - } - return; - } - - EditorGUI.EndDisabledGroup(); - return; - } - - EditorGUILayout.LabelField("-i input path(csproj or directory):"); - TextField(mpcArgument, x => x.Input, (x, y) => x.Input = y); - - EditorGUILayout.LabelField("-o output filepath(.cs) or directory(multiple):"); - TextField(mpcArgument, x => x.Output, (x, y) => x.Output = y); - - EditorGUILayout.LabelField("-m(optional) use map mode:"); - var newToggle = EditorGUILayout.Toggle(mpcArgument.UseMapMode); - if (mpcArgument.UseMapMode != newToggle) - { - mpcArgument.UseMapMode = newToggle; - mpcArgument.Save(); - } - - EditorGUILayout.LabelField("-c(optional) conditional compiler symbols(split with ','):"); - TextField(mpcArgument, x => x.ConditionalSymbol, (x, y) => x.ConditionalSymbol = y); - - EditorGUILayout.LabelField("-r(optional) generated resolver name:"); - TextField(mpcArgument, x => x.ResolverName, (x, y) => x.ResolverName = y); - - EditorGUILayout.LabelField("-n(optional) namespace root name:"); - TextField(mpcArgument, x => x.Namespace, (x, y) => x.Namespace = y); - - EditorGUILayout.LabelField("-ms(optional) Generate #if-- files by symbols, split with ','"); - TextField(mpcArgument, x => x.MultipleIfDirectiveOutputSymbols, (x, y) => x.MultipleIfDirectiveOutputSymbols = y); - - EditorGUI.BeginDisabledGroup(invokingMpc); - if (GUILayout.Button("Generate")) - { - var commnadLineArguments = mpcArgument.ToString(); - UnityEngine.Debug.Log("Generate MessagePack Files, command:" + commnadLineArguments); - - invokingMpc = true; - try - { - var log = await ProcessHelper.InvokeProcessStartAsync("dotnet", "mpc " + commnadLineArguments); - UnityEngine.Debug.Log(log); - } - finally - { - invokingMpc = false; - } - } - EditorGUI.EndDisabledGroup(); - } - - void TextField(MpcArgument args, Func getter, Action setter) - { - var current = getter(args); - var newValue = EditorGUILayout.TextField(current); - if (newValue != current) - { - setter(args, newValue); - args.Save(); - } - } - } - - internal class MpcArgument - { - public string Input; - public string Output; - public string ConditionalSymbol; - public string ResolverName; - public string Namespace; - public bool UseMapMode; - public string MultipleIfDirectiveOutputSymbols; - - static string Key => "MessagePackCodeGen." + Application.productName; - - public static MpcArgument Restore() - { - if (EditorPrefs.HasKey(Key)) - { - var json = EditorPrefs.GetString(Key); - return JsonUtility.FromJson(json); - } - else - { - return new MpcArgument(); - } - } - - public void Save() - { - var json = JsonUtility.ToJson(this); - EditorPrefs.SetString(Key, json); - } - - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("-i "); sb.Append(Input); - sb.Append(" -o "); sb.Append(Output); - if (!string.IsNullOrWhiteSpace(ConditionalSymbol)) - { - sb.Append(" -c "); sb.Append(ConditionalSymbol); - } - if (!string.IsNullOrWhiteSpace(ResolverName)) - { - sb.Append(" -r "); sb.Append(ResolverName); - } - if (UseMapMode) - { - sb.Append(" -m"); - } - if (!string.IsNullOrWhiteSpace(Namespace)) - { - sb.Append(" -n "); sb.Append(Namespace); - } - if (!string.IsNullOrWhiteSpace(MultipleIfDirectiveOutputSymbols)) - { - sb.Append(" -ms "); sb.Append(MultipleIfDirectiveOutputSymbols); - } - - return sb.ToString(); - } - } - - internal static class ProcessHelper - { - const string InstallName = "messagepack.generator"; - - public static async Task IsInstalledMpc() - { - var list = await InvokeProcessStartAsync("dotnet", "tool list -g"); - if (list.Contains(InstallName)) - { - return true; - } - else - { - return false; - } - } - - public static async Task InstallMpc() - { - return await InvokeProcessStartAsync("dotnet", "tool install --global " + InstallName); - } - - public static async Task<(bool found, string version)> FindDotnetAsync() - { - try - { - var version = await InvokeProcessStartAsync("dotnet", "--version"); - return (true, version); - } - catch - { - return (false, null); - } - } - - public static Task InvokeProcessStartAsync(string fileName, string arguments) - { - var psi = new ProcessStartInfo() - { - CreateNoWindow = true, - WindowStyle = ProcessWindowStyle.Hidden, - StandardOutputEncoding = Encoding.UTF8, - StandardErrorEncoding = Encoding.UTF8, - RedirectStandardOutput = true, - RedirectStandardError = true, - UseShellExecute = false, - FileName = fileName, - Arguments = arguments, - WorkingDirectory = Application.dataPath - }; - - Process p; - try - { - p = Process.Start(psi); - } - catch (Exception ex) - { - return Task.FromException(ex); - } - - var tcs = new TaskCompletionSource(); - p.EnableRaisingEvents = true; - p.Exited += (object sender, System.EventArgs e) => - { - var data = p.StandardOutput.ReadToEnd(); - p.Dispose(); - p = null; - - tcs.TrySetResult(data); - }; - - return tcs.Task; - } - } -} - -#endif diff --git a/Assets/Plugins/MessagePack/Unity/MessagePackWindow.cs.meta b/Assets/Plugins/MessagePack/Unity/MessagePackWindow.cs.meta deleted file mode 100644 index 7015fd2d2..000000000 --- a/Assets/Plugins/MessagePack/Unity/MessagePackWindow.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4e1974f6daf2611d0b8a78fe6230f4a8 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Unity/UnityResolver.cs b/Assets/Plugins/MessagePack/Unity/UnityResolver.cs deleted file mode 100644 index 033e513be..000000000 --- a/Assets/Plugins/MessagePack/Unity/UnityResolver.cs +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using MessagePack.Formatters; -using UnityEngine; - -namespace MessagePack.Unity -{ - public class UnityResolver : IFormatterResolver - { - public static readonly UnityResolver Instance = new UnityResolver(); - - private UnityResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - Formatter = (IMessagePackFormatter)UnityResolveryResolverGetFormatterHelper.GetFormatter(typeof(T)); - } - } - } - - internal static class UnityResolveryResolverGetFormatterHelper - { - private static readonly Dictionary FormatterMap = new Dictionary() - { - // standard - { typeof(Vector2), new Vector2Formatter() }, - { typeof(Vector3), new Vector3Formatter() }, - { typeof(Vector4), new Vector4Formatter() }, - { typeof(Quaternion), new QuaternionFormatter() }, - { typeof(Color), new ColorFormatter() }, - { typeof(Bounds), new BoundsFormatter() }, - { typeof(Rect), new RectFormatter() }, - { typeof(Vector2?), new StaticNullableFormatter(new Vector2Formatter()) }, - { typeof(Vector3?), new StaticNullableFormatter(new Vector3Formatter()) }, - { typeof(Vector4?), new StaticNullableFormatter(new Vector4Formatter()) }, - { typeof(Quaternion?), new StaticNullableFormatter(new QuaternionFormatter()) }, - { typeof(Color?), new StaticNullableFormatter(new ColorFormatter()) }, - { typeof(Bounds?), new StaticNullableFormatter(new BoundsFormatter()) }, - { typeof(Rect?), new StaticNullableFormatter(new RectFormatter()) }, - - // standard + array - { typeof(Vector2[]), new ArrayFormatter() }, - { typeof(Vector3[]), new ArrayFormatter() }, - { typeof(Vector4[]), new ArrayFormatter() }, - { typeof(Quaternion[]), new ArrayFormatter() }, - { typeof(Color[]), new ArrayFormatter() }, - { typeof(Bounds[]), new ArrayFormatter() }, - { typeof(Rect[]), new ArrayFormatter() }, - { typeof(Vector2?[]), new ArrayFormatter() }, - { typeof(Vector3?[]), new ArrayFormatter() }, - { typeof(Vector4?[]), new ArrayFormatter() }, - { typeof(Quaternion?[]), new ArrayFormatter() }, - { typeof(Color?[]), new ArrayFormatter() }, - { typeof(Bounds?[]), new ArrayFormatter() }, - { typeof(Rect?[]), new ArrayFormatter() }, - - // standard + list - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - - // new - { typeof(AnimationCurve), new AnimationCurveFormatter() }, - { typeof(RectOffset), new RectOffsetFormatter() }, - { typeof(Gradient), new GradientFormatter() }, - { typeof(WrapMode), new WrapModeFormatter() }, - { typeof(GradientMode), new GradientModeFormatter() }, - { typeof(Keyframe), new KeyframeFormatter() }, - { typeof(Matrix4x4), new Matrix4x4Formatter() }, - { typeof(GradientColorKey), new GradientColorKeyFormatter() }, - { typeof(GradientAlphaKey), new GradientAlphaKeyFormatter() }, - { typeof(Color32), new Color32Formatter() }, - { typeof(LayerMask), new LayerMaskFormatter() }, - { typeof(WrapMode?), new StaticNullableFormatter(new WrapModeFormatter()) }, - { typeof(GradientMode?), new StaticNullableFormatter(new GradientModeFormatter()) }, - { typeof(Keyframe?), new StaticNullableFormatter(new KeyframeFormatter()) }, - { typeof(Matrix4x4?), new StaticNullableFormatter(new Matrix4x4Formatter()) }, - { typeof(GradientColorKey?), new StaticNullableFormatter(new GradientColorKeyFormatter()) }, - { typeof(GradientAlphaKey?), new StaticNullableFormatter(new GradientAlphaKeyFormatter()) }, - { typeof(Color32?), new StaticNullableFormatter(new Color32Formatter()) }, - { typeof(LayerMask?), new StaticNullableFormatter(new LayerMaskFormatter()) }, - - // new + array - { typeof(AnimationCurve[]), new ArrayFormatter() }, - { typeof(RectOffset[]), new ArrayFormatter() }, - { typeof(Gradient[]), new ArrayFormatter() }, - { typeof(WrapMode[]), new ArrayFormatter() }, - { typeof(GradientMode[]), new ArrayFormatter() }, - { typeof(Keyframe[]), new ArrayFormatter() }, - { typeof(Matrix4x4[]), new ArrayFormatter() }, - { typeof(GradientColorKey[]), new ArrayFormatter() }, - { typeof(GradientAlphaKey[]), new ArrayFormatter() }, - { typeof(Color32[]), new ArrayFormatter() }, - { typeof(LayerMask[]), new ArrayFormatter() }, - { typeof(WrapMode?[]), new ArrayFormatter() }, - { typeof(GradientMode?[]), new ArrayFormatter() }, - { typeof(Keyframe?[]), new ArrayFormatter() }, - { typeof(Matrix4x4?[]), new ArrayFormatter() }, - { typeof(GradientColorKey?[]), new ArrayFormatter() }, - { typeof(GradientAlphaKey?[]), new ArrayFormatter() }, - { typeof(Color32?[]), new ArrayFormatter() }, - { typeof(LayerMask?[]), new ArrayFormatter() }, - - // new + list - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - - // unity 2017.2 -#if UNITY_2017_2_OR_NEWER - - {typeof(Vector2Int), new Vector2IntFormatter()}, - {typeof(Vector3Int), new Vector3IntFormatter()}, - {typeof(RangeInt), new RangeIntFormatter()}, - {typeof(RectInt), new RectIntFormatter()}, - {typeof(BoundsInt), new BoundsIntFormatter()}, - {typeof(Vector2Int?), new StaticNullableFormatter(new Vector2IntFormatter())}, - {typeof(Vector3Int?), new StaticNullableFormatter(new Vector3IntFormatter())}, - {typeof(RangeInt?), new StaticNullableFormatter(new RangeIntFormatter())}, - {typeof(RectInt?), new StaticNullableFormatter(new RectIntFormatter())}, - {typeof(BoundsInt?), new StaticNullableFormatter(new BoundsIntFormatter())}, - // unity 2017.2 + array - {typeof(Vector2Int[]), new ArrayFormatter()}, - {typeof(Vector3Int[]), new ArrayFormatter()}, - {typeof(RangeInt[]), new ArrayFormatter()}, - {typeof(RectInt[]), new ArrayFormatter()}, - {typeof(BoundsInt[]), new ArrayFormatter()}, - {typeof(Vector2Int?[]), new ArrayFormatter()}, - {typeof(Vector3Int?[]), new ArrayFormatter()}, - {typeof(RangeInt?[]), new ArrayFormatter()}, - {typeof(RectInt?[]), new ArrayFormatter()}, - {typeof(BoundsInt?[]), new ArrayFormatter()}, - // unity 2017.2 + list - {typeof(List), new ListFormatter()}, - {typeof(List), new ListFormatter()}, - {typeof(List), new ListFormatter()}, - {typeof(List), new ListFormatter()}, - {typeof(List), new ListFormatter()}, - {typeof(List), new ListFormatter()}, - {typeof(List), new ListFormatter()}, - {typeof(List), new ListFormatter()}, - {typeof(List), new ListFormatter()}, - {typeof(List), new ListFormatter()}, - -#endif - }; - - internal static object GetFormatter(Type t) - { - object formatter; - if (FormatterMap.TryGetValue(t, out formatter)) - { - return formatter; - } - - return null; - } - } -} diff --git a/Assets/Plugins/MessagePack/Unity/UnityResolver.cs.meta b/Assets/Plugins/MessagePack/Unity/UnityResolver.cs.meta deleted file mode 100644 index 8e525a0ed..000000000 --- a/Assets/Plugins/MessagePack/Unity/UnityResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a3b64d9daec5fd9b985abcb65adcf699 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/MessagePack/Utilities.cs b/Assets/Plugins/MessagePack/Utilities.cs deleted file mode 100644 index 8d5a4cfe8..000000000 --- a/Assets/Plugins/MessagePack/Utilities.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; - -namespace MessagePack -{ - /// - /// Internal utilities and extension methods for various external types. - /// - internal static class Utilities - { - /// - /// A value indicating whether we're running on mono. - /// -#if UNITY_2018_3_OR_NEWER - internal const bool IsMono = true; // hard code since we haven't tested whether mono is detected on all unity platforms. -#else - internal static readonly bool IsMono = Type.GetType("Mono.Runtime") is Type; -#endif - - internal delegate void GetWriterBytesAction(ref MessagePackWriter writer, TArg argument); - - internal static byte[] GetWriterBytes(TArg arg, GetWriterBytesAction action) - { - using (var sequenceRental = SequencePool.Shared.Rent()) - { - var writer = new MessagePackWriter(sequenceRental.Value); - action(ref writer, arg); - writer.Flush(); - return sequenceRental.Value.AsReadOnlySequence.ToArray(); - } - } - - internal static Memory GetMemoryCheckResult(this IBufferWriter bufferWriter, int size = 0) - { - var memory = bufferWriter.GetMemory(size); - if (memory.IsEmpty) - { - throw new InvalidOperationException("The underlying IBufferWriter.GetMemory(int) method returned an empty memory block, which is not allowed. This is a bug in " + bufferWriter.GetType().FullName); - } - - return memory; - } - } -} diff --git a/Assets/Plugins/MessagePack/Utilities.cs.meta b/Assets/Plugins/MessagePack/Utilities.cs.meta deleted file mode 100644 index 66859785b..000000000 --- a/Assets/Plugins/MessagePack/Utilities.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 908e893ec90c3e0a4acd036922925d17 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.dll b/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.dll deleted file mode 100644 index 19ad4e23b..000000000 --- a/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.dll +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1ad2dd7225d5162a0fd3a3b337a1949448520e3130a4bc8e010ec02f76097500 -size 23600 diff --git a/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.dll.meta b/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.dll.meta deleted file mode 100644 index ff4acd7c5..000000000 --- a/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.dll.meta +++ /dev/null @@ -1,33 +0,0 @@ -fileFormatVersion: 2 -guid: c4ad452d6724491ca843aaee0eacf0e1 -PluginImporter: - externalObjects: {} - serializedVersion: 2 - iconMap: {} - executionOrder: {} - defineConstraints: [] - isPreloaded: 0 - isOverridable: 0 - isExplicitlyReferenced: 0 - validateReferences: 1 - platformData: - - first: - Any: - second: - enabled: 1 - settings: {} - - first: - Editor: Editor - second: - enabled: 0 - settings: - DefaultValueInitialized: true - - first: - Windows Store Apps: WindowsStoreApps - second: - enabled: 0 - settings: - CPU: AnyCPU - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/Aetheria.Shared.Unity.asmdef b/Assets/Scripts/ServerShared/Aetheria.Shared.Unity.asmdef index e86a97903..9d0499aa6 100644 --- a/Assets/Scripts/ServerShared/Aetheria.Shared.Unity.asmdef +++ b/Assets/Scripts/ServerShared/Aetheria.Shared.Unity.asmdef @@ -2,7 +2,6 @@ "name": "Aetheria.Shared.Unity", "rootNamespace": "", "references": [ - "MessagePack", "UniRx", "Ink" ], diff --git a/Assets/Scripts/ServerShared/Attributes.cs b/Assets/Scripts/ServerShared/Attributes.cs index 32256b858..ad70b67c3 100644 --- a/Assets/Scripts/ServerShared/Attributes.cs +++ b/Assets/Scripts/ServerShared/Attributes.cs @@ -16,12 +16,26 @@ public class EntityTypeRestrictionAttribute : Attribute } public class RuntimeInspectable : Attribute { } -// public class CategoryAttribute : Attribute -// { -// public readonly Type Type; -// -// public CategoryAttribute(Type type) -// { -// Type = type; -// } -// } \ No newline at end of file + +// The runtime PropertiesPanel's opt-in; the Studio does not read it. +[AttributeUsage(AttributeTargets.All, Inherited = false)] +public class InspectableAttribute : Attribute { } + +// Inspection meaning CultLib's CultInspector attributes do not carry, drawn by Aetheria's Studio drawers. +[AttributeUsage(AttributeTargets.Field)] +public abstract class PreferredInspectorAttribute : InspectableAttribute { } + +public class InspectableTemperatureAttribute : PreferredInspectorAttribute { } +public class InspectableAnimationCurveAttribute : PreferredInspectorAttribute { } +public class InspectableColorAttribute : PreferredInspectorAttribute { } +public class InspectableSchematicShapeAttribute : PreferredInspectorAttribute { } + +public class InspectableTypeAttribute : PreferredInspectorAttribute +{ + public readonly Type Type; + + public InspectableTypeAttribute(Type type) + { + Type = type; + } +} \ No newline at end of file diff --git a/Assets/Scripts/ServerShared/CultCache.meta b/Assets/Scripts/ServerShared/CultCache.meta deleted file mode 100644 index 84e29514d..000000000 --- a/Assets/Scripts/ServerShared/CultCache.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 49ec0c83548c7084ab0d3f6c2175ee71 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/Attributes.cs b/Assets/Scripts/ServerShared/CultCache/Attributes.cs deleted file mode 100644 index e65b9c268..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Attributes.cs +++ /dev/null @@ -1,146 +0,0 @@ -using System; - -[AttributeUsage(AttributeTargets.Class)] -public class GlobalSettingsAttribute : Attribute { } - -// [AttributeUsage(AttributeTargets.Class)] -// public class ExternalEntryAttribute : Attribute { } - -[AttributeUsage(AttributeTargets.All, Inherited = false)] -public class InspectableAttribute : Attribute { } - -[AttributeUsage(AttributeTargets.Field)] -public abstract class PreferredInspectorAttribute : InspectableAttribute { } - -public class InspectableTextAttribute : PreferredInspectorAttribute { } -public class InspectablePrefabAttribute : PreferredInspectorAttribute { } -public class InspectableTextureAttribute : PreferredInspectorAttribute { } -public class InspectableTextAssetAttribute : PreferredInspectorAttribute { } -public class InspectableTemperatureAttribute : PreferredInspectorAttribute { } -public class InspectableAnimationCurveAttribute : PreferredInspectorAttribute { } -public class InspectableColorAttribute : PreferredInspectorAttribute { } -public class InspectableSoundBankAttribute : PreferredInspectorAttribute { } -public class InspectableAudioParameterAttribute : PreferredInspectorAttribute { } -public class InspectableSchematicShapeAttribute : PreferredInspectorAttribute { } - -public class InspectableEnumValuesAttribute : PreferredInspectorAttribute -{ - public Type EnumType; - - public InspectableEnumValuesAttribute(Type enumType) - { - EnumType = enumType; - } -} - -public class InspectableDatabaseLinkAttribute : PreferredInspectorAttribute -{ - public readonly Type EntryType; - - public InspectableDatabaseLinkAttribute(Type entryType) - { - EntryType = entryType; - } -} - -public class InspectableRangedFloatAttribute : PreferredInspectorAttribute -{ - public readonly float Min, Max; - - public InspectableRangedFloatAttribute(float min, float max) - { - Min = min; - Max = max; - } -} - -public class InspectableRangedIntAttribute : PreferredInspectorAttribute -{ - public readonly int Min, Max; - - public InspectableRangedIntAttribute(int min, int max) - { - Min = min; - Max = max; - } -} - -public class InspectableTypeAttribute : PreferredInspectorAttribute -{ - public readonly Type Type; - - public InspectableTypeAttribute(Type type) - { - Type = type; - } -} - -[AttributeUsage(AttributeTargets.Field)] -public class RangedFloatAttribute : Attribute -{ - public readonly float Min, Max; - - public RangedFloatAttribute(float min, float max) - { - Min = min; - Max = max; - } -} - - -/// -/// Specify a tooltip for a field in the Inspector window. -/// -[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)] -public class TooltipAttribute : Attribute -{ - /// - /// The tooltip text. - /// - public readonly string tooltip; - - /// - /// Specify a tooltip for a field. - /// - /// The tooltip text. - public TooltipAttribute(string tooltip) => this.tooltip = tooltip; -} - -[AttributeUsage(AttributeTargets.Class)] -public class DatabaseCategoryAttribute : Attribute -{ - public string Category; - - public DatabaseCategoryAttribute(string category) - { - Category = category; - } -} - -public class NameAttribute : Attribute -{ - public string Name; - - public NameAttribute(string name) - { - Name = name; - } -} - -public class OrderAttribute : Attribute -{ - public int Order; - - public OrderAttribute(int order) - { - Order = order; - } -} - -[AttributeUsage(AttributeTargets.Field, AllowMultiple = true, Inherited = true)] -public class InspectorHeaderAttribute : Attribute -{ - public readonly string header; - - public InspectorHeaderAttribute(string header) => this.header = header; -} \ No newline at end of file diff --git a/Assets/Scripts/ServerShared/CultCache/Attributes.cs.meta b/Assets/Scripts/ServerShared/CultCache/Attributes.cs.meta deleted file mode 100644 index 45035dfca..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Attributes.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d078a6b39f8c440fabe8d43881207c5d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/CollectionExtensions.cs b/Assets/Scripts/ServerShared/CultCache/CollectionExtensions.cs deleted file mode 100644 index ebb949302..000000000 --- a/Assets/Scripts/ServerShared/CultCache/CollectionExtensions.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Cryptography; -using System.Threading.Tasks; - -public static class CollectionExtensions -{ - // https://stackoverflow.com/a/800469 - public static string GetHashSHA1(this byte[] data) - { - using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider()) - { - return string.Concat(sha1.ComputeHash(data).Select(x => x.ToString("X2"))); - } - } - - // https://stackoverflow.com/a/3188835 - public static T MaxBy(this IEnumerable items, Func selector) - { - if (!items.Any()) - { - throw new InvalidOperationException("Empty input sequence"); - } - - var comparer = Comparer.Default; - T maxItem = items.First(); - U maxValue = selector(maxItem); - - foreach (T item in items.Skip(1)) - { - // Get the value of the item and compare it to the current max. - U value = selector(item); - if (comparer.Compare(value, maxValue) > 0) - { - maxValue = value; - maxItem = item; - } - } - - return maxItem; - } - - public static T MinBy(this IEnumerable items, Func selector) - { - if (!items.Any()) - { - throw new InvalidOperationException("Empty input sequence"); - } - - var comparer = Comparer.Default; - T maxItem = items.First(); - U maxValue = selector(maxItem); - - foreach (T item in items.Skip(1)) - { - // Get the value of the item and compare it to the current max. - U value = selector(item); - if (comparer.Compare(value, maxValue) < 0) - { - maxValue = value; - maxItem = item; - } - } - - return maxItem; - } -} - -public static class AsyncAwaitExtensions -{ - public static async void WrapAwait(this Task task) - { - await task; - } -} \ No newline at end of file diff --git a/Assets/Scripts/ServerShared/CultCache/CollectionExtensions.cs.meta b/Assets/Scripts/ServerShared/CultCache/CollectionExtensions.cs.meta deleted file mode 100644 index 6ff22bed8..000000000 --- a/Assets/Scripts/ServerShared/CultCache/CollectionExtensions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: eed05df00a9a6b84292c81be1662a66e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/CultCache.cs b/Assets/Scripts/ServerShared/CultCache/CultCache.cs deleted file mode 100644 index b2cd294e8..000000000 --- a/Assets/Scripts/ServerShared/CultCache/CultCache.cs +++ /dev/null @@ -1,437 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ - -using System; -using System.Buffers.Text; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; -using MessagePack; -using Newtonsoft.Json; -using UniRx; - -public class CultCache -{ - - private readonly object addLock = new object(); - - //public Action Logger = Console.WriteLine; - //private string _filePath; - - public event Action OnUpdate; - - private List _backingStores = new List(); - - private readonly Dictionary _typeStores = new Dictionary(); - private readonly Dictionary _storeTypes = new Dictionary(); - - private readonly Dictionary _entries = new Dictionary(); - - private readonly Dictionary _globals = new Dictionary(); - private readonly Dictionary> _types = new Dictionary>(); - - public IEnumerable AllEntries => _entries.Values; - - public CultCache() - { - DatabaseLinkBase.Cache = this; - - foreach (var type in typeof(DatabaseEntry).GetAllChildClasses()) - { - _types[type] = new HashSet(); - - if (type.GetCustomAttribute() != null) - { - _globals[type] = null; - Add(Activator.CreateInstance(type) as DatabaseEntry); - } - } - } - - public void AddBackingStore(CacheBackingStore store, params Type[] domain) - { - if (domain.Length > 0) - { - _storeTypes[store] = domain; - foreach (var t in domain) _typeStores[t] = store; - } - else - { - foreach(var existingStore in _backingStores) store.SubscribeTo(existingStore); - _backingStores.Add(store); - } - store.EntryAdded.Subscribe(entry => - { - Add(entry, store); - OnUpdate?.Invoke(null, entry); - }); - store.EntryUpdated.Subscribe(entry => - { - Add(entry, store); - OnUpdate?.Invoke(entry, entry); - }); - store.EntryDeleted.Subscribe(entry => - { - Remove(entry, store); - OnUpdate?.Invoke(entry, null); - }); - } - - public void PullAllBackingStores() - { - foreach(var store in _backingStores) store.PullAll(); - foreach(var store in _storeTypes.Keys) store.PullAll(); - } - - public void Add(DatabaseEntry entry, CacheBackingStore source = null) - { - lock(addLock) - { - if (entry != null) - { - var exists = _entries.ContainsKey(entry.ID); - - var type = entry.GetType(); - - if (_globals.ContainsKey(type)) - { - if(_globals[type]!=null) - { - Remove(_globals[type]); - exists = true; - } - _globals[type] = entry; - } - - if(_typeStores.ContainsKey(type)) - _typeStores[type].Push(entry); - else - { - var masterStore = _backingStores.First(); - if(masterStore!=source) - masterStore.Push(entry); - } - - _entries[entry.ID] = entry; - _types[type].Add(entry); - foreach (var parentType in type.GetParentTypes()) - { - if(_types.ContainsKey(parentType)) - _types[parentType].Add(entry); - } - - } - } - } - - public bool IsGlobal(DatabaseEntry entry) => _globals.ContainsKey(entry.GetType()); - - public void AddAll(IEnumerable entries) - { - foreach (var entry in entries) - { - Add(entry); - } - } - - public DatabaseEntry Get(Guid guid) - { - DatabaseEntry entry; - _entries.TryGetValue(guid, out entry); - return entry; - } - - public T Get(Guid guid) where T : DatabaseEntry - { - return Get(guid) as T; - } - - public DatabaseEntry GetGlobal(Type type) - { - if (_globals.ContainsKey(type)) return _globals[type]; - return null; - } - - public T GetGlobal() where T : DatabaseEntry - { - return GetGlobal(typeof(T)) as T; - } - - public IEnumerable GetAll(Type type) - { - return !_types.ContainsKey(type) ? Enumerable.Empty() : _types[type]; - } - - public IEnumerable GetAll() where T : DatabaseEntry - { - var type = typeof(T); - return !_types.ContainsKey(type) ? Enumerable.Empty() : _types[type].Cast(); - } - - public void Remove(DatabaseEntry entry, CacheBackingStore source = null) - { - _entries.Remove(entry.ID); - var type = entry.GetType(); - if(_typeStores.ContainsKey(type)) - _typeStores[type].Delete(entry); - else foreach(var store in _backingStores) - { - if(store != source) - store.Delete(entry); - } - foreach (var parentType in type.GetParentTypes()) - { - if(_types.ContainsKey(parentType)) - _types[parentType].Remove(entry); - } - } -} - -public interface RealtimeBackingStore -{ - public void ObserveChanges(); -} - -public abstract class CacheBackingStore -{ - protected CacheBackingStore() - { - EntryAdded = new Subject(); - EntryDeleted = new Subject(); - EntryUpdated = new Subject(); - } - - public abstract void PullAll(); - public abstract void Push(DatabaseEntry entry); - public abstract void Delete(DatabaseEntry entry); - public abstract void PushAll(bool soft = false); - - public Subject EntryAdded { get; } - public Subject EntryDeleted { get; } - public Subject EntryUpdated { get; } - - protected Dictionary Entries = new Dictionary(); - - public void SubscribeTo(CacheBackingStore targetStore) - { - targetStore.EntryAdded.Subscribe(Push); - targetStore.EntryDeleted.Subscribe(Delete); - targetStore.EntryUpdated.Subscribe(Push); - } -} - -public abstract class MultiFileBackingStore : CacheBackingStore, RealtimeBackingStore -{ - public DirectoryInfo DirectoryInfo { get; } - protected Dictionary _entryTypeDirectories = new Dictionary(); - - public abstract byte[] Serialize(DatabaseEntry entry); - public abstract DatabaseEntry Deserialize(byte[] data); - public abstract string Extension { get; } - - public MultiFileBackingStore(string path) - { - DirectoryInfo = new DirectoryInfo(path); - foreach (var type in typeof(DatabaseEntry).GetAllChildClasses()) - { - _entryTypeDirectories[type] = DirectoryInfo.CreateSubdirectory(type.Name); - } - } - - public override void PullAll() - { - if (!DirectoryInfo.Exists) return; - - foreach (var directory in _entryTypeDirectories.Values) - { - foreach (var file in directory.EnumerateFiles($"*.{Extension}")) - { - var entry = Deserialize(File.ReadAllBytes(file.FullName)); - Entries[entry.ID] = entry; - EntryAdded.OnNext(entry); - } - } - } - - private string GetFileName(DatabaseEntry entry) => - $"{(entry is INamedEntry namedEntry ? namedEntry.EntryName : entry.ID.ToString())}.{Extension}"; - - public override void Push(DatabaseEntry entry) - { - var type = entry.GetType(); - Entries[entry.ID] = entry; - var directory = _entryTypeDirectories[type]; - File.WriteAllBytes(Path.Combine(directory.FullName, GetFileName(entry)), Serialize(entry)); - } - - public override void Delete(DatabaseEntry entry) - { - if(Entries.ContainsKey(entry.ID)) - { - var type = entry.GetType(); - Entries.Remove(entry.ID); - var directory = _entryTypeDirectories[type]; - var file = new FileInfo(Path.Combine(directory.FullName, GetFileName(entry))); - if (file.Exists) - file.Delete(); - } - } - - public override void PushAll(bool soft = false) - { - foreach(var entry in Entries.Values.ToArray()) Push(entry); - } - - public void ObserveChanges() - { - foreach (var directory in _entryTypeDirectories.Values) - { - var watcher = new FileSystemWatcher(directory.FullName); - watcher.Changed += (sender, args) => - { - var entry = Deserialize(File.ReadAllBytes(args.FullPath)); - Entries[entry.ID] = entry; - EntryUpdated.OnNext(entry); - }; - watcher.Created += (sender, args) => - { - var entry = Deserialize(File.ReadAllBytes(args.FullPath)); - Entries[entry.ID] = entry; - EntryAdded.OnNext(entry); - }; - watcher.Deleted += (sender, args) => - { - var entry = Deserialize(File.ReadAllBytes(args.FullPath)); - Entries[entry.ID] = entry; - EntryDeleted.OnNext(entry); - }; - } - } -} - -public class MultiFileJsonBackingStore : MultiFileBackingStore -{ - public MultiFileJsonBackingStore(string path) : base(path) - { - RegisterResolver.Register(); - } - - public override byte[] Serialize(DatabaseEntry entry) - { - return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(entry)); - } - - public override DatabaseEntry Deserialize(byte[] data) - { - return JsonConvert.DeserializeObject(Encoding.UTF8.GetString(data)); - } - - public override string Extension => "json"; -} - -public class MultiFileMessagePackBackingStore : MultiFileBackingStore -{ - public MultiFileMessagePackBackingStore(string path) : base(path) - { - RegisterResolver.Register(); - } - - public override byte[] Serialize(DatabaseEntry entry) - { - return MessagePackSerializer.Serialize(entry); - } - - public override DatabaseEntry Deserialize(byte[] data) - { - return MessagePackSerializer.Deserialize(data); - } - - public override string Extension => "msgpack"; -} - -public abstract class SingleFileBackingStore : CacheBackingStore -{ - public FileInfo FileInfo { get; } - - public abstract byte[] Serialize(DatabaseEntry[] entries); - public abstract DatabaseEntry[] Deserialize(byte[] data); - - public SingleFileBackingStore(string filePath) - { - FileInfo = new FileInfo(filePath); - } - - public override void PullAll() - { - if (!FileInfo.Exists) return; - - foreach (var entry in Deserialize(File.ReadAllBytes(FileInfo.FullName))) - { - Entries[entry.ID] = entry; - EntryAdded.OnNext(entry); - } - } - - public override void Push(DatabaseEntry entry) - { - var type = entry.GetType(); - Entries[entry.ID] = entry; - PushAll(); - } - - public override void Delete(DatabaseEntry entry) - { - if(Entries.ContainsKey(entry.ID)) - { - Entries.Remove(entry.ID); - PushAll(); - } - } - - public override void PushAll(bool soft = false) - { - var entriesArray = Entries.Values.ToArray(); - File.WriteAllBytes(FileInfo.FullName, Serialize(entriesArray)); - } -} - -public class SingleFileMessagePackBackingStore : SingleFileBackingStore -{ - public SingleFileMessagePackBackingStore(string filePath) : base(filePath) - { - RegisterResolver.Register(); - } - - public override byte[] Serialize(DatabaseEntry[] entries) - { - return MessagePackSerializer.Serialize(entries); - } - - public override DatabaseEntry[] Deserialize(byte[] data) - { - return MessagePackSerializer.Deserialize(data); - } -} - -public class SingleFileJsonBackingStore : SingleFileBackingStore -{ - public SingleFileJsonBackingStore(string filePath) : base(filePath) - { - RegisterResolver.Register(); - } - - public override byte[] Serialize(DatabaseEntry[] entries) - { - return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(entries)); - } - - public override DatabaseEntry[] Deserialize(byte[] data) - { - return JsonConvert.DeserializeObject(Encoding.UTF8.GetString(data)); - } -} diff --git a/Assets/Scripts/ServerShared/CultCache/CultCache.cs.meta b/Assets/Scripts/ServerShared/CultCache/CultCache.cs.meta deleted file mode 100644 index b4bfbdf1f..000000000 --- a/Assets/Scripts/ServerShared/CultCache/CultCache.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a43b39c6991618b43aed4a24ffcdc0ff -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/DatabaseEntry.cs b/Assets/Scripts/ServerShared/CultCache/DatabaseEntry.cs deleted file mode 100644 index cf1463467..000000000 --- a/Assets/Scripts/ServerShared/CultCache/DatabaseEntry.cs +++ /dev/null @@ -1,92 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ - -using System; -using System.Linq; -using JsonKnownTypes; -using MessagePack; -using MessagePack.Formatters; -using Newtonsoft.Json; -// TODO: USE THIS EVERYWHERE -using CultMath; -using static CultMath.math; - -public interface INamedEntry -{ - string EntryName { get; set; } -} - -[MessagePackObject, - JsonObject(MemberSerialization.OptIn), - JsonConverter(typeof(JsonKnownTypesConverter)), - Union(0, typeof(SimpleCommodityData)), - Union(1, typeof(CompoundCommodityData)), - Union(2, typeof(GearData)), - Union(3, typeof(HullData)), - Union(4, typeof(SimpleCommodity)), - Union(5, typeof(CompoundCommodity)), - Union(6, typeof(EquippableItem)), - Union(8, typeof(GalaxyMapLayerData)), - Union(9, typeof(NameFile)), - //Union(10, typeof(ZoneData)), - Union(11, typeof(PlayerData)), - // Union(12, typeof(Corporation)), - Union(13, typeof(Faction)), - Union(14, typeof(OrbitalEntity)), - Union(15, typeof(OrbitData)), - Union(16, typeof(BodyData)), - Union(17, typeof(PersonalityAttribute)), - Union(18, typeof(AgentTask)), - // Union(19, typeof(LoadoutData)), - Union(20, typeof(Ship)), - Union(21, typeof(Mining)), - Union(22, typeof(StationTowing)), - Union(23, typeof(Survey)), - Union(24, typeof(HaulingTask)), - Union(25, typeof(AsteroidBeltData)), - Union(26, typeof(GasGiantData)), - Union(27, typeof(SunData)), - Union(28, typeof(PlanetData)), - Union(29, typeof(CargoBayData)), - Union(30, typeof(DockingBayData)), - Union(31, typeof(WeaponItemData)), - Union(32, typeof(FactionProductData))] -public abstract class DatabaseEntry -{ - [JsonProperty("id"), Key(0)] - public Guid ID = Guid.NewGuid(); - - public override int GetHashCode() - { - return ID.GetHashCode(); - } - - public override bool Equals(object obj) - { - if (obj is DatabaseEntry entry) return entry.ID == ID; - return false; - } -} - -[MessagePackObject, JsonObject(MemberSerialization.OptIn)] -public class DatabaseLink : DatabaseLinkBase where T : DatabaseEntry -{ - [IgnoreMember] - public T Value => Cache.Get(LinkID); -} - -[MessagePackObject, JsonObject(MemberSerialization.OptIn)] -public class DatabaseLinkBase -{ - [Key(0), JsonProperty("linkID")] - public Guid LinkID; - - [IgnoreMember] - public static CultCache Cache; -} - -public interface ITintInspector -{ - float3 TintColor { get; } -} \ No newline at end of file diff --git a/Assets/Scripts/ServerShared/CultCache/DatabaseEntry.cs.meta b/Assets/Scripts/ServerShared/CultCache/DatabaseEntry.cs.meta deleted file mode 100644 index 7e44aa10b..000000000 --- a/Assets/Scripts/ServerShared/CultCache/DatabaseEntry.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3bb4780bed7bb544dbf6ea2223dd8f06 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/ReflectionExtensions.cs b/Assets/Scripts/ServerShared/CultCache/ReflectionExtensions.cs deleted file mode 100644 index 8e3468194..000000000 --- a/Assets/Scripts/ServerShared/CultCache/ReflectionExtensions.cs +++ /dev/null @@ -1,128 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading.Tasks; - -public static class ReflectionExtensions -{ - // Every type that can be loaded from every assembly in the domain. An assembly whose dependencies are missing - // (a Unity plugin referencing UnityEngine when running outside Unity) still yields the types that do load. - private static IEnumerable LoadableTypes() - { - return AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => - { - try { return assembly.GetTypes(); } - catch (ReflectionTypeLoadException e) { return e.Types.Where(t => t != null); } - }); - } - - private static Dictionary InterfaceClasses = new Dictionary(); - public static Type[] GetAllInterfaceClasses(this Type type) - { - if (InterfaceClasses.ContainsKey(type)) - return InterfaceClasses[type]; - return InterfaceClasses[type] = LoadableTypes().Where(t => t.IsClass && t.GetInterfaces().Contains(type)).ToArray(); - } - - private static Dictionary ParentTypes = new Dictionary(); - - public static Type[] GetParentTypes(this Type type) - { - if (ParentTypes.ContainsKey(type)) - return ParentTypes[type]; - return ParentTypes[type] = type.GetParents().ToArray(); - } - - private static IEnumerable GetParents(this Type type) - { - // is there any base type? - if (type == null) - { - yield break; - } - - yield return type; - - // return all implemented or inherited interfaces - foreach (var i in type.GetInterfaces()) - { - yield return i; - } - - // return all inherited types - var currentBaseType = type.BaseType; - while (currentBaseType != null) - { - yield return currentBaseType; - currentBaseType= currentBaseType.BaseType; - } - } - - private static Dictionary ChildClasses = new Dictionary(); - public static Type[] GetAllChildClasses(this Type type) - { - if (ChildClasses.ContainsKey(type)) - return ChildClasses[type]; - return ChildClasses[type] = LoadableTypes().Where(type.IsAssignableFrom).ToArray(); - } - - private static Dictionary GenericChildClasses = new Dictionary(); - public static Type[] GetAllGenericChildClasses(this Type genericType) - { - if (GenericChildClasses.ContainsKey(genericType)) - return GenericChildClasses[genericType]; - return GenericChildClasses[genericType] = LoadableTypes().Where(type=>type.IsAssignableToGenericType(genericType)).ToArray(); - } - - public static bool IsAssignableToGenericType(this Type givenType, Type genericType) - { - var interfaceTypes = givenType.GetInterfaces(); - - foreach (var it in interfaceTypes) - { - if (it.IsGenericType && it.GetGenericTypeDefinition() == genericType) - return true; - } - - if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericType) - return true; - - Type baseType = givenType.BaseType; - if (baseType == null) return false; - - return IsAssignableToGenericType(baseType, genericType); - } - - public static string SplitCamelCase( this string str ) - { - return Regex.Replace( - Regex.Replace( - str, - @"(\P{Ll})(\P{Ll}\p{Ll})", - "$1 $2" - ), - @"(\p{Ll})(\P{Ll})", - "$1 $2" - ); - } - - public static string FormatTypeName(this string typeName) - { - return (typeName.EndsWith("Data", StringComparison.InvariantCultureIgnoreCase) - ? typeName.Substring(0, typeName.Length - 4) - : typeName).SplitCamelCase(); - } - - public static string GetFullName(this Type t) - { - if (!t.IsGenericType) - return t.Name.FormatTypeName(); - - var name = t.Name.FormatTypeName(); - return - $"{name.Substring(0, name.LastIndexOf("`"))}{t.GetGenericArguments().Aggregate("<", (aggregate, type) => $"{aggregate}{(aggregate == "<" ? "" : ",")}{GetFullName(type)}")}>"; - } -} \ No newline at end of file diff --git a/Assets/Scripts/ServerShared/CultCache/ReflectionExtensions.cs.meta b/Assets/Scripts/ServerShared/CultCache/ReflectionExtensions.cs.meta deleted file mode 100644 index 64127bd9f..000000000 --- a/Assets/Scripts/ServerShared/CultCache/ReflectionExtensions.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: fd5642f26b80465fb57f3d2610633140 -timeCreated: 1617055075 \ No newline at end of file diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonConverters.cs b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonConverters.cs deleted file mode 100644 index 6b6c1da96..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonConverters.cs +++ /dev/null @@ -1,169 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using CultMath; -using static CultMath.math; - -public class MathJsonConverter : JsonConverter -{ - private readonly Dictionary> _writers; - private readonly Dictionary> _readers; - - public MathJsonConverter() - { - _writers = GenerateWriters(); - _readers = GenerateReaders(); - } - - private Dictionary> GenerateWriters() - { - var writers = new Dictionary>(); - - writers[typeof(float2)] = (writer, o) => - { - if (!(o is float2 v)) - throw new JsonReaderException(); - - writer.WriteStartArray(); - writer.WriteValue(v.x); - writer.WriteValue(v.y); - writer.WriteEndArray(); - }; - - writers[typeof(int2)] = (writer, o) => - { - if (!(o is int2 v)) - throw new JsonReaderException(); - - writer.WriteStartArray(); - writer.WriteValue(v.x); - writer.WriteValue(v.y); - writer.WriteEndArray(); - }; - - writers[typeof(float3)] = (writer, o) => - { - if (!(o is float3 v)) - throw new JsonReaderException(); - - writer.WriteStartArray(); - writer.WriteValue(v.x); - writer.WriteValue(v.y); - writer.WriteValue(v.z); - writer.WriteEndArray(); - }; - - writers[typeof(float4)] = (writer, o) => - { - if (!(o is float4 v)) - throw new JsonReaderException(); - - writer.WriteStartArray(); - writer.WriteValue(v.x); - writer.WriteValue(v.y); - writer.WriteValue(v.z); - writer.WriteValue(v.w); - writer.WriteEndArray(); - }; - - return writers; - } - - private Dictionary> GenerateReaders() - { - var readers = new Dictionary>(); - - readers[typeof(float2)] = array => - { - if (array.Count < 2) - { - throw new JsonReaderException( - $"Could not read {typeof(float2)} from json, expected a json array with 2 elements"); - } - - return float2( - array[0].ToObject(), - array[1].ToObject()); - }; - - readers[typeof(int2)] = array => - { - if (array.Count < 2) - { - throw new JsonReaderException( - $"Could not read {typeof(float2)} from json, expected a json array with 2 elements"); - } - - return int2( - array[0].ToObject(), - array[1].ToObject()); - }; - - readers[typeof(float3)] = array => - { - if (array.Count < 3) - { - throw new JsonReaderException( - $"Could not read {typeof(float3)} from json, expected a json array with 3 elements"); - } - - return float3( - array[0].ToObject(), - array[1].ToObject(), - array[2].ToObject()); - }; - - readers[typeof(float4)] = array => - { - if (array.Count < 4) - { - throw new JsonReaderException( - $"Could not read {typeof(float4)} from json, expected a json array with 4 elements"); - } - - return float4( - array[0].ToObject(), - array[1].ToObject(), - array[2].ToObject(), - array[3].ToObject()); - }; - - return readers; - } - - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - if (_writers.TryGetValue(value.GetType(), out var serializeAction)) - serializeAction(writer, value); - else - throw new JsonReaderException($"Invalid type for ValueConverter:{value.GetType()}"); - } - - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - if (_readers.TryGetValue(objectType, out var deserializeFunc)) - { - // Convert token from reader to array for deserialize function - var token = JToken.ReadFrom(reader); - if (!(token is JArray asArray)) - throw new JsonReaderException( - $"Could not read {objectType} from json, expected a json array but got {token.Type}"); - - return deserializeFunc(asArray); - } - - throw new JsonReaderException($"Invalid type for ValueConverter:{objectType}"); - } - - public override bool CanConvert(Type objectType) - { - //If the dictionary contains the key, the type can be handled by this class - return _writers.ContainsKey(objectType); - } - - //Enable this JSON Converter for reading as well as writing values - public override bool CanRead => true; - public override bool CanWrite => true; -} diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonConverters.cs.meta b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonConverters.cs.meta deleted file mode 100644 index a45bf1a53..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonConverters.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: fafad9d553198e942a5501ea1472ec9c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes.meta b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes.meta deleted file mode 100644 index 81eae7208..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: f94c63c8b140fb34bb5d70a8d8a5dbd6 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/AttributesManager.cs b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/AttributesManager.cs deleted file mode 100644 index c164613f4..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/AttributesManager.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; - -namespace JsonKnownTypes -{ - public static class AttributesManager - { - public static JsonKnownTypeAttribute[] GetJsonKnownAttributes(Type type) => - (JsonKnownTypeAttribute[])Attribute.GetCustomAttributes(type, typeof(JsonKnownTypeAttribute)); - - public static JsonKnownThisTypeAttribute GetJsonKnownThisAttribute(Type type) => - (JsonKnownThisTypeAttribute)Attribute.GetCustomAttribute(type, typeof(JsonKnownThisTypeAttribute)); - - public static JsonDiscriminatorAttribute GetJsonDiscriminatorAttribute(Type type) => - (JsonDiscriminatorAttribute)Attribute.GetCustomAttribute(type, typeof(JsonDiscriminatorAttribute)); - } -} diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/AttributesManager.cs.meta b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/AttributesManager.cs.meta deleted file mode 100644 index 692781e53..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/AttributesManager.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6036d25d64e90064ca92c91f6d7827b2 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/Exceptions.meta b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/Exceptions.meta deleted file mode 100644 index e7515a8b8..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/Exceptions.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 01722fba3f2fd3942bca61d48508ad27 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/Exceptions/JsonKnownTypesException.cs b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/Exceptions/JsonKnownTypesException.cs deleted file mode 100644 index 417772b64..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/Exceptions/JsonKnownTypesException.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; - -namespace JsonKnownTypes.Exceptions -{ - public class JsonKnownTypesException : Exception - { - public JsonKnownTypesException(string message) - : base(message) - { } - - public JsonKnownTypesException(string message, Exception innerException) - : base(message, innerException) - { } - } -} diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/Exceptions/JsonKnownTypesException.cs.meta b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/Exceptions/JsonKnownTypesException.cs.meta deleted file mode 100644 index abc9ed520..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/Exceptions/JsonKnownTypesException.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 36f9ed87d773cf146bf68e828cefe89c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonDiscriminatorAttribute.cs b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonDiscriminatorAttribute.cs deleted file mode 100644 index bfb337f38..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonDiscriminatorAttribute.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; - -namespace JsonKnownTypes -{ - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)] - public class JsonDiscriminatorAttribute : Attribute - { - public string Name { get; set; } - - internal bool? _autoJson; - - public bool AutoJson - { - get => _autoJson != null && (bool) _autoJson; - set => _autoJson = value; - } - } -} diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonDiscriminatorAttribute.cs.meta b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonDiscriminatorAttribute.cs.meta deleted file mode 100644 index d826e354a..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonDiscriminatorAttribute.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f7c6582f43e22994ebbaf0e139e63dc5 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonDiscriminatorSettings.cs b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonDiscriminatorSettings.cs deleted file mode 100644 index 7d9386122..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonDiscriminatorSettings.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace JsonKnownTypes -{ - public class JsonDiscriminatorSettings - { - public string Name { get; set; } = "$type"; - public bool AutoJsonKnown { get; set; } = true; - } -} diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonDiscriminatorSettings.cs.meta b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonDiscriminatorSettings.cs.meta deleted file mode 100644 index b23d572e6..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonDiscriminatorSettings.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b5f09ee78f257904caa3ab939d3edc65 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownThisTypeAttribute.cs b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownThisTypeAttribute.cs deleted file mode 100644 index 6733da6ff..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownThisTypeAttribute.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; - -namespace JsonKnownTypes -{ - public class JsonKnownThisTypeAttribute : Attribute - { - public string Discriminator { get; } - - public JsonKnownThisTypeAttribute() - { } - - public JsonKnownThisTypeAttribute(string discriminator) - { - Discriminator = discriminator; - } - } -} diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownThisTypeAttribute.cs.meta b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownThisTypeAttribute.cs.meta deleted file mode 100644 index d11e7fc5f..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownThisTypeAttribute.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c8dc4cbd1c54167409cf14ec8ec37d70 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypeAttribute.cs b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypeAttribute.cs deleted file mode 100644 index ef8a2dcca..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypeAttribute.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; - -namespace JsonKnownTypes -{ - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true)] - public class JsonKnownTypeAttribute : Attribute - { - public Type Type { get; } - public string Discriminator { get; } - - public JsonKnownTypeAttribute(Type type) - { - Type = type; - } - - public JsonKnownTypeAttribute(Type type, string discriminator) - { - Type = type; - Discriminator = discriminator; - } - } -} diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypeAttribute.cs.meta b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypeAttribute.cs.meta deleted file mode 100644 index 67c7bc35e..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypeAttribute.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ecbe3646a4d9ca04eac598b60e5c77ca -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypes.csproj b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypes.csproj deleted file mode 100644 index 1d7caa587..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypes.csproj +++ /dev/null @@ -1,22 +0,0 @@ - - - - netstandard2.0 - - - - - - - - true - 0.2.0 - Dmitry Kaznacheev - https://github.com/dmitry-bym/JsonKnownTypes - https://github.com/dmitry-bym/JsonKnownTypes/blob/master/LICENSE - Dmitry Kaznacheev - https://github.com/dmitry-bym/JsonKnownTypes - json known polymorphic types - - - diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypes.csproj.meta b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypes.csproj.meta deleted file mode 100644 index c016da1db..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypes.csproj.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: 937d902757d946b47a7bea20ade37beb -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesContractResolver.cs b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesContractResolver.cs deleted file mode 100644 index 797e420a7..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesContractResolver.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; - -namespace JsonKnownTypes -{ - public class JsonKnownTypesContractResolver : DefaultContractResolver - { - protected override JsonConverter ResolveContractConverter(Type objectType) - { - if (typeof(T).IsAssignableFrom(objectType) && !objectType.IsAbstract) - return null; - return base.ResolveContractConverter(objectType); - } - } -} diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesContractResolver.cs.meta b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesContractResolver.cs.meta deleted file mode 100644 index 51f187146..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesContractResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bce1b7fa2da230447b3614d23394ee9f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesConverter.cs b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesConverter.cs deleted file mode 100644 index 343cd73a6..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesConverter.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace JsonKnownTypes -{ - public class JsonKnownTypesConverter : JsonConverter - { - private readonly JsonKnownTypesSettings _typesSettings - = JsonKnownTypesSettingsManager.GetSettings(); - - private JsonSerializerSettings SpecifiedSubclassConversion - { - get => - new JsonSerializerSettings - { - ContractResolver = new JsonKnownTypesContractResolver() - }; - } - - public override bool CanConvert(Type objectType) - => _typesSettings.TypeToDiscriminator.ContainsKey(objectType); - - public override bool CanWrite { get => true; } - - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - if (reader.TokenType == JsonToken.Null) return null; - - var jo = JObject.Load(reader); - - var discriminator = jo[_typesSettings.Name].ToString(); - - if(_typesSettings.DiscriminatorToType.TryGetValue(discriminator, out var typeForObject)) - return JsonConvert.DeserializeObject(jo.ToString(), typeForObject, SpecifiedSubclassConversion); - - return null; - //throw new NotImplementedException(); - } - - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - var objectType = value.GetType(); - if (_typesSettings.TypeToDiscriminator.TryGetValue(objectType, out var discriminator)) - { - var json = JsonConvert.SerializeObject(value, SpecifiedSubclassConversion); - var jo = JObject.Parse(json); - jo.Add(_typesSettings.Name, new JValue(discriminator)); - jo.WriteTo(writer); - } - else - { - throw new ArgumentException($"Json Known Types: Type Unknown {objectType.FullName}!"); - } - } - } -} diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesConverter.cs.meta b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesConverter.cs.meta deleted file mode 100644 index f075f2684..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b0a6c832fc846634789aa691cd2b81d9 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesDictionaryManager.cs b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesDictionaryManager.cs deleted file mode 100644 index 09b8f5634..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesDictionaryManager.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using JsonKnownTypes.Exceptions; - -namespace JsonKnownTypes -{ - internal static class JsonKnownTypesDictionaryManager - { - public static void AddJsonKnown(this Dictionary dictionary) - { - var attrs = AttributesManager.GetJsonKnownAttributes(typeof(T)); - foreach (var attr in attrs) - { - var discriminator = attr.Discriminator ?? attr.Type.Name; - dictionary.TryAdd(attr.Type, discriminator); - } - } - - public static void AddJsonKnownThis(this Dictionary dictionary, Type[] inherited) - { - foreach (var type in inherited) - { - var attr = AttributesManager.GetJsonKnownThisAttribute(type); - if (attr != null) - { - var discriminator = attr.Discriminator ?? type.Name; - dictionary.TryAdd(type, discriminator); - } - } - } - - public static void AddAutoGenerated(this Dictionary dictionary, Type[] inherited) - { - foreach (var type in inherited.Except(dictionary.Keys)) - { - dictionary.TryAdd(type, type.Name); - } - } - - public static void TryAdd(this Dictionary dictionary, Type key, string discriminator) - { - if (dictionary.ContainsKey(key)) - throw new JsonKnownTypesException($"Dictionary already contains the key {key.Name}");//todo - - if (dictionary.ContainsValue(discriminator)) - throw new JsonKnownTypesException($"Dictionary already contains the value {discriminator}");//todo - - dictionary.Add(key, discriminator); - } - - public static Dictionary Revert(this Dictionary dictionary) - { - try - { - return dictionary.ToDictionary(x => x.Value, x => x.Key); - } - catch (ArgumentException e) - { - throw new JsonKnownTypesException("Dictionary has a repeated value", e); - } - } - } -} diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesDictionaryManager.cs.meta b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesDictionaryManager.cs.meta deleted file mode 100644 index 33f376bd2..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesDictionaryManager.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 77ce621509349204a87085f089b3daa3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesSettings.cs b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesSettings.cs deleted file mode 100644 index 6d61fdb74..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesSettings.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace JsonKnownTypes -{ - public class JsonKnownTypesSettings - { - public string Name { get; set; } - public Dictionary DiscriminatorToType { get; set; } = new Dictionary(); - public Dictionary TypeToDiscriminator { get; set; } = new Dictionary(); - } -} diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesSettings.cs.meta b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesSettings.cs.meta deleted file mode 100644 index 750329339..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesSettings.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 99b988650c739094aa3a5ba7040ea379 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesSettingsManager.cs b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesSettingsManager.cs deleted file mode 100644 index c3c011efa..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesSettingsManager.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using JsonKnownTypes.Exceptions; -using JsonKnownTypes.Utils; - -namespace JsonKnownTypes -{ - public static class JsonKnownTypesSettingsManager - { - public static JsonDiscriminatorSettings DefaultDiscriminatorSettings { get; set; } = new JsonDiscriminatorSettings(); - - private static HashSet RegisteredAssemblies = new HashSet(); - public static void RegisterTypeAssembly() - { - var type = typeof(T); - RegisteredAssemblies.Add(type.Assembly); - } - - public static JsonKnownTypesSettings GetSettings() - { - var discriminatorAttribute = AttributesManager.GetJsonDiscriminatorAttribute(typeof(T)); - - var discriminatorSettings = discriminatorAttribute == null ? DefaultDiscriminatorSettings : Mapper.Map(discriminatorAttribute); - - var typeSettings = new JsonKnownTypesSettings - { - Name = discriminatorSettings.Name - }; - - var allTypes = GetAllInheritance(); - - typeSettings.TypeToDiscriminator.AddJsonKnown(); - typeSettings.TypeToDiscriminator.AddJsonKnownThis(allTypes); - - if (discriminatorSettings.AutoJsonKnown) - { - typeSettings.TypeToDiscriminator.AddAutoGenerated(allTypes); - } - else if(!allTypes.All(typeSettings.TypeToDiscriminator.ContainsKey)) - { - throw new JsonKnownTypesException("Dictionary contains not all types of hierarchy, enable AutoJsonKnow or add attributes for all classes"); //todo - } - - typeSettings.DiscriminatorToType = typeSettings.TypeToDiscriminator.Revert(); - - return typeSettings; - } - - private static Type[] GetAllInheritance() - { - RegisterTypeAssembly(); - var type = typeof(T); - return RegisteredAssemblies.SelectMany(a=>a.GetTypes()) - .Where(x => type.IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract) - .ToArray(); - } - } -} diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesSettingsManager.cs.meta b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesSettingsManager.cs.meta deleted file mode 100644 index b7a14d98d..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/JsonKnownTypesSettingsManager.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a361505c5408b374788cbaeed6fa2f55 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/Utils.meta b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/Utils.meta deleted file mode 100644 index caeca5e85..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/Utils.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 6d6706b0998d8af458321fd5f35906fb -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/Utils/Mapper.cs b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/Utils/Mapper.cs deleted file mode 100644 index c18b844ae..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/Utils/Mapper.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace JsonKnownTypes.Utils -{ - internal static class Mapper - { - public static JsonDiscriminatorSettings Map(JsonDiscriminatorAttribute entity) - { - var settings = new JsonDiscriminatorSettings(); - - settings.Name = entity.Name ?? settings.Name; - settings.AutoJsonKnown = entity._autoJson ?? settings.AutoJsonKnown; - - return settings; - } - } -} diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/Utils/Mapper.cs.meta b/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/Utils/Mapper.cs.meta deleted file mode 100644 index 21162c161..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/JsonKnownTypes/Utils/Mapper.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c30d51fc767627a41b65f5cdd2b22cc3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/RegisterResolver.cs b/Assets/Scripts/ServerShared/CultCache/Serialization/RegisterResolver.cs deleted file mode 100644 index b9292893d..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/RegisterResolver.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Collections; -using System.Collections.Generic; -using MessagePack; -using MessagePack.ReactivePropertyExtension; -using MessagePack.Resolvers; -using Newtonsoft.Json; - -public static class RegisterResolver -{ - private static bool registered = false; - public static void Register() - { - if (registered) return; - - // Set extensions to default resolver. - var resolver = CompositeResolver.Create( - MathResolver.Instance, - TypeResolver.Instance, - NativeGuidResolver.Instance, - StandardResolver.Instance, - ReactivePropertyResolver.Instance - ); - var options = MessagePackSerializerOptions.Standard.WithResolver(resolver); - MessagePackSerializer.DefaultOptions = options; - - // Add CultMath serialization support to Newtonsoft JSON - JsonConvert.DefaultSettings = () => new JsonSerializerSettings - { - Converters = new List - { - new MathJsonConverter() - } - }; - - registered = true; - } -} diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/RegisterResolver.cs.meta b/Assets/Scripts/ServerShared/CultCache/Serialization/RegisterResolver.cs.meta deleted file mode 100644 index 5249600aa..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/RegisterResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: cc638a5fae4350643871d45495a49643 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/TypeFormatterResolver.cs b/Assets/Scripts/ServerShared/CultCache/Serialization/TypeFormatterResolver.cs deleted file mode 100644 index 2f8860f64..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/TypeFormatterResolver.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using MessagePack; -using MessagePack.Formatters; - -public class TypeFormatter : MessagePack.Formatters.IMessagePackFormatter -{ - public static readonly IMessagePackFormatter Instance = new TypeFormatter(); - - private TypeFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Type value, MessagePackSerializerOptions options) - { - writer.Write(value == null ? "" : value.AssemblyQualifiedName); - } - - public Type Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - return null; //throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var assemblyQualifiedName = reader.ReadString(); - if (string.IsNullOrEmpty(assemblyQualifiedName)) return null; - - return Type.GetType(assemblyQualifiedName); - } -} - -public class TypeResolver : IFormatterResolver -{ - public static readonly TypeResolver Instance = new TypeResolver(); - - private TypeResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static object GetFormatterHelper(Type t) - { - if (t == typeof(Type)) - { - return TypeFormatter.Instance; - } - - return null; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - Formatter = (IMessagePackFormatter)GetFormatterHelper(typeof(T)); - } - } -} \ No newline at end of file diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/TypeFormatterResolver.cs.meta b/Assets/Scripts/ServerShared/CultCache/Serialization/TypeFormatterResolver.cs.meta deleted file mode 100644 index 0a739e995..000000000 --- a/Assets/Scripts/ServerShared/CultCache/Serialization/TypeFormatterResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ede4e7a24e20d134fb02868d010af83d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/Extensions.cs b/Assets/Scripts/ServerShared/Extensions.cs index 8118b1a11..a3a111556 100644 --- a/Assets/Scripts/ServerShared/Extensions.cs +++ b/Assets/Scripts/ServerShared/Extensions.cs @@ -23,6 +23,49 @@ public static class Extensions return baseType.GetInterfaces().Any(interfaceType.Equals); } + // Every loadable type assignable to this one. An assembly whose dependencies are missing (a Unity plugin + // referencing UnityEngine outside Unity) still yields the types that do load. + private static readonly Dictionary ChildClasses = new Dictionary(); + public static Type[] GetAllChildClasses(this Type type) + { + if (ChildClasses.TryGetValue(type, out var children)) return children; + return ChildClasses[type] = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => + { + try { return assembly.GetTypes(); } + catch (ReflectionTypeLoadException e) { return e.Types.Where(t => t != null); } + }).Where(type.IsAssignableFrom).ToArray(); + } + + public static string SplitCamelCase(this string str) => + Regex.Replace(Regex.Replace(str, @"(\P{Ll})(\P{Ll}\p{Ll})", "$1 $2"), @"(\p{Ll})(\P{Ll})", "$1 $2"); + + public static string FormatTypeName(this string typeName) => + (typeName.EndsWith("Data", StringComparison.InvariantCultureIgnoreCase) + ? typeName.Substring(0, typeName.Length - 4) + : typeName).SplitCamelCase(); + + public static T MaxBy(this IEnumerable items, Func selector) => items.Best(selector, 1); + public static T MinBy(this IEnumerable items, Func selector) => items.Best(selector, -1); + + private static T Best(this IEnumerable items, Func selector, int sign) + { + using var e = items.GetEnumerator(); + if (!e.MoveNext()) throw new InvalidOperationException("Empty input sequence"); + var best = e.Current; + var bestValue = selector(best); + var comparer = Comparer.Default; + while (e.MoveNext()) + { + var value = selector(e.Current); + if (comparer.Compare(value, bestValue) * sign > 0) + { + best = e.Current; + bestValue = value; + } + } + return best; + } + public static T[] WeightedRandomElements(this IEnumerable collection, ref Random random, Func weightFunction, int count) { var elements = collection as T[] ?? collection.ToArray(); diff --git a/Assets/Scripts/ServerShared/GlobalData.cs b/Assets/Scripts/ServerShared/GlobalData.cs index 9ff30376d..0b29aa7ad 100644 --- a/Assets/Scripts/ServerShared/GlobalData.cs +++ b/Assets/Scripts/ServerShared/GlobalData.cs @@ -11,73 +11,6 @@ using CultMath; using static CultMath.math; using static NoiseFbm; -[Inspectable, Serializable, DatabaseCategory("Galaxy"), MessagePackObject, JsonObject(MemberSerialization.OptIn)] -public class GalaxyMapLayerData : DatabaseEntry, INamedEntry -{ - [Inspectable, JsonProperty("coreBoost"), Key(1)] - public float CoreBoost = 1.05f; - - [Inspectable, JsonProperty("coreBoostOffset"), Key(2)] - public float CoreBoostOffset = .1f; - - [Inspectable, JsonProperty("coreBoostPower"), Key(3)] - public float CoreBoostPower = 2.25f; - - [Inspectable, JsonProperty("spokeScale"), Key(4)] - public float SpokeScale = 1; - - [Inspectable, JsonProperty("spokeOffset"), Key(5)] - public float SpokeOffset = 0; - - [Inspectable, JsonProperty("edgeReduction"), Key(6)] - public float EdgeReduction = 3; - - [Inspectable, JsonProperty("noiseOffset"), Key(7)] - public float NoiseOffset = 0; - - [Inspectable, JsonProperty("noiseAmplitude"), Key(8)] - public float NoiseAmplitude = 1.5f; - - [Inspectable, JsonProperty("noiseGain"), Key(9)] - public float NoiseGain = .7f; - - [Inspectable, JsonProperty("noiseLacunarity"), Key(10)] - public float NoiseLacunarity = 2; - - [Inspectable, JsonProperty("noiseOctaves"), Key(11)] - public int NoiseOctaves = 7; - - [Inspectable, JsonProperty("noiseFrequency"), Key(12)] - public float NoiseFrequency = 1; - - [Inspectable, JsonProperty("noisePosition"), Key(13)] - public float NoisePosition = 1337; - - [Inspectable, JsonProperty("name"), Key(14)] - public string Name; - - public float Evaluate(float2 uv, GalaxyShapeSettings settings) - { - float2 offset = -float2(.5f, .5f)+uv; - float circle = (.5f-length(offset))*2; - float angle = pow(length(offset)*2,settings.TwistExponent) * settings.Twist; - float2 t = float2(offset.x*cos(angle) - offset.y*sin(angle), offset.x*sin(angle) + offset.y*cos(angle)); - float atan = atan2(t.y,t.x); - float spokes = (sin(atan*settings.Arms) + SpokeOffset) * SpokeScale; - float noise = fBm(uv + float2(NoisePosition), NoiseOctaves, NoiseFrequency, NoiseOffset, NoiseAmplitude, NoiseLacunarity, NoiseGain); - float shape = lerp(spokes - EdgeReduction * length(offset), 1, pow(circle, CoreBoostPower) * CoreBoost) + CoreBoostOffset; - float gal = max(shape - noise * saturate(circle), 0); - - return gal; - } - - [IgnoreMember] public string EntryName - { - get => Name; - set => Name = value; - } -} - public static class NoiseFbm { public static float3 fBm3(float2 p, int octaves, float frequency, float offset, float amplitude, float lacunarity, float gain) diff --git a/Assets/Scripts/ServerShared/PlayerData.cs b/Assets/Scripts/ServerShared/PlayerData.cs deleted file mode 100644 index acb1ec534..000000000 --- a/Assets/Scripts/ServerShared/PlayerData.cs +++ /dev/null @@ -1,29 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ - -using System; -using MessagePack; -using Newtonsoft.Json; - -[DatabaseCategory("Users"), MessagePackObject, JsonObject(MemberSerialization.OptIn)] -public class PlayerData : DatabaseEntry, INamedEntry -{ - [JsonProperty("email"), Key(1)] - public string Email; - - [JsonProperty("password"), Key(2)] - public string Password; - - [JsonProperty("username"), Key(3)] - public string Username; - - [JsonProperty("corporation"), Key(4)] - public Guid Corporation; - - [IgnoreMember] public string EntryName - { - get => Username; - set => Username = value; - } -} \ No newline at end of file diff --git a/Assets/Scripts/ServerShared/PlayerData.cs.meta b/Assets/Scripts/ServerShared/PlayerData.cs.meta deleted file mode 100644 index c4469f21b..000000000 --- a/Assets/Scripts/ServerShared/PlayerData.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 6daac48880264dcc91c928f0dd9c2abb -timeCreated: 1591829144 \ No newline at end of file diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization.meta b/Assets/Scripts/ServerShared/Serialization.meta similarity index 100% rename from Assets/Scripts/ServerShared/CultCache/Serialization.meta rename to Assets/Scripts/ServerShared/Serialization.meta diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/MathFormatters.cs b/Assets/Scripts/ServerShared/Serialization/MathFormatters.cs similarity index 100% rename from Assets/Scripts/ServerShared/CultCache/Serialization/MathFormatters.cs rename to Assets/Scripts/ServerShared/Serialization/MathFormatters.cs diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/MathFormatters.cs.meta b/Assets/Scripts/ServerShared/Serialization/MathFormatters.cs.meta similarity index 100% rename from Assets/Scripts/ServerShared/CultCache/Serialization/MathFormatters.cs.meta rename to Assets/Scripts/ServerShared/Serialization/MathFormatters.cs.meta diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/MathResolver.cs b/Assets/Scripts/ServerShared/Serialization/MathResolver.cs similarity index 100% rename from Assets/Scripts/ServerShared/CultCache/Serialization/MathResolver.cs rename to Assets/Scripts/ServerShared/Serialization/MathResolver.cs diff --git a/Assets/Scripts/ServerShared/CultCache/Serialization/MathResolver.cs.meta b/Assets/Scripts/ServerShared/Serialization/MathResolver.cs.meta similarity index 100% rename from Assets/Scripts/ServerShared/CultCache/Serialization/MathResolver.cs.meta rename to Assets/Scripts/ServerShared/Serialization/MathResolver.cs.meta