Decompiled source of protobuf net v3.2.56
protobuf-net.Core.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using ProtoBuf.Internal; using ProtoBuf.Meta; using ProtoBuf.Serializers; using ProtoBuf.WellKnownTypes; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyFileVersion("3.2.56.57311")] [assembly: AssemblyInformationalVersion("3.2.56+dfdfce61a7")] [assembly: InternalsVisibleTo("protobuf-net.Test, PublicKey=002400000480000094000000060200000024000052534131000400000100010009ed9caa457bfc205716c3d4e8b255a63ddf71c9e53b1b5f574ab6ffdba11e80ab4b50be9c46d43b75206280070ddba67bd4c830f93f0317504a76ba6a48243c36d2590695991164592767a7bbc4453b34694e31e20815a096e4483605139a32a76ec2fef196507487329c12047bf6a68bca8ee9354155f4d01daf6eec5ff6bc")] [assembly: InternalsVisibleTo("protobuf-net, PublicKey=002400000480000094000000060200000024000052534131000400000100010009ed9caa457bfc205716c3d4e8b255a63ddf71c9e53b1b5f574ab6ffdba11e80ab4b50be9c46d43b75206280070ddba67bd4c830f93f0317504a76ba6a48243c36d2590695991164592767a7bbc4453b34694e31e20815a096e4483605139a32a76ec2fef196507487329c12047bf6a68bca8ee9354155f4d01daf6eec5ff6bc")] [assembly: InternalsVisibleTo("Benchmark, PublicKey=002400000480000094000000060200000024000052534131000400000100010009ed9caa457bfc205716c3d4e8b255a63ddf71c9e53b1b5f574ab6ffdba11e80ab4b50be9c46d43b75206280070ddba67bd4c830f93f0317504a76ba6a48243c36d2590695991164592767a7bbc4453b34694e31e20815a096e4483605139a32a76ec2fef196507487329c12047bf6a68bca8ee9354155f4d01daf6eec5ff6bc")] [assembly: InternalsVisibleTo("protobuf-net.MessagePipes, PublicKey=002400000480000094000000060200000024000052534131000400000100010009ed9caa457bfc205716c3d4e8b255a63ddf71c9e53b1b5f574ab6ffdba11e80ab4b50be9c46d43b75206280070ddba67bd4c830f93f0317504a76ba6a48243c36d2590695991164592767a7bbc4453b34694e31e20815a096e4483605139a32a76ec2fef196507487329c12047bf6a68bca8ee9354155f4d01daf6eec5ff6bc")] [assembly: InternalsVisibleTo("protobuf-net.ServiceModel, PublicKey=002400000480000094000000060200000024000052534131000400000100010009ed9caa457bfc205716c3d4e8b255a63ddf71c9e53b1b5f574ab6ffdba11e80ab4b50be9c46d43b75206280070ddba67bd4c830f93f0317504a76ba6a48243c36d2590695991164592767a7bbc4453b34694e31e20815a096e4483605139a32a76ec2fef196507487329c12047bf6a68bca8ee9354155f4d01daf6eec5ff6bc")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Marc Gravell")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("See https://github.com/protobuf-net/protobuf-net")] [assembly: AssemblyDescription("Provides simple access to fast and efficient \"Protocol Buffers\" serialization from .NET applications")] [assembly: AssemblyProduct("protobuf-net (netstandard2.1)")] [assembly: AssemblyTitle("protobuf-net.Core")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/protobuf-net/protobuf-net")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("3.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsUnmanagedAttribute : Attribute { } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } [GeneratedCode("Nerdbank.GitVersioning.Tasks", "3.7.115.8147")] [ExcludeFromCodeCoverage] internal static class ThisAssembly { internal const string AssemblyConfiguration = "Release"; internal const string AssemblyFileVersion = "3.2.56.57311"; internal const string AssemblyInformationalVersion = "3.2.56+dfdfce61a7"; internal const string AssemblyName = "protobuf-net.Core"; internal const string AssemblyTitle = "protobuf-net.Core"; internal const string AssemblyVersion = "3.0.0.0"; internal static readonly DateTime GitCommitAuthorDate = new DateTime(638895502940000000L, DateTimeKind.Utc); internal static readonly DateTime GitCommitDate = new DateTime(638895502940000000L, DateTimeKind.Utc); internal const string GitCommitId = "dfdfce61a739cfd76f05fcdacf8a4b3b9e94e684"; internal const bool IsPrerelease = false; internal const bool IsPublicRelease = true; internal const string PublicKey = "002400000480000094000000060200000024000052534131000400000100010009ed9caa457bfc205716c3d4e8b255a63ddf71c9e53b1b5f574ab6ffdba11e80ab4b50be9c46d43b75206280070ddba67bd4c830f93f0317504a76ba6a48243c36d2590695991164592767a7bbc4453b34694e31e20815a096e4483605139a32a76ec2fef196507487329c12047bf6a68bca8ee9354155f4d01daf6eec5ff6bc"; internal const string PublicKeyToken = "257b51d87d2e4d67"; internal const string RootNamespace = "ProtoBuf"; } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)] internal sealed class DynamicallyAccessedMembersAttribute : Attribute { public DynamicallyAccessedMemberTypes MemberTypes { get; } public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) { MemberTypes = memberTypes; } } [Flags] internal enum DynamicallyAccessedMemberTypes { None = 0, PublicParameterlessConstructor = 1, PublicConstructors = 3, NonPublicConstructors = 4, PublicMethods = 8, NonPublicMethods = 0x10, PublicFields = 0x20, NonPublicFields = 0x40, PublicNestedTypes = 0x80, NonPublicNestedTypes = 0x100, PublicProperties = 0x200, NonPublicProperties = 0x400, PublicEvents = 0x800, NonPublicEvents = 0x1000, All = -1 } } namespace ProtoBuf { internal enum TimeSpanScale { Days = 0, Hours = 1, Minutes = 2, Seconds = 3, Milliseconds = 4, Ticks = 5, MinMax = 15 } public static class BclHelpers { internal static readonly DateTime[] EpochOrigin = new DateTime[3] { new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local) }; private const int MAX_DECIMAL_BYTES = 32; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static object GetUninitializedObject(Type type) { return FormatterServices.GetUninitializedObject(type); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteTimeSpan(TimeSpan timeSpan, ProtoWriter dest) { ProtoWriter.State state = dest.DefaultState(); WriteTimeSpanImpl(ref state, timeSpan, DateTimeKind.Unspecified); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteTimeSpan(ref ProtoWriter.State state, TimeSpan value) { WriteTimeSpanImpl(ref state, value, DateTimeKind.Unspecified); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteTimeSpanImpl(ref ProtoWriter.State state, TimeSpan timeSpan, DateTimeKind kind) { switch (state.WireType) { case WireType.String: case WireType.StartGroup: { PrimaryTypeProvider.ScaledTicks value = new PrimaryTypeProvider.ScaledTicks(timeSpan, kind); state.WriteMessage(SerializerFeatures.OptionSkipRecursionCheck, value, SerializerCache<PrimaryTypeProvider>.InstanceField); break; } case WireType.Fixed64: state.WriteInt64(timeSpan.Ticks); break; default: ThrowHelper.ThrowProtoException("Unexpected wire-type: " + state.WireType); break; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static TimeSpan ReadTimeSpan(ProtoReader source) { ProtoReader.State state = source.DefaultState(); return ReadTimeSpan(ref state); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static TimeSpan ReadTimeSpan(ref ProtoReader.State state) { switch (state.WireType) { case WireType.String: case WireType.StartGroup: return state.ReadMessage(SerializerFeatures.CategoryRepeated, default(PrimaryTypeProvider.ScaledTicks), SerializerCache<PrimaryTypeProvider>.InstanceField).ToTimeSpan(); case WireType.Fixed64: { long num = state.ReadInt64(); return num switch { long.MinValue => TimeSpan.MinValue, long.MaxValue => TimeSpan.MaxValue, _ => TimeSpan.FromTicks(num), }; } default: ThrowHelper.ThrowProtoException($"Unexpected wire-type: {state.WireType}"); return default(TimeSpan); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static TimeSpan ReadDuration(ProtoReader source) { ProtoReader.State state = source.DefaultState(); return ReadDuration(ref state); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static TimeSpan ReadDuration(ref ProtoReader.State state) { return state.ReadMessage(SerializerFeatures.CategoryRepeated, default(Duration), SerializerCache<PrimaryTypeProvider>.InstanceField); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteDuration(TimeSpan value, ProtoWriter dest) { ProtoWriter.State state = dest.DefaultState(); WriteDuration(ref state, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteDuration(ref ProtoWriter.State state, TimeSpan value) { state.WriteMessage(SerializerFeatures.OptionSkipRecursionCheck, (Duration)value, (ISerializer<Duration>)SerializerCache<PrimaryTypeProvider>.InstanceField); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static DateTime ReadTimestamp(ProtoReader source) { ProtoReader.State state = source.DefaultState(); return ReadTimestamp(ref state); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static DateTime ReadTimestamp(ref ProtoReader.State state) { return state.ReadMessage(SerializerFeatures.CategoryRepeated, default(Timestamp), SerializerCache<PrimaryTypeProvider>.InstanceField); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteTimestamp(DateTime value, ProtoWriter dest) { ProtoWriter.State state = dest.DefaultState(); WriteTimestamp(ref state, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteTimestamp(ref ProtoWriter.State state, DateTime value) { state.WriteMessage(SerializerFeatures.OptionSkipRecursionCheck, (Timestamp)value, (ISerializer<Timestamp>)SerializerCache<PrimaryTypeProvider>.InstanceField); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static DateTime ReadDateTime(ProtoReader source) { ProtoReader.State state = source.DefaultState(); return ReadDateTime(ref state); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static DateTime ReadDateTime(ref ProtoReader.State state) { switch (state.WireType) { case WireType.String: case WireType.StartGroup: return state.ReadMessage(SerializerFeatures.CategoryRepeated, default(PrimaryTypeProvider.ScaledTicks), SerializerCache<PrimaryTypeProvider>.InstanceField).ToDateTime(); case WireType.Fixed64: { long num = state.ReadInt64(); return num switch { long.MinValue => DateTime.MinValue, long.MaxValue => DateTime.MaxValue, _ => EpochOrigin[0].AddTicks(num), }; } default: ThrowHelper.ThrowProtoException($"Unexpected wire-type: {state.WireType}"); return default(DateTime); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteDateTime(DateTime value, ProtoWriter dest) { ProtoWriter.State state = dest.DefaultState(); WriteDateTimeImpl(ref state, value, includeKind: false); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteDateTime(ref ProtoWriter.State state, DateTime value) { WriteDateTimeImpl(ref state, value, includeKind: false); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteDateTimeWithKind(DateTime value, ProtoWriter dest) { ProtoWriter.State state = dest.DefaultState(); WriteDateTimeImpl(ref state, value, includeKind: true); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteDateTimeWithKind(ref ProtoWriter.State state, DateTime value) { WriteDateTimeImpl(ref state, value, includeKind: true); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteDateTimeImpl(ref ProtoWriter.State state, DateTime value, bool includeKind) { WireType wireType = state.WireType; TimeSpan timeSpan; if ((uint)(wireType - 2) <= 1u) { if (value == DateTime.MaxValue) { timeSpan = TimeSpan.MaxValue; includeKind = false; } else if (value == DateTime.MinValue) { timeSpan = TimeSpan.MinValue; includeKind = false; } else { timeSpan = value - EpochOrigin[0]; } } else { timeSpan = value - EpochOrigin[0]; } WriteTimeSpanImpl(ref state, timeSpan, includeKind ? value.Kind : DateTimeKind.Unspecified); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal ReadDecimal(ProtoReader reader) { ProtoReader.State state = reader.DefaultState(); return ReadDecimal(ref state); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal ReadDecimal(ref ProtoReader.State state) { return state.ReadMessage(SerializerFeatures.CategoryRepeated, 0m, SerializerCache<PrimaryTypeProvider>.InstanceField); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static decimal ReadDecimalString(ref ProtoReader.State state) { byte* ptr = stackalloc byte[32]; Span<byte> span = state.ReadBytes(new Span<byte>(ptr, 32)); if (!Utf8Parser.TryParse((ReadOnlySpan<byte>)span, out decimal value, out int bytesConsumed, '\0') || bytesConsumed != span.Length) { ThrowHelper.ThrowInvalidOperationException("Unable to parse decimal: '" + Encoding.UTF8.GetString(ptr, span.Length) + "'"); } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteDecimal(decimal value, ProtoWriter writer) { ProtoWriter.State state = writer.DefaultState(); WriteDecimal(ref state, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteDecimal(ref ProtoWriter.State state, decimal value) { state.WriteMessage(SerializerFeatures.OptionSkipRecursionCheck, value, SerializerCache<PrimaryTypeProvider>.InstanceField); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteDecimalString(ref ProtoWriter.State state, decimal value) { byte[] array = ArrayPool<byte>.Shared.Rent(32); try { if (!Utf8Formatter.TryFormat(value, array, out var bytesWritten)) { ThrowHelper.ThrowInvalidOperationException($"Unable to format decimal: '{value}'"); } state.WriteBytes(new ReadOnlyMemory<byte>(array, 0, bytesWritten)); } finally { ArrayPool<byte>.Shared.Return(array); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteGuid(Guid value, ProtoWriter dest) { ProtoWriter.State state = dest.DefaultState(); WriteGuid(ref state, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteGuid(ref ProtoWriter.State state, Guid value) { state.WriteMessage(SerializerFeatures.OptionSkipRecursionCheck, value, SerializerCache<PrimaryTypeProvider>.InstanceField); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteGuidBytes(ref ProtoWriter.State state, Guid value) { GuidHelper.Write(ref state, in value, asBytes: true); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteGuidString(ref ProtoWriter.State state, Guid value) { GuidHelper.Write(ref state, in value, asBytes: false); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Guid ReadGuid(ProtoReader source) { ProtoReader.State state = source.DefaultState(); return ReadGuid(ref state); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Guid ReadGuid(ref ProtoReader.State state) { return state.ReadMessage(SerializerFeatures.CategoryRepeated, default(Guid), SerializerCache<PrimaryTypeProvider>.InstanceField); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Guid ReadGuidBytes(ref ProtoReader.State state) { return GuidHelper.Read(ref state); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Guid ReadGuidString(ref ProtoReader.State state) { return GuidHelper.Read(ref state); } } public sealed class BufferExtension : IExtension, IExtensionResettable { private ArraySegment<byte> _buffer; internal Type Type { get; private set; } internal BufferExtension Tail { get; private set; } internal void SetTail(Type type, BufferExtension tail) { Type = type; Tail = tail; } void IExtensionResettable.Reset() { _buffer = default(ArraySegment<byte>); } int IExtension.GetLength() { return _buffer.Count; } Stream IExtension.BeginAppend() { return new MemoryStream(); } void IExtension.EndAppend(Stream stream, bool commit) { using (stream) { if (!commit || !(stream is MemoryStream memoryStream) || !memoryStream.TryGetBuffer(out var buffer) || buffer.Count == 0) { return; } if (_buffer.Count == 0) { _buffer = buffer; return; } int num = _buffer.Offset + _buffer.Count; int num2 = _buffer.Array.Length - num; if (num2 >= buffer.Count) { Buffer.BlockCopy(buffer.Array, buffer.Offset, _buffer.Array, num, buffer.Count); _buffer = new ArraySegment<byte>(_buffer.Array, _buffer.Offset, num + buffer.Count); return; } byte[] array = new byte[_buffer.Count + buffer.Count]; Buffer.BlockCopy(_buffer.Array, _buffer.Offset, array, 0, _buffer.Count); Buffer.BlockCopy(buffer.Array, buffer.Offset, array, _buffer.Count, buffer.Count); _buffer = new ArraySegment<byte>(array, 0, _buffer.Count + buffer.Count); } } Stream IExtension.BeginQuery() { if (_buffer.Count != 0) { return new MemoryStream(_buffer.Array, _buffer.Offset, _buffer.Count, writable: false, publiclyVisible: true); } return Stream.Null; } void IExtension.EndQuery(Stream stream) { using (stream) { } } } internal static class BufferPool { private static readonly ArrayPool<byte> _pool = ArrayPool<byte>.Shared; internal const int BUFFER_LENGTH = 1024; private const int MaxByteArraySize = 2147483591; internal static byte[] GetBuffer() { return GetBuffer(1024); } internal static byte[] GetBuffer(int minSize) { byte[] cachedBuffer = GetCachedBuffer(minSize); return cachedBuffer ?? new byte[minSize]; } internal static byte[] GetCachedBuffer(int minSize) { return _pool.Rent(minSize); } internal static void ResizeAndFlushLeft(ref byte[] buffer, int toFitAtLeastBytes, int copyFromIndex, int copyBytes) { int num = buffer.Length * 2; if (num < 0) { num = 2147483591; } if (num < toFitAtLeastBytes) { num = toFitAtLeastBytes; } if (copyBytes == 0) { ReleaseBufferToPool(ref buffer); } byte[] array = GetCachedBuffer(num) ?? new byte[num]; if (copyBytes > 0) { Buffer.BlockCopy(buffer, copyFromIndex, array, 0, copyBytes); ReleaseBufferToPool(ref buffer); } buffer = array; } internal static void ReleaseBufferToPool(ref byte[] buffer) { byte[] array = buffer; buffer = null; if (array != null) { _pool.Return(array); } } } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] [ImmutableObject(true)] public sealed class ProtoBeforeSerializationAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] [ImmutableObject(true)] public sealed class ProtoAfterSerializationAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] [ImmutableObject(true)] public sealed class ProtoBeforeDeserializationAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] [ImmutableObject(true)] public sealed class ProtoAfterDeserializationAttribute : Attribute { } public enum CompatibilityLevel { NotSpecified = 0, Level200 = 200, Level240 = 240, Level300 = 300 } [ImmutableObject(true)] [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface, AllowMultiple = false, Inherited = true)] public sealed class CompatibilityLevelAttribute : Attribute { public CompatibilityLevel Level { get; } public CompatibilityLevelAttribute(CompatibilityLevel level) { Level = level; } internal static void AssertValid(CompatibilityLevel compatibilityLevel) { switch (compatibilityLevel) { case CompatibilityLevel.NotSpecified: case CompatibilityLevel.Level200: case CompatibilityLevel.Level240: case CompatibilityLevel.Level300: return; } Throw(compatibilityLevel); static void Throw(CompatibilityLevel compatibilityLevel2) { throw new ArgumentOutOfRangeException("compatibilityLevel", $"Compatiblity level '{compatibilityLevel2}' is not recognized."); } } } public enum DataFormat { Default, ZigZag, TwosComplement, FixedSize, Group, [Obsolete("This option is replaced with CompatibilityLevel, and is only used for Level200, where it changes this field to Level240", false)] WellKnown } [Serializable] [StructLayout(LayoutKind.Auto)] public readonly struct DiscriminatedUnionObject : ISerializable { public readonly object Object; public int Discriminator { get; } public bool Is(int discriminator) { return Discriminator == discriminator; } public DiscriminatedUnionObject(int discriminator, object value) { Discriminator = discriminator; Object = value; } public static void Reset(ref DiscriminatedUnionObject value, int discriminator) { if (value.Discriminator == discriminator) { value = default(DiscriminatedUnionObject); } } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (Discriminator != 0) { info.AddValue("d", Discriminator); } if (Object != null) { info.AddValue("o", Object); } } private DiscriminatedUnionObject(SerializationInfo info, StreamingContext context) { this = default(DiscriminatedUnionObject); SerializationInfoEnumerator enumerator = info.GetEnumerator(); while (enumerator.MoveNext()) { SerializationEntry current = enumerator.Current; string name = current.Name; if (!(name == "d")) { if (name == "o") { Object = current.Value; } } else { Discriminator = (int)current.Value; } } } } [Serializable] [StructLayout(LayoutKind.Explicit)] public readonly struct DiscriminatedUnion64 : ISerializable { [FieldOffset(0)] private readonly int _discriminator; [FieldOffset(8)] public readonly long Int64; [FieldOffset(8)] public readonly ulong UInt64; [FieldOffset(8)] public readonly int Int32; [FieldOffset(8)] public readonly uint UInt32; [FieldOffset(8)] public readonly bool Boolean; [FieldOffset(8)] public readonly float Single; [FieldOffset(8)] public readonly double Double; [FieldOffset(8)] public readonly DateTime DateTime; [FieldOffset(8)] public readonly TimeSpan TimeSpan; public int Discriminator => _discriminator; private DiscriminatedUnion64(int discriminator) { this = default(DiscriminatedUnion64); _discriminator = discriminator; } public bool Is(int discriminator) { return _discriminator == discriminator; } public DiscriminatedUnion64(int discriminator, long value) : this(discriminator) { Int64 = value; } public DiscriminatedUnion64(int discriminator, int value) : this(discriminator) { Int32 = value; } public DiscriminatedUnion64(int discriminator, ulong value) : this(discriminator) { UInt64 = value; } public DiscriminatedUnion64(int discriminator, uint value) : this(discriminator) { UInt32 = value; } public DiscriminatedUnion64(int discriminator, float value) : this(discriminator) { Single = value; } public DiscriminatedUnion64(int discriminator, double value) : this(discriminator) { Double = value; } public DiscriminatedUnion64(int discriminator, bool value) : this(discriminator) { Boolean = value; } public DiscriminatedUnion64(int discriminator, DateTime? value) : this(value.HasValue ? discriminator : 0) { DateTime = value.GetValueOrDefault(); } public DiscriminatedUnion64(int discriminator, TimeSpan? value) : this(value.HasValue ? discriminator : 0) { TimeSpan = value.GetValueOrDefault(); } public static void Reset(ref DiscriminatedUnion64 value, int discriminator) { if (value.Discriminator == discriminator) { value = default(DiscriminatedUnion64); } } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (_discriminator != 0) { info.AddValue("d", _discriminator); } if (Int64 != 0L) { info.AddValue("i", Int64); } } private DiscriminatedUnion64(SerializationInfo info, StreamingContext context) { this = default(DiscriminatedUnion64); SerializationInfoEnumerator enumerator = info.GetEnumerator(); while (enumerator.MoveNext()) { SerializationEntry current = enumerator.Current; string name = current.Name; if (!(name == "d")) { if (name == "i") { Int64 = (long)current.Value; } } else { _discriminator = (int)current.Value; } } } } [Serializable] [StructLayout(LayoutKind.Explicit)] public readonly struct DiscriminatedUnion128Object : ISerializable { [FieldOffset(0)] private readonly int _discriminator; [FieldOffset(8)] public readonly long Int64; [FieldOffset(8)] public readonly ulong UInt64; [FieldOffset(8)] public readonly int Int32; [FieldOffset(8)] public readonly uint UInt32; [FieldOffset(8)] public readonly bool Boolean; [FieldOffset(8)] public readonly float Single; [FieldOffset(8)] public readonly double Double; [FieldOffset(8)] public readonly DateTime DateTime; [FieldOffset(8)] public readonly TimeSpan TimeSpan; [FieldOffset(8)] public readonly Guid Guid; [FieldOffset(24)] public readonly object Object; [FieldOffset(8)] private readonly long _lo; [FieldOffset(16)] private readonly long _hi; public int Discriminator => _discriminator; private DiscriminatedUnion128Object(int discriminator) { this = default(DiscriminatedUnion128Object); _discriminator = discriminator; } public bool Is(int discriminator) { return _discriminator == discriminator; } public DiscriminatedUnion128Object(int discriminator, long value) : this(discriminator) { Int64 = value; } public DiscriminatedUnion128Object(int discriminator, int value) : this(discriminator) { Int32 = value; } public DiscriminatedUnion128Object(int discriminator, ulong value) : this(discriminator) { UInt64 = value; } public DiscriminatedUnion128Object(int discriminator, uint value) : this(discriminator) { UInt32 = value; } public DiscriminatedUnion128Object(int discriminator, float value) : this(discriminator) { Single = value; } public DiscriminatedUnion128Object(int discriminator, double value) : this(discriminator) { Double = value; } public DiscriminatedUnion128Object(int discriminator, bool value) : this(discriminator) { Boolean = value; } public DiscriminatedUnion128Object(int discriminator, object value) : this((value != null) ? discriminator : 0) { Object = value; } public DiscriminatedUnion128Object(int discriminator, DateTime? value) : this(value.HasValue ? discriminator : 0) { DateTime = value.GetValueOrDefault(); } public DiscriminatedUnion128Object(int discriminator, TimeSpan? value) : this(value.HasValue ? discriminator : 0) { TimeSpan = value.GetValueOrDefault(); } public DiscriminatedUnion128Object(int discriminator, Guid? value) : this(value.HasValue ? discriminator : 0) { Guid = value.GetValueOrDefault(); } public static void Reset(ref DiscriminatedUnion128Object value, int discriminator) { if (value.Discriminator == discriminator) { value = default(DiscriminatedUnion128Object); } } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (_discriminator != 0) { info.AddValue("d", _discriminator); } if (_lo != 0L) { info.AddValue("l", _lo); } if (_hi != 0L) { info.AddValue("h", _hi); } if (Object != null) { info.AddValue("o", Object); } } private DiscriminatedUnion128Object(SerializationInfo info, StreamingContext context) { this = default(DiscriminatedUnion128Object); SerializationInfoEnumerator enumerator = info.GetEnumerator(); while (enumerator.MoveNext()) { SerializationEntry current = enumerator.Current; switch (current.Name) { case "d": _discriminator = (int)current.Value; break; case "l": _lo = (long)current.Value; break; case "h": _hi = (long)current.Value; break; case "o": Object = current.Value; break; } } } } [Serializable] [StructLayout(LayoutKind.Explicit)] public readonly struct DiscriminatedUnion128 : ISerializable { [FieldOffset(0)] private readonly int _discriminator; [FieldOffset(8)] public readonly long Int64; [FieldOffset(8)] public readonly ulong UInt64; [FieldOffset(8)] public readonly int Int32; [FieldOffset(8)] public readonly uint UInt32; [FieldOffset(8)] public readonly bool Boolean; [FieldOffset(8)] public readonly float Single; [FieldOffset(8)] public readonly double Double; [FieldOffset(8)] public readonly DateTime DateTime; [FieldOffset(8)] public readonly TimeSpan TimeSpan; [FieldOffset(8)] public readonly Guid Guid; [FieldOffset(8)] private readonly long _lo; [FieldOffset(16)] private readonly long _hi; public int Discriminator => _discriminator; private DiscriminatedUnion128(int discriminator) { this = default(DiscriminatedUnion128); _discriminator = discriminator; } public bool Is(int discriminator) { return _discriminator == discriminator; } public DiscriminatedUnion128(int discriminator, long value) : this(discriminator) { Int64 = value; } public DiscriminatedUnion128(int discriminator, int value) : this(discriminator) { Int32 = value; } public DiscriminatedUnion128(int discriminator, ulong value) : this(discriminator) { UInt64 = value; } public DiscriminatedUnion128(int discriminator, uint value) : this(discriminator) { UInt32 = value; } public DiscriminatedUnion128(int discriminator, float value) : this(discriminator) { Single = value; } public DiscriminatedUnion128(int discriminator, double value) : this(discriminator) { Double = value; } public DiscriminatedUnion128(int discriminator, bool value) : this(discriminator) { Boolean = value; } public DiscriminatedUnion128(int discriminator, DateTime? value) : this(value.HasValue ? discriminator : 0) { DateTime = value.GetValueOrDefault(); } public DiscriminatedUnion128(int discriminator, TimeSpan? value) : this(value.HasValue ? discriminator : 0) { TimeSpan = value.GetValueOrDefault(); } public DiscriminatedUnion128(int discriminator, Guid? value) : this(value.HasValue ? discriminator : 0) { Guid = value.GetValueOrDefault(); } public static void Reset(ref DiscriminatedUnion128 value, int discriminator) { if (value.Discriminator == discriminator) { value = default(DiscriminatedUnion128); } } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (_discriminator != 0) { info.AddValue("d", _discriminator); } if (_lo != 0L) { info.AddValue("l", _lo); } if (_hi != 0L) { info.AddValue("h", _hi); } } private DiscriminatedUnion128(SerializationInfo info, StreamingContext context) { this = default(DiscriminatedUnion128); SerializationInfoEnumerator enumerator = info.GetEnumerator(); while (enumerator.MoveNext()) { SerializationEntry current = enumerator.Current; switch (current.Name) { case "d": _discriminator = (int)current.Value; break; case "l": _lo = (long)current.Value; break; case "h": _hi = (long)current.Value; break; } } } } [Serializable] [StructLayout(LayoutKind.Explicit)] public readonly struct DiscriminatedUnion64Object : ISerializable { [FieldOffset(0)] private readonly int _discriminator; [FieldOffset(8)] public readonly long Int64; [FieldOffset(8)] public readonly ulong UInt64; [FieldOffset(8)] public readonly int Int32; [FieldOffset(8)] public readonly uint UInt32; [FieldOffset(8)] public readonly bool Boolean; [FieldOffset(8)] public readonly float Single; [FieldOffset(8)] public readonly double Double; [FieldOffset(8)] public readonly DateTime DateTime; [FieldOffset(8)] public readonly TimeSpan TimeSpan; [FieldOffset(16)] public readonly object Object; public int Discriminator => _discriminator; private DiscriminatedUnion64Object(int discriminator) { this = default(DiscriminatedUnion64Object); _discriminator = discriminator; } public bool Is(int discriminator) { return _discriminator == discriminator; } public DiscriminatedUnion64Object(int discriminator, long value) : this(discriminator) { Int64 = value; } public DiscriminatedUnion64Object(int discriminator, int value) : this(discriminator) { Int32 = value; } public DiscriminatedUnion64Object(int discriminator, ulong value) : this(discriminator) { UInt64 = value; } public DiscriminatedUnion64Object(int discriminator, uint value) : this(discriminator) { UInt32 = value; } public DiscriminatedUnion64Object(int discriminator, float value) : this(discriminator) { Single = value; } public DiscriminatedUnion64Object(int discriminator, double value) : this(discriminator) { Double = value; } public DiscriminatedUnion64Object(int discriminator, bool value) : this(discriminator) { Boolean = value; } public DiscriminatedUnion64Object(int discriminator, object value) : this((value != null) ? discriminator : 0) { Object = value; } public DiscriminatedUnion64Object(int discriminator, DateTime? value) : this(value.HasValue ? discriminator : 0) { DateTime = value.GetValueOrDefault(); } public DiscriminatedUnion64Object(int discriminator, TimeSpan? value) : this(value.HasValue ? discriminator : 0) { TimeSpan = value.GetValueOrDefault(); } public static void Reset(ref DiscriminatedUnion64Object value, int discriminator) { if (value.Discriminator == discriminator) { value = default(DiscriminatedUnion64Object); } } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (_discriminator != 0) { info.AddValue("d", _discriminator); } if (Int64 != 0L) { info.AddValue("i", Int64); } if (Object != null) { info.AddValue("o", Object); } } private DiscriminatedUnion64Object(SerializationInfo info, StreamingContext context) { this = default(DiscriminatedUnion64Object); SerializationInfoEnumerator enumerator = info.GetEnumerator(); while (enumerator.MoveNext()) { SerializationEntry current = enumerator.Current; switch (current.Name) { case "d": _discriminator = (int)current.Value; break; case "i": Int64 = (long)current.Value; break; case "o": Object = current.Value; break; } } } } [Serializable] [StructLayout(LayoutKind.Explicit)] public readonly struct DiscriminatedUnion32 : ISerializable { [FieldOffset(0)] private readonly int _discriminator; [FieldOffset(4)] public readonly int Int32; [FieldOffset(4)] public readonly uint UInt32; [FieldOffset(4)] public readonly bool Boolean; [FieldOffset(4)] public readonly float Single; public int Discriminator => _discriminator; private DiscriminatedUnion32(int discriminator) { this = default(DiscriminatedUnion32); _discriminator = discriminator; } public bool Is(int discriminator) { return _discriminator == discriminator; } public DiscriminatedUnion32(int discriminator, int value) : this(discriminator) { Int32 = value; } public DiscriminatedUnion32(int discriminator, uint value) : this(discriminator) { UInt32 = value; } public DiscriminatedUnion32(int discriminator, float value) : this(discriminator) { Single = value; } public DiscriminatedUnion32(int discriminator, bool value) : this(discriminator) { Boolean = value; } public static void Reset(ref DiscriminatedUnion32 value, int discriminator) { if (value.Discriminator == discriminator) { value = default(DiscriminatedUnion32); } } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (_discriminator != 0) { info.AddValue("d", _discriminator); } if (Int32 != 0) { info.AddValue("i", Int32); } } private DiscriminatedUnion32(SerializationInfo info, StreamingContext context) { this = default(DiscriminatedUnion32); SerializationInfoEnumerator enumerator = info.GetEnumerator(); while (enumerator.MoveNext()) { SerializationEntry current = enumerator.Current; string name = current.Name; if (!(name == "d")) { if (name == "i") { Int32 = (int)current.Value; } } else { _discriminator = (int)current.Value; } } } } [Serializable] [StructLayout(LayoutKind.Explicit)] public readonly struct DiscriminatedUnion32Object : ISerializable { [FieldOffset(0)] private readonly int _discriminator; [FieldOffset(4)] public readonly int Int32; [FieldOffset(4)] public readonly uint UInt32; [FieldOffset(4)] public readonly bool Boolean; [FieldOffset(4)] public readonly float Single; [FieldOffset(8)] public readonly object Object; public int Discriminator => _discriminator; private DiscriminatedUnion32Object(int discriminator) { this = default(DiscriminatedUnion32Object); _discriminator = discriminator; } public bool Is(int discriminator) { return _discriminator == discriminator; } public DiscriminatedUnion32Object(int discriminator, int value) : this(discriminator) { Int32 = value; } public DiscriminatedUnion32Object(int discriminator, uint value) : this(discriminator) { UInt32 = value; } public DiscriminatedUnion32Object(int discriminator, float value) : this(discriminator) { Single = value; } public DiscriminatedUnion32Object(int discriminator, bool value) : this(discriminator) { Boolean = value; } public DiscriminatedUnion32Object(int discriminator, object value) : this((value != null) ? discriminator : 0) { Object = value; } public static void Reset(ref DiscriminatedUnion32Object value, int discriminator) { if (value.Discriminator == discriminator) { value = default(DiscriminatedUnion32Object); } } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (_discriminator != 0) { info.AddValue("d", _discriminator); } if (Int32 != 0) { info.AddValue("i", Int32); } if (Object != null) { info.AddValue("o", Object); } } private DiscriminatedUnion32Object(SerializationInfo info, StreamingContext context) { this = default(DiscriminatedUnion32Object); SerializationInfoEnumerator enumerator = info.GetEnumerator(); while (enumerator.MoveNext()) { SerializationEntry current = enumerator.Current; switch (current.Name) { case "d": _discriminator = (int)current.Value; break; case "i": Int32 = (int)current.Value; break; case "o": Object = current.Value; break; } } } } public abstract class Extensible : ITypedExtensible, IExtensible { private IExtension extensionObject; IExtension IExtensible.GetExtensionObject(bool createIfMissing) { return GetExtensionObject(createIfMissing); } IExtension ITypedExtensible.GetExtensionObject(Type type, bool createIfMissing) { if ((object)type != GetType()) { return GetExtensionObject(ref extensionObject, type, createIfMissing); } return GetExtensionObject(createIfMissing); } [Obsolete("This API is considered, and may no longer be used in all scenarios (in particular when inheritance is involved); it is not recommended to rely on this API")] protected virtual IExtension GetExtensionObject(bool createIfMissing) { return GetExtensionObject(ref extensionObject, GetType(), createIfMissing); } public static IExtension GetExtensionObject(ref IExtension extensionObject, Type type, bool createIfMissing) { if ((object)type == null) { ThrowHelper.ThrowArgumentNullException("type"); } BufferExtension bufferExtension = extensionObject as BufferExtension; BufferExtension bufferExtension2 = bufferExtension; if (bufferExtension == null) { if (extensionObject != null) { ThrowHelper.ThrowNotSupportedException("Custom extension implementations should not be passed to GetExtensionObject"); } } else { while (bufferExtension2 != null) { Type type2 = bufferExtension2.Type; if ((object)type2 == null) { ThrowHelper.ThrowInvalidOperationException("Typed and untyped extension data cannot be mixed"); } if ((object)type2 == type) { return bufferExtension2; } bufferExtension2 = bufferExtension2.Tail; } } if (createIfMissing) { BufferExtension bufferExtension3 = new BufferExtension(); bufferExtension3.SetTail(type, bufferExtension); bufferExtension2 = (BufferExtension)(extensionObject = bufferExtension3); } return bufferExtension2; } public static IExtension GetExtensionObject(ref IExtension extensionObject, bool createIfMissing) { if (extensionObject == null) { if (createIfMissing) { extensionObject = new BufferExtension(); } } else if (extensionObject is BufferExtension { Type: not null }) { ThrowHelper.ThrowInvalidOperationException("Typed and untyped extension data cannot be mixed"); } return extensionObject; } public static void AppendValue<TValue>(IExtensible instance, int tag, TValue value) { ExtensibleUtil.AppendExtendValue(null, instance, tag, DataFormat.Default, value); } public static void AppendValue<TValue>(IExtensible instance, int tag, DataFormat format, TValue value) { ExtensibleUtil.AppendExtendValue(null, instance, tag, format, value); } public static void AppendValue<TValue>(TypeModel model, IExtensible instance, int tag, TValue value, DataFormat format = DataFormat.Default) { ExtensibleUtil.AppendExtendValue(model, instance, tag, format, value); } public static TValue GetValue<TValue>(IExtensible instance, int tag) { return GetValue<TValue>(null, instance, tag); } public static TValue GetValue<TValue>(IExtensible instance, int tag, DataFormat format) { return GetValue<TValue>(null, instance, tag, format); } public static TValue GetValue<TValue>(TypeModel model, IExtensible instance, int tag, DataFormat format = DataFormat.Default) { if (!TryGetValue<TValue>(model, instance, tag, out var value, format)) { return default(TValue); } return value; } public static bool TryGetValue<TValue>(IExtensible instance, int tag, out TValue value) { return TryGetValue<TValue>(null, instance, tag, out value); } public static bool TryGetValue<TValue>(IExtensible instance, int tag, DataFormat format, out TValue value) { return TryGetValue<TValue>(null, instance, tag, out value, format); } public static bool TryGetValue<TValue>(IExtensible instance, int tag, DataFormat format, bool allowDefinedTag, out TValue value) { return TryGetValue<TValue>(null, instance, tag, out value, format, allowDefinedTag); } public static bool TryGetValue<TValue>(TypeModel model, IExtensible instance, int tag, out TValue value, DataFormat format = DataFormat.Default, bool allowDefinedTag = false) { value = default(TValue); bool result = false; foreach (TValue extendedValue in ExtensibleUtil.GetExtendedValues<TValue>(model, instance, tag, format, singleton: true, allowDefinedTag)) { value = extendedValue; result = true; } return result; } public static IEnumerable<TValue> GetValues<TValue>(IExtensible instance, int tag) { return ExtensibleUtil.GetExtendedValues<TValue>(null, instance, tag, DataFormat.Default, singleton: false, allowDefinedTag: false); } public static IEnumerable<TValue> GetValues<TValue>(IExtensible instance, int tag, DataFormat format) { return ExtensibleUtil.GetExtendedValues<TValue>(null, instance, tag, format, singleton: false, allowDefinedTag: false); } public static IEnumerable<TValue> GetValues<TValue>(TypeModel model, IExtensible instance, int tag, DataFormat format = DataFormat.Default) { return ExtensibleUtil.GetExtendedValues<TValue>(model, instance, tag, format, singleton: false, allowDefinedTag: false); } public static bool TryGetValue(TypeModel model, Type type, IExtensible instance, int tag, DataFormat format, bool allowDefinedTag, out object value) { value = null; bool result = false; foreach (object extendedValue in ExtensibleUtil.GetExtendedValues(model, type, instance, tag, format, singleton: true, allowDefinedTag)) { value = extendedValue; result = true; } return result; } public static IEnumerable GetValues(TypeModel model, Type type, IExtensible instance, int tag, DataFormat format = DataFormat.Default) { return ExtensibleUtil.GetExtendedValues(model, type, instance, tag, format, singleton: false, allowDefinedTag: false); } public static void AppendValue(TypeModel model, IExtensible instance, int tag, DataFormat format, object value) { ExtensibleUtil.AppendExtendValue(model, instance, tag, format, value); } } internal static class ExtensibleUtil { internal static IEnumerable<TValue> GetExtendedValues<TValue>(TypeModel model, IExtensible instance, int tag, DataFormat format, bool singleton, bool allowDefinedTag) { foreach (TValue extendedValue in GetExtendedValues(model, typeof(TValue), instance, tag, format, singleton, allowDefinedTag)) { yield return extendedValue; } } internal static IEnumerable GetExtendedValues(TypeModel model, Type type, IExtensible instance, int tag, DataFormat format, bool singleton, bool allowDefinedTag) { if (instance == null) { ThrowHelper.ThrowArgumentNullException("instance"); } if (tag <= 0) { ThrowHelper.ThrowArgumentOutOfRangeException("tag"); } return GetExtendedValues(model, type, instance.GetExtensionObject(createIfMissing: false), tag, format, singleton); } internal static IEnumerable GetExtendedValues(TypeModel model, Type type, IExtension extn, int tag, DataFormat format, bool singleton) { if (model == null) { model = TypeModel.DefaultModel; } if (extn == null) { yield break; } Stream stream = extn.BeginQuery(); try { object value = null; SerializationContext userState = new SerializationContext(); ProtoReader.SolidState state = ProtoReader.State.Create(stream, model, userState, -1L).Solidify(); try { while (model.TryDeserializeAuxiliaryType(ref state, format, tag, type, ref value, skipOtherFields: true, asListItem: true, autoCreate: false, insideList: false, null, isRoot: false) && value != null) { if (!singleton) { yield return value; value = null; } } if (singleton && value != null) { yield return value; } } finally { state.Dispose(); } } finally { extn.EndQuery(stream); } } internal static void AppendExtendValue(TypeModel model, IExtensible instance, int tag, DataFormat format, object value) { if (instance == null) { ThrowHelper.ThrowArgumentNullException("instance"); } if (value == null) { ThrowHelper.ThrowArgumentNullException("value"); } AppendExtendValue(model, instance.GetExtensionObject(createIfMissing: true), tag, format, value); } internal static void AppendExtendValue(TypeModel model, IExtension extn, int tag, DataFormat format, object value) { if (model == null) { model = TypeModel.DefaultModel; } if (extn == null) { ThrowHelper.ThrowInvalidOperationException("No extension object available; appended data would be lost."); } bool commit = false; Stream stream = extn.BeginAppend(); try { ProtoWriter.State state = ProtoWriter.State.Create(stream, model); try { model.TrySerializeAuxiliaryType(ref state, null, format, tag, value, isInsideList: false, null, isRoot: false); state.Close(); } catch { state.Abandon(); throw; } finally { state.Dispose(); } commit = true; } finally { extn.EndAppend(stream, commit); } } } internal static class Helpers { internal static MethodInfo GetInstanceMethod(Type declaringType, string name) { return declaringType.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } internal static MethodInfo GetStaticMethod(Type declaringType, string name) { return declaringType.GetMethod(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } internal static MethodInfo GetInstanceMethod(Type declaringType, string name, Type[] types) { if (types == null) { types = Type.EmptyTypes; } return declaringType.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, types, null); } internal static bool IsSubclassOf(Type type, Type baseClass) { return type.IsSubclassOf(baseClass); } public static ProtoTypeCode GetTypeCode(Type type) { TypeCode typeCode = Type.GetTypeCode(type); switch (typeCode) { case TypeCode.Empty: case TypeCode.Boolean: case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: case TypeCode.DateTime: case TypeCode.String: return (ProtoTypeCode)typeCode; default: if (type == typeof(TimeSpan)) { return ProtoTypeCode.TimeSpan; } if (type == typeof(Guid)) { return ProtoTypeCode.Guid; } if (type == typeof(Uri)) { return ProtoTypeCode.Uri; } if (type == typeof(byte[])) { return ProtoTypeCode.ByteArray; } if (type == typeof(ArraySegment<byte>)) { return ProtoTypeCode.ByteArraySegment; } if (type == typeof(Memory<byte>)) { return ProtoTypeCode.ByteMemory; } if (type == typeof(ReadOnlyMemory<byte>)) { return ProtoTypeCode.ByteReadOnlyMemory; } if (type == typeof(Type)) { return ProtoTypeCode.Type; } if (type == typeof(IntPtr)) { return ProtoTypeCode.IntPtr; } if (type == typeof(UIntPtr)) { return ProtoTypeCode.UIntPtr; } return ProtoTypeCode.Unknown; } } internal static MethodInfo GetGetMethod(PropertyInfo property, bool nonPublic, bool allowInternal) { if ((object)property == null) { return null; } MethodInfo methodInfo = property.GetGetMethod(nonPublic); if ((object)methodInfo == null && !nonPublic && allowInternal) { methodInfo = property.GetGetMethod(nonPublic: true); if ((object)methodInfo != null && !methodInfo.IsAssembly && !methodInfo.IsFamilyOrAssembly) { methodInfo = null; } } return methodInfo; } internal static MethodInfo GetSetMethod(PropertyInfo property, bool nonPublic, bool allowInternal) { if ((object)property == null) { return null; } MethodInfo methodInfo = property.GetSetMethod(nonPublic); if ((object)methodInfo == null && !nonPublic && allowInternal) { methodInfo = property.GetSetMethod(nonPublic: true); if ((object)methodInfo != null && !methodInfo.IsAssembly && !methodInfo.IsFamilyOrAssembly) { methodInfo = null; } } return methodInfo; } internal static ConstructorInfo GetConstructor(Type type, Type[] parameterTypes, bool nonPublic) { return type.GetConstructor(nonPublic ? (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) : (BindingFlags.Instance | BindingFlags.Public), null, parameterTypes, null); } internal static ConstructorInfo[] GetConstructors(Type type, bool nonPublic) { return type.GetConstructors(nonPublic ? (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) : (BindingFlags.Instance | BindingFlags.Public)); } internal static void GetBuffer(MemoryStream stream, out ArraySegment<byte> segment) { if (stream == null || !stream.TryGetBuffer(out segment)) { ThrowHelper.ThrowInvalidOperationException("Unable to obtain buffer from MemoryStream"); segment = default(ArraySegment<byte>); } } internal static PropertyInfo GetProperty(Type type, string name, bool nonPublic) { return type.GetProperty(name, nonPublic ? (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) : (BindingFlags.Instance | BindingFlags.Public)); } internal static MemberInfo[] GetInstanceFieldsAndProperties(Type type, bool publicOnly) { BindingFlags bindingAttr = (publicOnly ? (BindingFlags.Instance | BindingFlags.Public) : (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)); PropertyInfo[] properties = type.GetProperties(bindingAttr); FieldInfo[] fields = type.GetFields(bindingAttr); MemberInfo[] array = new MemberInfo[fields.Length + properties.Length]; properties.CopyTo(array, 0); fields.CopyTo(array, properties.Length); return array; } internal static Type GetMemberType(MemberInfo member) { return member.MemberType switch { MemberTypes.Field => ((FieldInfo)member).FieldType, MemberTypes.Property => ((PropertyInfo)member).PropertyType, _ => null, }; } } internal enum ProtoTypeCode { Empty = 0, Unknown = 1, Boolean = 3, Char = 4, SByte = 5, Byte = 6, Int16 = 7, UInt16 = 8, Int32 = 9, UInt32 = 10, Int64 = 11, UInt64 = 12, Single = 13, Double = 14, Decimal = 15, DateTime = 16, String = 18, TimeSpan = 100, ByteArray = 101, Guid = 102, Uri = 103, Type = 104, ByteArraySegment = 105, ByteMemory = 106, ByteReadOnlyMemory = 107, IntPtr = 108, UIntPtr = 109 } public interface IExtensible { IExtension GetExtensionObject(bool createIfMissing); } public interface ITypedExtensible { IExtension GetExtensionObject(Type type, bool createIfMissing); } public interface IExtension { Stream BeginAppend(); void EndAppend(Stream stream, bool commit); Stream BeginQuery(); void EndQuery(Stream stream); int GetLength(); } public interface IExtensionResettable : IExtension { void Reset(); } public enum ImplicitFields { None, AllPublic, AllFields } public interface IProtoInput<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] TInput> { T Deserialize<T>(TInput source, T value = default(T), object userState = null); } public interface IProtoOutput<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] TOutput> { void Serialize<T>(TOutput destination, T value, object userState = null); } public interface IMeasuredProtoOutput<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] TOutput> : IProtoOutput<TOutput> { MeasureState<T> Measure<T>(T value, object userState = null); void Serialize<T>(MeasureState<T> measured, TOutput destination); } public interface ISerializationContext { TypeModel Model { get; } object UserState { get; } } public struct MeasureState<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T> : IDisposable { private readonly TypeModel _model; private readonly T _value; private readonly object _userState; private ProtoWriter _writer; public long Length { get; } internal MeasureState(TypeModel model, in T value, object userState, long abortAfter) { _model = model; _value = value; _userState = userState; ProtoWriter.State state = ProtoWriter.NullProtoWriter.CreateNullProtoWriter(_model, userState, abortAfter); try { Length = TypeModel.SerializeImpl(ref state, _value); ProtoWriter.NullProtoWriter.CheckOversized(abortAfter, Length); _writer = state.GetWriter(); } catch { state.Dispose(); throw; } } public void Dispose() { ProtoWriter writer = _writer; _writer = null; writer?.Dispose(); } public long LengthOnly() { long length = Length; Dispose(); return length; } private readonly void SerializeCore(ProtoWriter.State state) { try { ProtoWriter writer = _writer ?? throw new ObjectDisposedException("MeasureState"); ProtoWriter writer2 = state.GetWriter(); writer2.InitializeFrom(writer); long num = TypeModel.SerializeImpl(ref state, _value); writer2.CopyBack(writer); if (num != Length) { ThrowHelper.ThrowInvalidOperationException($"Invalid length; expected {Length}, actual: {num}"); } } catch (Exception ex) { ex.Data?.Add("ProtoBuf.MeasuredLength", Length); throw; } finally { state.Dispose(); } } internal readonly int GetLengthHits(out int misses) { return _writer.GetLengthHits(out misses); } public readonly void Serialize(Stream stream) { SerializeCore(ProtoWriter.State.Create(stream, _model, _userState)); } public readonly void Serialize(IBufferWriter<byte> writer) { SerializeCore(ProtoWriter.State.Create(writer, _model, _userState)); } } internal sealed class NetObjectCache { [StructLayout(LayoutKind.Auto)] private readonly struct ObjectKey : IEquatable<ObjectKey> { private readonly object _obj; private readonly Type _subTypeLevel; [MethodImpl(MethodImplOptions.AggressiveInlining)] public ObjectKey(object obj, Type subTypeLevel) { _obj = obj; _subTypeLevel = subTypeLevel; } public override string ToString() { return $"{_subTypeLevel}/{_obj}"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { return RuntimeHelpers.GetHashCode(_obj) ^ (_subTypeLevel?.GetHashCode() ?? 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) { if (obj is ObjectKey other) { return Equals(other); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(ObjectKey other) { return (_obj == other._obj) & (_subTypeLevel == other._subTypeLevel); } } private readonly Dictionary<ObjectKey, long> _knownLengths = new Dictionary<ObjectKey, long>(); private int _hit; private int _miss; internal int LengthHits => _hit; internal int LengthMisses => _miss; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryGetKnownLength(object obj, Type subTypeLevel, out long length) { if (_knownLengths.TryGetValue(new ObjectKey(obj, subTypeLevel), out length)) { _hit++; return true; } _miss++; length = 0L; return false; } public void SetKnownLength(object obj, Type subTypeLevel, long length) { ObjectKey key = new ObjectKey(obj, subTypeLevel); _knownLengths[key] = length; } internal void Clear() { _knownLengths.Clear(); _hit = (_miss = 0); } internal void InitializeFrom(NetObjectCache obj) { if (obj == null) { return; } _knownLengths.Clear(); foreach (KeyValuePair<ObjectKey, long> knownLength in obj._knownLengths) { _knownLengths.Add(knownLength.Key, knownLength.Value); } } internal void CopyBack(NetObjectCache obj) { if (obj != null) { obj._hit += _hit; obj._miss += _miss; } } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class NullWrappedValueAttribute : Attribute { public bool AsGroup { get; set; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class NullWrappedCollectionAttribute : Attribute { public bool AsGroup { get; set; } } public enum PrefixStyle { None, Base128, Fixed32, Fixed32BigEndian } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface, AllowMultiple = false, Inherited = false)] public sealed class ProtoContractAttribute : Attribute { [Flags] private enum TypeOptions : ushort { InferTagFromName = 1, InferTagFromNameHasValue = 2, UseProtoMembersOnly = 4, SkipConstructor = 8, IgnoreListHandling = 0x10, IsGroup = 0x100, IgnoreUnknownSubTypes = 0x200 } internal const string ReferenceDynamicDisabled = "Reference-tracking and dynamic-type are not currently implemented in this build; they may be reinstated later; this is partly due to doubts over whether the features are adviseable, and partly over confidence in testing all the scenarios (it takes time; that time hasn't get happened); feedback is invited"; private int implicitFirstTag; private TypeOptions flags; public string Name { get; set; } public string Origin { get; set; } public int ImplicitFirstTag { get { return implicitFirstTag; } set { if (value < 1) { ThrowHelper.ThrowArgumentOutOfRangeException("ImplicitFirstTag"); } implicitFirstTag = value; } } public bool UseProtoMembersOnly { get { return HasFlag(TypeOptions.UseProtoMembersOnly); } set { SetFlag(TypeOptions.UseProtoMembersOnly, value); } } public bool IgnoreListHandling { get { return HasFlag(TypeOptions.IgnoreListHandling); } set { SetFlag(TypeOptions.IgnoreListHandling, value); } } public ImplicitFields ImplicitFields { get; set; } public bool InferTagFromName { get { return HasFlag(TypeOptions.InferTagFromName); } set { SetFlag(TypeOptions.InferTagFromName, value); SetFlag(TypeOptions.InferTagFromNameHasValue, value: true); } } internal bool InferTagFromNameHasValue => HasFlag(TypeOptions.InferTagFromNameHasValue); public int DataMemberOffset { get; set; } public bool SkipConstructor { get { return HasFlag(TypeOptions.SkipConstructor); } set { SetFlag(TypeOptions.SkipConstructor, value); } } public bool AsReferenceDefault { get { return false; } [Obsolete("Reference-tracking and dynamic-type are not currently implemented in this build; they may be reinstated later; this is partly due to doubts over whether the features are adviseable, and partly over confidence in testing all the scenarios (it takes time; that time hasn't get happened); feedback is invited", true)] set { if (value != AsReferenceDefault) { ThrowHelper.ThrowNotSupportedException(); } } } public bool IsGroup { get { return HasFlag(TypeOptions.IsGroup); } set { SetFlag(TypeOptions.IsGroup, value); } } public bool IgnoreUnknownSubTypes { get { return HasFlag(TypeOptions.IgnoreUnknownSubTypes); } set { SetFlag(TypeOptions.IgnoreUnknownSubTypes, value); } } [Obsolete("Enum value maps have been deprecated and are no longer supported; all enums are now effectively pass-thru; custom maps should be applied via shadow properties; in C#, lambda-based 'switch expressions' make for very convenient shadow properties", true)] public bool EnumPassthru { get { return true; } set { if (!value) { ThrowHelper.ThrowInvalidOperationException("EnumPassthru is not longer supported, and is always considered true"); } } } public Type Surrogate { get; set; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods)] public Type Serializer { get; set; } private bool HasFlag(TypeOptions flag) { return (flags & flag) == flag; } private void SetFlag(TypeOptions flag, bool value) { if (value) { flags |= flag; } else { flags &= (TypeOptions)(ushort)(~(int)flag); } } } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class ProtoConverterAttribute : Attribute { } [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] public sealed class ProtoEnumAttribute : Attribute { internal const string EnumValueDeprecated = "Enum value maps have been deprecated and are no longer supported; all enums are now effectively pass-thru; custom maps should be applied via shadow properties; in C#, lambda-based 'switch expressions' make for very convenient shadow properties"; public int Value { [Obsolete("Enum value maps have been deprecated and are no longer supported; all enums are now effectively pass-thru; custom maps should be applied via shadow properties; in C#, lambda-based 'switch expressions' make for very convenient shadow properties", false)] get { return 0; } [Obsolete("Enum value maps have been deprecated and are no longer supported; all enums are now effectively pass-thru; custom maps should be applied via shadow properties; in C#, lambda-based 'switch expressions' make for very convenient shadow properties", true)] set { ThrowHelper.ThrowNotSupportedException(); } } public string Name { get; set; } [Obsolete("Enum value maps have been deprecated and are no longer supported; all enums are now effectively pass-thru; custom maps should be applied via shadow properties; in C#, lambda-based 'switch expressions' make for very convenient shadow properties", false)] public bool HasValue() { return false; } } [Serializable] public class ProtoException : Exception { public ProtoException() { } public ProtoException(string message) : base(message) { } public ProtoException(string message, Exception innerException) : base(message, innerException) { } protected ProtoException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] public class ProtoIgnoreAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public sealed class ProtoPartialIgnoreAttribute : ProtoIgnoreAttribute { public string MemberName { get; } public ProtoPartialIgnoreAttribute(string memberName) { if (string.IsNullOrEmpty(memberName)) { ThrowHelper.ThrowArgumentNullException("memberName"); } MemberName = memberName; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] public sealed class ProtoIncludeAttribute : Attribute { public int Tag { get; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] public string KnownTypeName { get; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] public Type KnownType => TypeModel.ResolveKnownType(KnownTypeName, null); [DefaultValue(DataFormat.Default)] public DataFormat DataFormat { get; set; } public ProtoIncludeAttribute(int tag, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] Type knownType) : this(tag, ((object)knownType == null) ? "" : knownType.AssemblyQualifiedName) { } public ProtoIncludeAttribute(int tag, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] string knownTypeName) { if (tag <= 0) { ThrowHelper.ThrowArgumentOutOfRangeException("tag", "Tags must be positive integers"); } if (string.IsNullOrEmpty(knownTypeName)) { ThrowHelper.ThrowArgumentNullException("knownTypeName", "Known type cannot be blank"); } Tag = tag; KnownTypeName = knownTypeName; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] public class ProtoMapAttribute : Attribute { public DataFormat KeyFormat { get; set; } public DataFormat ValueFormat { get; set; } public bool DisableMap { get; set; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] public class ProtoMemberAttribute : Attribute, IComparable, IComparable<ProtoMemberAttribute> { internal MemberInfo Member; internal MemberInfo BackingMember; internal bool TagIsPinned; private string name; private DataFormat dataFormat; private int tag; private MemberSerializationOptions options; public string Name { get { return name; } set { name = value; } } public DataFormat DataFormat { get { return dataFormat; } set { dataFormat = value; } } public int Tag => tag; public bool IsRequired { get { return (options & MemberSerializationOptions.Required) == MemberSerializationOptions.Required; } set { if (value) { options |= MemberSerializationOptions.Required; } else { options &= ~MemberSerializationOptions.Required; } } } public bool IsPacked { get { return (options & MemberSerializationOptions.Packed) == MemberSerializationOptions.Packed; } set { if (value) { options |= MemberSerializationOptions.Packed; } else { options &= ~MemberSerializationOptions.Packed; } } } public bool OverwriteList { get { return (options & MemberSerializationOptions.OverwriteList) == MemberSerializationOptions.OverwriteList; } set { if (value) { options |= MemberSerializationOptions.OverwriteList; } else { options &= ~MemberSerializationOptions.OverwriteList; } } } [Obsolete("Reference-tracking and dynamic-type are not currently implemented in this build; they may be reinstated later; this is partly due to doubts over whether the features are adviseable, and partly over confidence in testing all the scenarios (it takes time; that time hasn't get happened); feedback is invited", true)] public bool AsReference { get { return (options & MemberSerializationOptions.AsReference) == MemberSerializationOptions.AsReference; } set { if (value) { options |= MemberSerializationOptions.AsReference; } else { options &= ~MemberSerializationOptions.AsReference; } options |= MemberSerializationOptions.AsReferenceHasValue; } } [Obsolete("Reference-tracking and dynamic-type are not currently implemented in this build; they may be reinstated later; this is partly due to doubts over whether the features are adviseable, and partly over confidence in testing all the scenarios (it takes time; that time hasn't get happened); feedback is invited", true)] internal bool AsReferenceHasValue { get { return (options & MemberSerializationOptions.AsReferenceHasValue) == MemberSerializationOptions.AsReferenceHasValue; } set { if (value) { options |= MemberSerializationOptions.AsReferenceHasValue; } else { options &= ~MemberSerializationOptions.AsReferenceHasValue; } } } [Obsolete("Reference-tracking and dynamic-type are not currently implemented in this build; they may be reinstated later; this is partly due to doubts over whether the features are adviseable, and partly over confidence in testing all the scenarios (it takes time; that time hasn't get happened); feedback is invited", true)] public bool DynamicType { get { return (options & MemberSerializationOptions.DynamicType) == MemberSerializationOptions.DynamicType; } set { if (value) { options |= MemberSerializationOptions.DynamicType; } else { options &= ~MemberSerializationOptions.DynamicType; } } } public MemberSerializationOptions Options { get { return options; } set { options = value; } } public int CompareTo(object other) { return CompareTo(other as ProtoMemberAttribute); } public int CompareTo(ProtoMemberAttribute other) { if (other == null) { return -1; } if (this == other) { return 0; } int num = tag.CompareTo(other.tag); if (num == 0) { num = string.CompareOrdinal(name, other.name); } return num; } public ProtoMemberAttribute(int tag) : this(tag, forced: false) { } internal ProtoMemberAttribute(int tag, bool forced) { if (tag <= 0 && !forced) { ThrowHelper.ThrowArgumentOutOfRangeException("tag"); } this.tag = tag; } internal void Rebase(int tag) { this.tag = tag; } } [Flags] public enum MemberSerializationOptions { None = 0, Packed = 1, Required = 2, [Obsolete("Reference-tracking and dynamic-type are not currently implemented in this build; they may be reinstated later; this is partly due to doubts over whether the features are adviseable, and partly over confidence in testing all the scenarios (it takes time; that time hasn't get happened); feedback is invited", false)] AsReference = 4, [Obsolete("Reference-tracking and dynamic-type are not currently implemented in this build; they may be reinstated later; this is partly due to doubts over whether the features are adviseable, and partly over confidence in testing all the scenarios (it takes time; that time hasn't get happened); feedback is invited", false)] DynamicType = 8, OverwriteList = 0x10, [Obsolete("Reference-tracking and dynamic-type are not currently implemented in this build; they may be reinstated later; this is partly due to doubts over whether the features are adviseable, and partly over confidence in testing all the scenarios (it takes time; that time hasn't get happened); feedback is invited", false)] AsReferenceHasValue = 0x20 } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public sealed class ProtoPartialMemberAttribute : ProtoMemberAttribute { public string MemberName { get; private set; } public ProtoPartialMemberAttribute(int tag, string memberName) : base(tag) { if (string.IsNullOrEmpty(memberName)) { ThrowHelper.ThrowArgumentNullException("memberName"); } MemberName = memberName; } } public abstract class ProtoReader : IDisposable, ISerializationContext { private protected enum Read32VarintMode { Signed, Unsigned, FieldHeader } [StructLayout(LayoutKind.Auto)] public ref struct State { private ProtoReader _reader; private ReadOnlyMemory<byte> _memory; internal ReadOnlySpan<byte> Span { get; private set; } internal int OffsetInCurrent { get; private set; } internal int RemainingInCurrent { get; private set; } public readonly WireType WireType { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _reader.WireType; } } public readonly bool InternStrings { get { return _reader.InternStrings; } set { _reader.InternStrings = value; } } public readonly int FieldNumber { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _reader._fieldNumber; } } internal readonly TypeModel Model { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _reader?.Model; } private set { _reader.Model = value; } } public readonly ISerializationContext Context { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _reader; } } public static State Create(ReadOnlySequence<byte> source, TypeModel model, object userState = null) { ReadOnlySequenceProtoReader readOnlySequenceProtoReader = Pool<ReadOnlySequenceProtoReader>.TryGet() ?? new ReadOnlySequenceProtoReader(); readOnlySequenceProtoReader.Init(source, model, userState); return new State(readOnlySequenceProtoReader); } public static State Create(ReadOnlyMemory<byte> source, TypeModel model, object userState = null) { return Create(new ReadOnlySequence<byte>(source), model, userState); } public void Dispose() { ProtoReader reader = _reader; this = default(State); reader?.Dispose(); } internal readonly SolidState Solidify() { return new SolidState(_reader, _memory.Slice(OffsetInCurrent, RemainingInCurrent)); } internal State(ProtoReader reader, ReadOnlyMemory<byte> memory) : this(reader) { Init(memory); } internal State(ProtoReader reader) { this = default(State); _reader = reader; } internal void Init(ReadOnlyMemory<byte> memory) { _memory = memory; Span = memory.Span; OffsetInCurrent = 0; RemainingInCurrent = Span.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void Skip(int bytes) { OffsetInCurrent += bytes; RemainingInCurrent -= bytes; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ReadOnlySpan<byte> Consume(int bytes) { ReadOnlySpan<byte> result = Span.Slice(OffsetInCurrent, bytes); OffsetInCurrent += bytes; RemainingInCurrent -= bytes; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ReadOnlySpan<byte> Consume(int bytes, out int offset) { offset = OffsetInCurrent; OffsetInCurrent += bytes; RemainingInCurrent -= bytes; return Span; } internal int ReadVarintUInt32(out uint value) { value = Span[OffsetInCurrent]; int num = (((value & 0x80) == 0) ? 1 : ParseVarintUInt32Tail(Span.Slice(OffsetInCurrent), ref value)); OffsetInCurrent += num; RemainingInCurrent -= num; return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal int ParseVarintUInt32(ReadOnlySpan<byte> span, out uint value) { value = span[0]; if ((value & 0x80) != 0) { return ParseVarintUInt32Tail(span, ref value); } return 1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal int ParseVarintUInt32(ReadOnlySpan<byte> span, int offset, out uint value) { value = span[offset]; if ((value & 0x80) != 0) { return ParseVarintUInt32Tail(span.Slice(offset), ref value); } return 1; } private int ParseVarintUInt32Tail(ReadOnlySpan<byte> span, ref uint value) { uint num = span[1]; value = (value & 0x7F) | ((num & 0x7F) << 7); if ((num & 0x80) == 0) { return 2; } num = span[2]; value |= (num & 0x7F) << 14; if ((num & 0x80) == 0) { return 3; } num = span[3]; value |= (num & 0x7F) << 21; if ((num & 0x80) == 0) { return 4; } num = span[4]; value |= num << 28; if ((num & 0xF0) == 0) { return 5; } ThrowOverflow(); return 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal readonly void Advance(long count) { _reader.Advance(count); } internal static int TryParseUInt64Varint(ReadOnlySpan<byte> span, int offset, out ulong value) { if ((uint)offset >= (uint)span.Length) { value = 0uL; return 0; } value = span[offset++]; if ((value & 0x80) == 0L) { return 1; } value &= 127uL; if ((uint)offset >= (uint)span.Length) { NoContextThrowEoF(); } ulong num = span[offset++]; value |= (num & 0x7F) << 7; if ((num & 0x80) == 0L) { return 2; } if ((uint)offset >= (uint)span.Length) { NoContextThrowEoF(); } num = span[offset++]; value |= (num & 0x7F) << 14; if ((num & 0x80) == 0L) { return 3; } if ((uint)offset >= (uint)span.Length) { NoContextThrowEoF(); } num = span[offset++]; value |= (num & 0x7F) << 21; if ((num & 0x80) == 0L) { return 4; } if ((uint)offset >= (uint)span.Length) { NoContextThrowEoF(); } num = span[offset++]; value |= (num & 0x7F) << 28; if ((num & 0x80) == 0L) { return 5; } if ((uint)offset >= (uint)span.Length) { NoContextThrowEoF(); } num = span[offset++]; value |= (num & 0x7F) << 35; if ((num & 0x80) == 0L) { return 6; } if ((uint)offset >= (uint)span.Length) { NoContextThrowEoF(); } num = span[offset++]; value |= (num & 0x7F) << 42; if ((num & 0x80) == 0L) { return 7; } if ((uint)offset >= (uint)span.Length) { NoContextThrowEoF(); } num = span[offset++]; value |= (num & 0x7F) << 49; if ((num & 0x80) == 0L) { return 8; } if ((uint)offset >= (uint)span.Length) { NoContextThrowEoF(); } num = span[offset++]; value |= (num & 0x7F) << 56; if ((num & 0x80) == 0L) { return 9; } if ((uint)offset >= (uint)span.Length) { NoContextThrowEoF(); } num = span[offset]; value |= num << 63; if ((num & 0xFFFFFFFFFFFFFFFEuL) != 0L) { NoContextThrowOverflow(); } return 10; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal readonly ProtoReader GetReader() { return _reader; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ushort ReadUInt16() { return checked((ushort)ReadUInt32()); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public short ReadInt16() { return checked((short)ReadInt32()); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly long GetPosition() { return _reader._longPosition; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public byte ReadByte() { return checked((byte)ReadUInt32()); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public sbyte ReadSByte() { return checked((sbyte)ReadInt32()); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public IntPtr ReadIntPtr() { return new IntPtr(ReadInt64()); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public UIntPtr ReadUIntPtr() { return new UIntPtr(ReadUInt64()); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public uint ReadUInt32() { switch (_reader.WireType) { case WireType.Variant: return ReadUInt32Varint(Read32VarintMode.Signed); case WireType.Fixed32: return _reader.ImplReadUInt32Fixed(ref this); case WireType.Fixed64: { ulong num = _reader.ImplReadUInt64Fixed(ref this); return checked((uint)num); } default: ThrowWireTypeException(); return 0u; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int ReadInt32() { switch (_reader.WireType) { case WireType.Variant: return (int)ReadUInt32Varint(Read32VarintMode.Signed); case WireType.Fixed32: return (int)_reader.ImplReadUInt32Fixed(ref this); case WireType.Fixed64: { long num = ReadInt64(); return checked((int)num); } case WireType.SignedVariant: return Zag(ReadUInt32Varint(Read32VarintMode.Signed)); default: ThrowWireTypeException(); return 0; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public long ReadInt64() { switch (_reader.WireType) { case WireType.Variant: return (long)ReadUInt64Varint(); case WireType.Fixed32: return (int)_reader.ImplReadUInt32Fixed(ref this); case WireType.Fixed64: return (long)_reader.ImplReadUInt64Fixed(ref this); case WireType.SignedVariant: return Zag(ReadUInt64Varint()); default: ThrowWireTypeException(); return 0L; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe double ReadDouble() { switch (_reader.WireType) { case WireType.Fixed32: return ReadSingle(); case WireType.Fixed64: { long num = ReadInt64(); return *(double*)(&num); } default: ThrowWireTypeException(); return 0.0; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe float ReadSingle() { switch (_reader.WireType) { case WireType.Fixed32: { int num3 = ReadInt32(); return *(float*)(&num3); } case WireType.Fixed64: { double num = ReadDouble(); float num2 = (float)num; if (float.IsInfinity(num2) && !double.IsInfinity(num)) { ThrowOverflow(); } return num2; } default: ThrowWireTypeException(); return 0f; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void PrepareToReadRepeated<T>(ref SerializerFeatures features, SerializerFeatures serializerFeatures, out SerializerFeatures category, out bool packed) { if (serializerFeatures.IsRepeated()) { TypeModel.ThrowNestedListsNotSupported(typeof(T)); } features.InheritFrom(serializerFeatures); category = serializerFeatures.GetCategory(); packed = false; if (TypeHelper<T>.CanBePacked && WireType == WireType.String && !features.HasAny(SerializerFeatures.OptionWrappedValue)) { if (category != SerializerFeatures.CategoryScalar) { ThrowInvalidOperationException("Packed data expected a scalar serializer"); } packed = true; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ReadRepeatedCore<TSerializer, TList, T>(ref TList values, SerializerFeatures category, WireType wireType, in TSerializer serializer, SerializerFeatures features) where TSerializer : ISerializer<T> where TList : ICollection<T> { int fieldNumber = FieldNumber; bool flag = features.HasAny(SerializerFeatures.OptionWrappedValue); T value = features.DefaultFor<T>(); do { T item; if (flag) { item = ReadWrapped(features, value, serializer); } else { switch (category) { case SerializerFeatures.CategoryScalar: Hint(wireType); item = serializer.Read(ref this, value); break; case SerializerFeatures.CategoryMessage: case SerializerFeatures.CategoryMessageWrappedAtRoot: item = ReadMessage(SerializerFeatures.CategoryRepeated, value, in serializer); break; default: category.ThrowInvalidCategory(); item = default(T); break; } } values.Add(item); } while (TryReadFieldHeader(fieldNumber)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ReadPackedScalar<TSerializer, TList, T>(ref TList list, WireType wireType, in TSerializer serializer) where TSerializer : ISerializer<T> where TList : ICollection<T> { int num = (int)ReadUInt32Varint(Read32VarintMode.Unsigned); if (num == 0) { return; } if (num < 0) { ThrowInvalidLength(num); } int num2; if (wireType <= WireType.Fixed64) { if (wireType == WireType.Variant) { goto IL_00ff; } if (wireType == WireType.Fixed64) { if (num % 8 != 0) { ThrowHelper.ThrowInvalidOperationException("packed length should be multiple of 8"); } num2 = num / 8; goto IL_0065; } } else { if (wireType == WireType.Fixed32) { if (num % 4 != 0) { ThrowHelper.ThrowInvalidOperationException("packed length should be multiple of 4"); } num2 = num / 4; goto IL_0065; } if (wireType == WireType.SignedVariant) { goto IL_00ff; } } ThrowHelper.ThrowInvalidPackedOperationException(WireType, typeof(T)); return; IL_0065: if (list is List<T> list2) { list2.Capacity = Math.Max(list2.Capacity, list2.Count + Math.Min(num2, 8192)); } TList val; TSerializer val2; for (int i = 0; i < num2; i++) { _reader.WireType = wireType; ref TList reference = ref list; val = default(TList); if (val == null) { val = reference; reference = ref val; } val2 = serializer; T item = val2.Read(ref this, default(T)); reference.Add(item); } return; IL_00ff: long num3 = GetPosition() + num; do { _reader.WireType = wireType; ref TList reference2 = ref list; val = default(TList); if (val == null) { val = reference2; reference2 = ref val; } val2 = serializer; T item2 = val2.Read(ref this, default(T)); reference2.Add(item2); } while (GetPosition() < num3); if (GetPosition() != num3) { ThrowHelper.ThrowInvalidOperationException("over-read packed data"); } } internal ReadBuffer<T> FillBuffer<TSerializer, T>(SerializerFeatures features, in TSerializer serializer, T initialValue) where TSerializer : ISerializer<T> { PrepareToReadRepeated<T>(ref features, serializer.Features, out var category, out var packed); ReadBuffer<T> values = ReadBuffer<T>.Create(); try { WireType wireType = features.GetWireType(); if (packed) { ReadPackedScalar<TSerializer, ReadBuffer<T>, T>(ref values, wireType, in serializer); } else { ReadRepeatedCore<TSerializer, ReadBuffer<T>, T>(ref values, category, wireType, in serializer, features); } return values; } catch { try { values.Dispose(); } catch { } throw; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ReadBoolean() { return ReadUInt32() != 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong ReadUInt64() { switch (_reader.WireType) { case WireType.Variant: return ReadUInt64Varint(); case WireType.Fixed32: return _reader.ImplReadUInt32Fixed(ref this); case WireType.Fixed64: return _reader.ImplReadUInt64Fixed(ref this); default: ThrowWireTypeException(); return 0uL; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public byte[] AppendBytes(byte[] value) { return AppendBytesImpl(value, DefaultMemoryConverter<byte>.Instance); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory<byte> AppendBytes(ReadOnlyMemory<byte> value) { return AppendBytesImpl(value, DefaultMemoryConverter<byte>.Instance); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<byte> AppendBytes(Memory<byte> value) { return AppendBytesImpl(value, DefaultMemoryConverter<byte>.Instance); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ArraySegment<byte> AppendBytes(ArraySegment<byte> value) { return AppendBytesImpl(value, DefaultMemoryConverter<byte>.Instance); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public TStorage AppendBytes<TStorage>(TStorage value, IMemoryConverter<TStorage, byte> converter = null) { return AppendBytesImpl(value, converter ?? DefaultMemoryConverter<byte>.GetFor<TStorage>(Model)); } private TStorage AppendBytesImpl<TStorage>(TStorage value, IMemoryConverter<TStorage, byte> converter) { WireType wireType = _reader.WireType; if (wireType == WireType.String) { int num = (int)ReadUInt32Varint(Read32VarintMode.Signed); _reader.WireType = WireType.None; if (num == 0) { return converter.NonNull(in value); } if (num < 0) { ThrowInvalidLength(num); } Memory<byte> memory = converter.Expand(Context, ref value, num); _reader.ImplReadBytes(ref this, memory.Span); return value; } ThrowWireTypeException(); return default(TStorage); } [Browsable(false)] public Span<byte> ReadBytes(Span<byte> destination) { ReadBytes(destination, out var length); return destination.Slice(0, length); } public void ReadBytes(Span<byte> destination, out int length) { WireType wireType = _reader.WireType; if (wireType == WireType.String) { length = (int)ReadUInt32Varint(Read32VarintMode.Signed); if (length < 0) { ThrowInvalidLength(length); } if (length > destination.Length) { ThrowHelper.ThrowInvalidOperationException($"Insufficient space in the target span to read a string/bytes value; {destination.Length} vs {length} bytes"); } _reader.WireType = WireType.None; destination = destination.Slice(0, length); _reader.ImplReadBytes(ref this, destination); } else { length = 0; ThrowWireTypeException(); } } [MethodImpl(MethodImplOptions.NoInlining)] public SubItemToken StartSubItem() { ProtoReader reader = _reader; switch (_reader.WireType) { case WireType.StartGroup: reader.WireType = WireType.None; if (reader.IncrDepth()) { ThrowTooDeep(); } return new SubItemToken(-reader._fieldNumber); case WireType.String: { long num = (long)ReadUInt64Varint(); if (num < 0) { ThrowInvalidOperationException(); } long blockEnd = reader.blockEnd64; reader.blockEnd64 = reader._longPosition + num; if (reader.IncrDepth()) { ThrowTooDeep(); } return new SubItemToken(blockEnd); } default: ThrowWireTypeException(); return default(SubItemToken); } } [MethodImpl(MethodImplOptions.NoInlining)] public void EndSubItem(SubItemToken token) { long value = token.value64; ProtoReader reader = _reader; WireType wireType = reader.WireType; if (wireType == WireType.EndGroup) { if (value >= 0) { ThrowProtoException("A length-based message was terminated via end-group; this indicates data corruption"); } if (-(int)value != reader._fieldNumber) { ThrowProtoException("Wrong group was ended"); } reader.WireType = WireType.None; reader.DecrDepth(); return; } long longPosition = reader._longPosition; if (value < longPosition) { ThrowProtoException($"Sub-message not read entirely; expected {value}, was {longPosition}"); } if (reader.blockEnd64 != longPosition && reader.blockEnd64 != long.MaxValue) { ThrowProtoException($"Sub-message not read correctly (end {reader.blockEnd64} vs {longPosition})"); } reader.blockEnd64 = value; reader.DecrDepth(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal object ReadObject(object value, Type type) { return ReadTypedObject(value, type); } [MethodImpl(MethodImplOptions.NoInlining)] internal object ReadTypedObject(object value, Type type) { TypeModel model = Model; if (model == null) { ThrowInvalidOperationException("Cannot deserialize sub-objects unless a model is provided"); } if (DynamicStub.TryDeserialize(ObjectScope.WrappedMessage, type, model, ref this, ref value)) { return value; } SubItemToken token = StartSubItem(); if ((object)type == null || !model.TryDeserializeAuxiliaryType(ref this, DataFormat.Default, 1, type, ref value, skipOtherFields: true, asListItem: false, autoCreate: true, insideList: false, null, isRoot: false)) { TypeModel.ThrowUnexpectedType(type, Model); } EndSubItem(token); return value; } internal void SkipAllFields() { while (ReadFieldHeader() > 0) { SkipField(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public string ReadString(StringMap map = null) { if (_reader.WireType == WireType.String) { int num = (int)ReadUInt32Varint(Read32VarintMode.Unsigned); if (num == 0) { return ""; } if (num < 0) { ThrowInvalidLength(num); } string text = _reader.ImplReadString(ref this, num); if (_reader.InternStrings) { tex
protobuf-net.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using System.Xml; using System.Xml.Serialization; using Microsoft.CodeAnalysis; using ProtoBuf; using ProtoBuf.Compiler; using ProtoBuf.Extensions; using ProtoBuf.Internal; using ProtoBuf.Internal.Serializers; using ProtoBuf.Meta; using ProtoBuf.Serializers; using ProtoBuf.WellKnownTypes; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyFileVersion("3.2.56.57311")] [assembly: AssemblyInformationalVersion("3.2.56+dfdfce61a7")] [assembly: InternalsVisibleTo("protobuf-net.Test, PublicKey=002400000480000094000000060200000024000052534131000400000100010009ed9caa457bfc205716c3d4e8b255a63ddf71c9e53b1b5f574ab6ffdba11e80ab4b50be9c46d43b75206280070ddba67bd4c830f93f0317504a76ba6a48243c36d2590695991164592767a7bbc4453b34694e31e20815a096e4483605139a32a76ec2fef196507487329c12047bf6a68bca8ee9354155f4d01daf6eec5ff6bc")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Marc Gravell")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("See https://github.com/protobuf-net/protobuf-net")] [assembly: AssemblyDescription("Provides simple access to fast and efficient \"Protocol Buffers\" serialization from .NET applications")] [assembly: AssemblyProduct("protobuf-net (netstandard2.1)")] [assembly: AssemblyTitle("protobuf-net")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/protobuf-net/protobuf-net")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("3.0.0.0")] [assembly: TypeForwardedTo(typeof(BclHelpers))] [assembly: TypeForwardedTo(typeof(BufferExtension))] [assembly: TypeForwardedTo(typeof(CompatibilityLevel))] [assembly: TypeForwardedTo(typeof(CompatibilityLevelAttribute))] [assembly: TypeForwardedTo(typeof(DataFormat))] [assembly: TypeForwardedTo(typeof(DiscriminatedUnion128))] [assembly: TypeForwardedTo(typeof(DiscriminatedUnion128Object))] [assembly: TypeForwardedTo(typeof(DiscriminatedUnion32))] [assembly: TypeForwardedTo(typeof(DiscriminatedUnion32Object))] [assembly: TypeForwardedTo(typeof(DiscriminatedUnion64))] [assembly: TypeForwardedTo(typeof(DiscriminatedUnion64Object))] [assembly: TypeForwardedTo(typeof(DiscriminatedUnionObject))] [assembly: TypeForwardedTo(typeof(Extensible))] [assembly: TypeForwardedTo(typeof(IExtensible))] [assembly: TypeForwardedTo(typeof(IExtension))] [assembly: TypeForwardedTo(typeof(IExtensionResettable))] [assembly: TypeForwardedTo(typeof(IMeasuredProtoOutput<>))] [assembly: TypeForwardedTo(typeof(ImplicitFields))] [assembly: TypeForwardedTo(typeof(IProtoInput<>))] [assembly: TypeForwardedTo(typeof(IProtoOutput<>))] [assembly: TypeForwardedTo(typeof(MeasureState<>))] [assembly: TypeForwardedTo(typeof(MemberSerializationOptions))] [assembly: TypeForwardedTo(typeof(ProtoSyntax))] [assembly: TypeForwardedTo(typeof(TypeFormatEventArgs))] [assembly: TypeForwardedTo(typeof(TypeFormatEventHandler))] [assembly: TypeForwardedTo(typeof(TypeModel))] [assembly: TypeForwardedTo(typeof(PrefixStyle))] [assembly: TypeForwardedTo(typeof(ProtoAfterDeserializationAttribute))] [assembly: TypeForwardedTo(typeof(ProtoAfterSerializationAttribute))] [assembly: TypeForwardedTo(typeof(ProtoBeforeDeserializationAttribute))] [assembly: TypeForwardedTo(typeof(ProtoBeforeSerializationAttribute))] [assembly: TypeForwardedTo(typeof(ProtoContractAttribute))] [assembly: TypeForwardedTo(typeof(ProtoConverterAttribute))] [assembly: TypeForwardedTo(typeof(ProtoEnumAttribute))] [assembly: TypeForwardedTo(typeof(ProtoException))] [assembly: TypeForwardedTo(typeof(ProtoIgnoreAttribute))] [assembly: TypeForwardedTo(typeof(ProtoIncludeAttribute))] [assembly: TypeForwardedTo(typeof(ProtoMapAttribute))] [assembly: TypeForwardedTo(typeof(ProtoMemberAttribute))] [assembly: TypeForwardedTo(typeof(ProtoPartialIgnoreAttribute))] [assembly: TypeForwardedTo(typeof(ProtoPartialMemberAttribute))] [assembly: TypeForwardedTo(typeof(ProtoReader))] [assembly: TypeForwardedTo(typeof(ProtoTypeCode))] [assembly: TypeForwardedTo(typeof(ProtoWriter))] [assembly: TypeForwardedTo(typeof(SerializationContext))] [assembly: TypeForwardedTo(typeof(SubItemToken))] [assembly: TypeForwardedTo(typeof(TimeSpanScale))] [assembly: TypeForwardedTo(typeof(WireType))] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsUnmanagedAttribute : Attribute { } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } [GeneratedCode("Nerdbank.GitVersioning.Tasks", "3.7.115.8147")] [ExcludeFromCodeCoverage] internal static class ThisAssembly { internal const string AssemblyConfiguration = "Release"; internal const string AssemblyFileVersion = "3.2.56.57311"; internal const string AssemblyInformationalVersion = "3.2.56+dfdfce61a7"; internal const string AssemblyName = "protobuf-net"; internal const string AssemblyTitle = "protobuf-net"; internal const string AssemblyVersion = "3.0.0.0"; internal static readonly DateTime GitCommitAuthorDate = new DateTime(638895502940000000L, DateTimeKind.Utc); internal static readonly DateTime GitCommitDate = new DateTime(638895502940000000L, DateTimeKind.Utc); internal const string GitCommitId = "dfdfce61a739cfd76f05fcdacf8a4b3b9e94e684"; internal const bool IsPrerelease = false; internal const bool IsPublicRelease = true; internal const string PublicKey = "002400000480000094000000060200000024000052534131000400000100010009ed9caa457bfc205716c3d4e8b255a63ddf71c9e53b1b5f574ab6ffdba11e80ab4b50be9c46d43b75206280070ddba67bd4c830f93f0317504a76ba6a48243c36d2590695991164592767a7bbc4453b34694e31e20815a096e4483605139a32a76ec2fef196507487329c12047bf6a68bca8ee9354155f4d01daf6eec5ff6bc"; internal const string PublicKeyToken = "257b51d87d2e4d67"; internal const string RootNamespace = "ProtoBuf"; } namespace ProtoBuf { public static class Serializer { public static class NonGeneric { public static object DeepClone(object instance) { if (instance != null) { return ((TypeModel)RuntimeTypeModel.Default).DeepClone(instance); } return null; } public static void Serialize(Stream dest, object instance) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (instance != null) { State val = State.Create(dest, (TypeModel)(object)RuntimeTypeModel.Default, (object)null); try { ((State)(ref val)).Model.SerializeRootFallback(ref val, instance); } finally { ((State)(ref val)).Dispose(); } } } public static object Deserialize([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] Type type, Stream source) { return ((TypeModel)RuntimeTypeModel.Default).Deserialize(type, source, (object)null, (object)null, -1L); } public static object Deserialize([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] Type type, Stream source, object instance = null, object userState = null, long length = -1L) { return ((TypeModel)RuntimeTypeModel.Default).Deserialize(type, source, instance, userState, length); } public static object Deserialize([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] Type type, ReadOnlyMemory<byte> source, object instance = null, object userState = null) { return ((TypeModel)RuntimeTypeModel.Default).Deserialize(type, source, instance, userState); } public static object Deserialize([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] Type type, ReadOnlySequence<byte> source, object instance = null, object userState = null) { return ((TypeModel)RuntimeTypeModel.Default).Deserialize(type, source, instance, userState); } public static object Deserialize([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] Type type, ReadOnlySpan<byte> source, object instance = null, object userState = null) { return ((TypeModel)RuntimeTypeModel.Default).Deserialize(type, source, instance, userState); } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public static object Merge(Stream source, object instance) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) if (instance == null) { throw new ArgumentNullException("instance"); } State val = State.Create(source, (TypeModel)(object)RuntimeTypeModel.Default, (object)null, -1L); try { return ((State)(ref val)).DeserializeRootFallback(instance, instance.GetType()); } finally { ((State)(ref val)).Dispose(); } } public static void SerializeWithLengthPrefix(Stream destination, object instance, PrefixStyle style, int fieldNumber) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) if (instance == null) { throw new ArgumentNullException("instance"); } ((TypeModel)RuntimeTypeModel.Default).SerializeWithLengthPrefix(destination, instance, instance.GetType(), style, fieldNumber); } public static bool TryDeserializeWithLengthPrefix(Stream source, PrefixStyle style, TypeResolver resolver, out object value) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) value = ((TypeModel)RuntimeTypeModel.Default).DeserializeWithLengthPrefix(source, (object)null, (Type)null, style, 0, resolver); return value != null; } public static bool CanSerialize(Type type) { return ((TypeModel)RuntimeTypeModel.Default).IsDefined(type); } public static void PrepareSerializer([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] Type type) { RuntimeTypeModel.Default[type].CompileInPlace(); } } public static class GlobalOptions { private static ProtoSyntax _defaultSyntax = (ProtoSyntax)1; [Obsolete("Please use RuntimeTypeModel.Default.InferTagFromNameDefault instead (or on a per-model basis)", false)] public static bool InferTagFromName { get { return RuntimeTypeModel.Default.InferTagFromNameDefault; } set { RuntimeTypeModel.Default.InferTagFromNameDefault = value; } } public static ProtoSyntax DefaultSyntax { get { //IL_0000: Unknown result type (might be due to invalid IL or missing references) return _defaultSyntax; } set { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) if ((int)value <= 1) { _defaultSyntax = value; } else { ThrowHelper.ThrowArgumentOutOfRangeException("DefaultSyntax"); } } } internal static ProtoSyntax Normalize(ProtoSyntax syntax) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Invalid comparison between Unknown and I4 //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) if ((int)syntax != 0) { if ((int)syntax == 1) { return syntax; } return DefaultSyntax; } return syntax; } } [Obsolete("Please use ProtoBuf.TypeResolver", true)] public delegate Type TypeResolver(int fieldNumber); private const string ProtoBinaryField = "proto"; public const int ListItemTag = 1; public static string GetProto<T>() { return ((TypeModel)RuntimeTypeModel.Default).GetSchema(typeof(T), (ProtoSyntax)(-1)); } public static string GetProto<T>(ProtoSyntax syntax) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) return ((TypeModel)RuntimeTypeModel.Default).GetSchema(typeof(T), syntax); } public static string GetProto(SchemaGenerationOptions options) { return ((TypeModel)RuntimeTypeModel.Default).GetSchema(options); } public static T DeepClone<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(T instance, SerializationContext context) { return ((TypeModel)RuntimeTypeModel.Default).DeepClone<T>(instance, (object)context); } public static T DeepClone<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(T instance, object userState = null) { return ((TypeModel)RuntimeTypeModel.Default).DeepClone<T>(instance, userState); } public static MeasureState<T> Measure<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(T value, object userState = null, long abortAfter = -1L) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) return ((TypeModel)RuntimeTypeModel.Default).Measure<T>(value, userState, abortAfter); } public static T Merge<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream source, T instance) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) State val = State.Create(source, (TypeModel)(object)RuntimeTypeModel.Default, (object)null, -1L); try { return ((State)(ref val)).DeserializeRootImpl<T>(instance); } finally { ((State)(ref val)).Dispose(); } } public static TTo ChangeType<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] TFrom, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] TTo>(TFrom instance) { using MemoryStream memoryStream = new MemoryStream(); Serialize(memoryStream, instance); memoryStream.Position = 0L; return Deserialize<TTo>(memoryStream); } public static void Merge<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(XmlReader reader, T instance) where T : IXmlSerializable { if (reader == null) { throw new ArgumentNullException("reader"); } if (instance == null) { throw new ArgumentNullException("instance"); } byte[] buffer = new byte[4096]; using MemoryStream memoryStream = new MemoryStream(); int depth = reader.Depth; while (reader.Read() && reader.Depth > depth) { if (reader.NodeType == XmlNodeType.Text) { int count; while ((count = reader.ReadContentAsBase64(buffer, 0, 4096)) > 0) { memoryStream.Write(buffer, 0, count); } if (reader.Depth <= depth) { break; } } } memoryStream.Position = 0L; Merge(memoryStream, instance); } public static void Merge<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(SerializationInfo info, T instance) where T : class, ISerializable { Merge(info, new StreamingContext(StreamingContextStates.Persistence), instance); } public static void Merge<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(SerializationInfo info, StreamingContext context, T instance) where T : class, ISerializable { //IL_0096: Unknown result type (might be due to invalid IL or missing references) if (info == null) { throw new ArgumentNullException("info"); } if (instance == null) { throw new ArgumentNullException("instance"); } if (instance.GetType() != typeof(T)) { throw new ArgumentException("Incorrect type", "instance"); } byte[] buffer = (byte[])info.GetValue("proto", typeof(byte[])); using MemoryStream memoryStream = new MemoryStream(buffer); T val = ((TypeModel)RuntimeTypeModel.Default).Deserialize<T>((Stream)memoryStream, instance, context.Context); if (val != instance) { throw new ProtoException("Deserialization changed the instance; cannot succeed."); } } public static void PrepareSerializer<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>() { RuntimeTypeModel.Default[typeof(T)].CompileInPlace(); } public static IFormatter CreateFormatter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>() { return ((TypeModel)RuntimeTypeModel.Default).CreateFormatter(typeof(T)); } public static IEnumerable<T> DeserializeItems<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream source, PrefixStyle style, int fieldNumber) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return ((TypeModel)RuntimeTypeModel.Default).DeserializeItems<T>(source, style, fieldNumber); } public static T DeserializeWithLengthPrefix<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream source, PrefixStyle style) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return DeserializeWithLengthPrefix<T>(source, style, 0); } public static T DeserializeWithLengthPrefix<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream source, PrefixStyle style, int fieldNumber) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) return (T)((TypeModel)RuntimeTypeModel.Default).DeserializeWithLengthPrefix(source, (object)null, typeof(T), style, fieldNumber); } public static T MergeWithLengthPrefix<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream source, T instance, PrefixStyle style) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) return (T)((TypeModel)RuntimeTypeModel.Default).DeserializeWithLengthPrefix(source, (object)instance, typeof(T), style, 0); } public static bool TryReadLengthPrefix(Stream source, PrefixStyle style, out int length) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) int num = default(int); int num2 = default(int); length = ProtoReader.ReadLengthPrefix(source, false, style, ref num, ref num2); return num2 > 0; } public static bool TryReadLengthPrefix(byte[] buffer, int index, int count, PrefixStyle style, out int length) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) using Stream source = new MemoryStream(buffer, index, count); return TryReadLengthPrefix(source, style, out length); } [Obsolete("This API is no longer required and may be removed in a future release")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public static void FlushPool() { } public static T Deserialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream source) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) State val = State.Create(source, (TypeModel)(object)RuntimeTypeModel.Default, (object)null, -1L); try { return ((State)(ref val)).DeserializeRootImpl<T>(default(T)); } finally { ((State)(ref val)).Dispose(); } } public static T Deserialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream source, T value, SerializationContext context, long length = -1L) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) State val = State.Create(source, (TypeModel)(object)RuntimeTypeModel.Default, (object)context, length); try { return ((State)(ref val)).DeserializeRootImpl<T>(value); } finally { ((State)(ref val)).Dispose(); } } public static T Deserialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream source, T value = default(T), object userState = null, long length = -1L) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) State val = State.Create(source, (TypeModel)(object)RuntimeTypeModel.Default, userState, length); try { return ((State)(ref val)).DeserializeRootImpl<T>(value); } finally { ((State)(ref val)).Dispose(); } } public static object Deserialize([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] Type type, Stream source) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) State val = State.Create(source, (TypeModel)(object)RuntimeTypeModel.Default, (object)null, -1L); try { return ((State)(ref val)).DeserializeRootFallback((object)null, type); } finally { ((State)(ref val)).Dispose(); } } public static T Deserialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(ReadOnlyMemory<byte> source, T value = default(T), object userState = null) { return ((TypeModel)RuntimeTypeModel.Default).Deserialize<T>(source, value, userState); } public static T Deserialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(ReadOnlySequence<byte> source, T value = default(T), object userState = null) { return ((TypeModel)RuntimeTypeModel.Default).Deserialize<T>(source, value, userState); } public static T Deserialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(ReadOnlySpan<byte> source, T value = default(T), object userState = null) { return ((TypeModel)RuntimeTypeModel.Default).Deserialize<T>(source, value, userState); } public static void Serialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream destination, T instance) { Serialize(destination, instance, null); } public static void Serialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream destination, T instance, object userState) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) State val = State.Create(destination, (TypeModel)(object)RuntimeTypeModel.Default, userState); try { TypeModel.SerializeImpl<T>(ref val, instance); } finally { ((State)(ref val)).Dispose(); } } public static void Serialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(IBufferWriter<byte> destination, T instance, object userState = null) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) State val = State.Create(destination, (TypeModel)(object)RuntimeTypeModel.Default, userState); try { TypeModel.SerializeImpl<T>(ref val, instance); } finally { ((State)(ref val)).Dispose(); } } public static void Serialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(SerializationInfo info, T instance) where T : class, ISerializable { Serialize(info, new StreamingContext(StreamingContextStates.Persistence), instance); } public static void Serialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(SerializationInfo info, StreamingContext context, T instance) where T : class, ISerializable { if (info == null) { throw new ArgumentNullException("info"); } if (instance == null) { throw new ArgumentNullException("instance"); } if (instance.GetType() != typeof(T)) { throw new ArgumentException("Incorrect type", "instance"); } using MemoryStream memoryStream = new MemoryStream(); ((TypeModel)RuntimeTypeModel.Default).Serialize<T>((Stream)memoryStream, instance, context.Context); info.AddValue("proto", memoryStream.ToArray()); } public static void Serialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(XmlWriter writer, T instance) where T : IXmlSerializable { if (writer == null) { throw new ArgumentNullException("writer"); } if (instance == null) { throw new ArgumentNullException("instance"); } using MemoryStream memoryStream = new MemoryStream(); Serialize(memoryStream, instance); ArraySegment<byte> arraySegment = default(ArraySegment<byte>); Helpers.GetBuffer(memoryStream, ref arraySegment); writer.WriteBase64(arraySegment.Array, arraySegment.Offset, arraySegment.Count); } public static void SerializeWithLengthPrefix<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream destination, T instance, PrefixStyle style) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) SerializeWithLengthPrefix(destination, instance, style, 0); } public static void SerializeWithLengthPrefix<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream destination, T instance, PrefixStyle style, int fieldNumber) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) ((TypeModel)RuntimeTypeModel.Default).SerializeWithLengthPrefix(destination, (object)instance, typeof(T), style, fieldNumber); } } } namespace ProtoBuf.Serializers { internal static class EnumSerializers { internal static object GetSerializer(Type type) { MemberInfo underlyingProvider = RuntimeTypeModel.GetUnderlyingProvider(GetProvider(type), type); if (!(underlyingProvider is FieldInfo fieldInfo)) { if (underlyingProvider is MethodInfo methodInfo) { return methodInfo.Invoke(null, null); } return null; } return fieldInfo.GetValue(null); } internal static MemberInfo GetProvider(Type type) { if ((object)type == null) { return null; } type = Nullable.GetUnderlyingType(type) ?? type; if (!type.IsEnum) { return null; } string text = Type.GetTypeCode(type) switch { TypeCode.SByte => "CreateSByte", TypeCode.Int16 => "CreateInt16", TypeCode.Int32 => "CreateInt32", TypeCode.Int64 => "CreateInt64", TypeCode.Byte => "CreateByte", TypeCode.UInt16 => "CreateUInt16", TypeCode.UInt32 => "CreateUInt32", TypeCode.UInt64 => "CreateUInt64", _ => null, }; if (text == null) { return null; } return typeof(EnumSerializer).GetMethod(text, BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(type); } } internal static class RepeatedSerializers { [StructLayout(LayoutKind.Auto)] private readonly struct MethodTuple { public string Name => Method.Name; private MethodInfo Method { get; } public int GenericArgCount { get; } public MethodInfo Construct(Type[] targs) { if (GenericArgCount != 0) { return Method.MakeGenericMethod(targs); } return Method; } public MethodTuple(MethodInfo method) { Method = method; GenericArgCount = (method.IsGenericMethodDefinition ? method.GetGenericArguments().Length : 0); } } private sealed class Registration { public bool ExactOnly { get; } public int Priority { get; } private Func<Type, Type, Type[], MemberInfo> Implementation { get; } public MemberInfo Resolve(Type root, Type current) { Type[] arg = (current.IsGenericType ? current.GetGenericArguments() : ((!current.IsArray) ? Type.EmptyTypes : new Type[1] { current.GetElementType() })); return Implementation?.Invoke(root, current, arg); } public Registration(int priority, Func<Type, Type, Type[], MemberInfo> implementation, bool exactOnly) { Priority = priority; Implementation = implementation; ExactOnly = exactOnly; } } private static readonly Hashtable s_providers; private static readonly Hashtable s_methodsPerDeclaringType; private static readonly Hashtable s_knownTypes; private static readonly Registration s_Array; private static readonly Type[] NotSupportedFlavors; private static readonly MethodInfo s_NestedNotSupported; private static readonly MethodInfo s_GeneralNotSupported; internal static MemberInfo Resolve(Type declaringType, string methodName, Type[] targs) { if (targs == null) { targs = Type.EmptyTypes; } MethodTuple[] array = (MethodTuple[])s_methodsPerDeclaringType[declaringType]; if (array == null) { MethodInfo[] methods = declaringType.GetMethods(BindingFlags.Static | BindingFlags.Public); array = Array.ConvertAll(methods, (MethodInfo m) => new MethodTuple(m)); lock (s_methodsPerDeclaringType) { s_methodsPerDeclaringType[declaringType] = array; } } MethodTuple[] array2 = array; for (int num = 0; num < array2.Length; num++) { MethodTuple methodTuple = array2[num]; if (methodTuple.Name == methodName && targs.Length == methodTuple.GenericArgCount) { return methodTuple.Construct(targs); } } return null; } static RepeatedSerializers() { s_methodsPerDeclaringType = new Hashtable(); s_knownTypes = new Hashtable(); s_Array = new Registration(0, (Type root, Type current, Type[] targs) => (!(root == current)) ? null : Resolve(typeof(RepeatedSerializer), "CreateVector", targs), exactOnly: true); NotSupportedFlavors = new Type[7] { typeof(Span<>), typeof(ReadOnlySpan<>), typeof(ReadOnlySequence<>), typeof(ReadOnlyMemory<>), typeof(Memory<>), typeof(ArraySegment<>), typeof(IMemoryOwner<>) }; s_NestedNotSupported = typeof(RepeatedSerializer).GetMethod("CreateNestedDataNotSupported"); s_GeneralNotSupported = typeof(RepeatedSerializer).GetMethod("CreateNotSupported"); s_providers = new Hashtable(); Add(typeof(List<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateList", (root == current) ? targs : new Type[2] { root, targs[0] }), exactOnly: false); Add(typeof(ImmutableArray<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateImmutableArray", targs)); Add(typeof(ImmutableDictionary<, >), (Type root, Type current, Type[] targs) => Resolve(typeof(MapSerializer), "CreateImmutableDictionary", targs)); Add(typeof(ImmutableSortedDictionary<, >), (Type root, Type current, Type[] targs) => Resolve(typeof(MapSerializer), "CreateImmutableSortedDictionary", targs)); Add(typeof(IImmutableDictionary<, >), (Type root, Type current, Type[] targs) => Resolve(typeof(MapSerializer), "CreateIImmutableDictionary", targs)); Add(typeof(ImmutableList<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateImmutableList", targs)); Add(typeof(IImmutableList<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateImmutableIList", targs)); Add(typeof(ImmutableHashSet<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateImmutableHashSet", targs)); Add(typeof(ImmutableSortedSet<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateImmutableSortedSet", targs)); Add(typeof(IImmutableSet<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateImmutableISet", targs)); Add(typeof(ImmutableQueue<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateImmutableQueue", targs)); Add(typeof(IImmutableQueue<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateImmutableIQueue", targs)); Add(typeof(ImmutableStack<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateImmutableStack", targs)); Add(typeof(IImmutableStack<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateImmutableIStack", targs)); Add(typeof(ConcurrentDictionary<, >), (Type root, Type current, Type[] targs) => Resolve(typeof(MapSerializer), "CreateConcurrentDictionary", new Type[3] { root, targs[0], targs[1] }), exactOnly: false); Add(typeof(ConcurrentBag<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateConcurrentBag", new Type[2] { root, targs[0] }), exactOnly: false); Add(typeof(ConcurrentQueue<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateConcurrentQueue", new Type[2] { root, targs[0] }), exactOnly: false); Add(typeof(ConcurrentStack<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateConcurrentStack", new Type[2] { root, targs[0] }), exactOnly: false); Add(typeof(IProducerConsumerCollection<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateIProducerConsumerCollection", new Type[2] { root, targs[0] }), exactOnly: false); Add(typeof(Dictionary<, >), (Type root, Type current, Type[] targs) => Resolve(typeof(MapSerializer), "CreateDictionary", (root == current) ? targs : new Type[3] { root, targs[0], targs[1] }), exactOnly: false); Add(typeof(IDictionary<, >), (Type root, Type current, Type[] targs) => Resolve(typeof(MapSerializer), "CreateDictionary", new Type[3] { root, targs[0], targs[1] }), exactOnly: false); Add(typeof(IReadOnlyDictionary<, >), (Type root, Type current, Type[] targs) => Resolve(typeof(MapSerializer), "CreateIReadOnlyDictionary", targs)); Add(typeof(Queue<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateQueue", new Type[2] { root, targs[0] }), exactOnly: false); Add(typeof(Stack<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateStack", new Type[2] { root, targs[0] }), exactOnly: false); Add(typeof(HashSet<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateSet", new Type[2] { root, targs[0] })); Add(typeof(ISet<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateSet", new Type[2] { root, targs[0] })); Add(typeof(IEnumerable<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateEnumerable", new Type[2] { root, targs[0] }), exactOnly: false); } public static void Add(Type type, Func<Type, Type, Type[], MemberInfo> implementation, bool exactOnly = true, Hashtable externalProviders = null) { Hashtable hashtable = ((externalProviders == null) ? s_providers : externalProviders); if ((object)type == null) { ThrowHelper.ThrowArgumentNullException("type"); } lock (hashtable) { Registration value = new Registration(s_providers.Count * ((externalProviders == null) ? 1 : (-1)) + 1, implementation, exactOnly); hashtable.Add(type, value); } lock (s_knownTypes) { s_knownTypes.Clear(); } } internal static RepeatedSerializerStub TryGetRepeatedProvider(Type type, Hashtable externalProvders = null) { if ((object)type == null || type == typeof(string)) { return null; } RepeatedSerializerStub repeatedSerializerStub = (RepeatedSerializerStub)s_knownTypes[type]; if (repeatedSerializerStub == null) { Type genericTypeDefinition; if (!TypeHelper.IsBytesLike(type) && type.IsGenericType && Array.IndexOf(NotSupportedFlavors, genericTypeDefinition = type.GetGenericTypeDefinition()) >= 0) { if (genericTypeDefinition == typeof(Span<>) || genericTypeDefinition == typeof(ReadOnlySpan<>)) { throw new NotSupportedException("Serialization cannot work with [ReadOnly]Span<T>; [ReadOnly]Memory<T> may be enabled later"); } repeatedSerializerStub = NotSupported(s_GeneralNotSupported, type, type.GetGenericArguments()[0]); } else { MemberInfo providerForType = GetProviderForType(type, externalProvders); if ((object)providerForType == null) { repeatedSerializerStub = ((!type.IsArray || !(type != typeof(byte[]))) ? RepeatedSerializerStub.Empty : NotSupported(s_GeneralNotSupported, type, type.GetElementType())); } else { repeatedSerializerStub = RepeatedSerializerStub.Create(type, providerForType); if (TestIfNestedNotSupported(repeatedSerializerStub)) { repeatedSerializerStub = NotSupported(s_NestedNotSupported, repeatedSerializerStub.ForType, repeatedSerializerStub.ItemType); } } } lock (s_knownTypes) { s_knownTypes[type] = repeatedSerializerStub; } } if (!repeatedSerializerStub.IsEmpty) { return repeatedSerializerStub; } return null; } [MethodImpl(MethodImplOptions.NoInlining)] internal static RepeatedSerializerStub NotSupported(MethodInfo kind, Type collectionType, Type itemType) { return RepeatedSerializerStub.Create(collectionType, kind.MakeGenericMethod(collectionType, itemType)); } private static bool TestIfNestedNotSupported(RepeatedSerializerStub repeated) { if ((object)repeated?.ItemType == null) { return false; } if (!repeated.IsMap && (repeated.ItemType == repeated.ForType || TryGetRepeatedProvider(repeated.ItemType) != null)) { return true; } return false; } private static MemberInfo GetProviderForType(Type type, Hashtable externalProviders) { if ((object)type == null) { return null; } if (TypeHelper.IsBytesLike(type)) { return null; } if (type.IsArray) { Type type2 = type.GetElementType().MakeArrayType(); if (!(type2 == type)) { return null; } return s_Array.Resolve(type, type2); } MemberInfo bestMatch = null; int bestMatchPriority = int.MaxValue; bool bestIsAmbiguous = false; Type type3 = type; if (externalProviders != null) { while ((object)type3 != null && type3 != typeof(object)) { if (TryGetExternalProvider(type, type3, bestMatchPriority, out var member, out var priority, externalProviders)) { Consider(member, priority); } type3 = type3.BaseType; } Type[] interfaces = type.GetInterfaces(); foreach (Type current in interfaces) { if (TryGetExternalProvider(type, current, bestMatchPriority, out var member2, out var priority2, externalProviders)) { Consider(member2, priority2); } } } type3 = type; while ((object)type3 != null && type3 != typeof(object)) { if (TryGetProvider(type, type3, bestMatchPriority, out var member3, out var priority3)) { Consider(member3, priority3); } type3 = type3.BaseType; } Type[] interfaces2 = type.GetInterfaces(); foreach (Type current2 in interfaces2) { if (TryGetProvider(type, current2, bestMatchPriority, out var member4, out var priority4)) { Consider(member4, priority4); } } if (!bestIsAmbiguous) { return bestMatch; } return null; void Consider(MemberInfo memberInfo, int num) { if (num < bestMatchPriority) { bestMatch = memberInfo; bestMatchPriority = num; bestIsAmbiguous = false; } else if (num == bestMatchPriority && !object.Equals(bestMatch, memberInfo)) { bestIsAmbiguous = true; } } } private static bool TryGetProvider(Type root, Type current, int bestMatchPriority, out MemberInfo member, out int priority) { Registration registration = (Registration)s_providers[current]; if (registration == null && current.IsGenericType) { registration = (Registration)s_providers[current.GetGenericTypeDefinition()]; } if (registration == null || registration.Priority > bestMatchPriority || (registration.ExactOnly && root != current)) { member = null; priority = 0; return false; } member = registration.Resolve(root, current); priority = registration.Priority; return true; } private static bool TryGetExternalProvider(Type root, Type current, int bestMatchPriority, out MemberInfo member, out int priority, Hashtable externalProviders) { Registration registration = (Registration)externalProviders[current]; if (registration == null && current.IsGenericType) { registration = (Registration)externalProviders[current.GetGenericTypeDefinition()]; } if (registration == null || registration.Priority > bestMatchPriority || (registration.ExactOnly && root != current)) { member = null; priority = 0; return false; } member = registration.Resolve(root, current); priority = registration.Priority; return true; } } internal sealed class RepeatedSerializerStub { internal static readonly RepeatedSerializerStub Empty = new RepeatedSerializerStub(null, null); private object _serializer; public MemberInfo Provider { get; } public bool IsMap { get; } public bool IsEmpty => (object)Provider == null; public object Serializer => _serializer ?? CreateSerializer(); public Type ForType { get; } public Type ItemType { get; } internal bool IsValidProtobufMap(RuntimeTypeModel model, CompatibilityLevel compatibilityLevel, DataFormat dataFormat) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) if (!IsMap) { return false; } ResolveMapTypes(out var keyType, out var valueType); if (!IsValidKey(keyType, compatibilityLevel, dataFormat)) { return false; } RepeatedSerializerStub repeatedSerializerStub = ((model == null) ? RepeatedSerializers.TryGetRepeatedProvider(valueType) : model.TryGetRepeatedProvider(valueType, (CompatibilityLevel)0)); if (repeatedSerializerStub != null) { return false; } return true; static bool IsValidKey(Type type, CompatibilityLevel val, DataFormat val2) { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Invalid comparison between Unknown and I4 //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Invalid comparison between Unknown and I4 if ((object)type == null) { return false; } if (type.IsEnum) { return true; } if (type == typeof(string)) { return true; } if (!type.IsValueType) { return false; } if ((object)Nullable.GetUnderlyingType(type) != null) { return false; } TypeCode typeCode = Type.GetTypeCode(type); if ((uint)(typeCode - 5) <= 7u) { return true; } if ((int)val >= 300 && type == typeof(Guid) && (int)val2 != 3) { return true; } return false; } } [MethodImpl(MethodImplOptions.NoInlining)] private object CreateSerializer() { try { MemberInfo underlyingProvider = RuntimeTypeModel.GetUnderlyingProvider(Provider, ForType); object serializer; if (!(underlyingProvider is FieldInfo fieldInfo)) { if (!(underlyingProvider is MethodInfo { IsStatic: not false } methodInfo)) { goto IL_004d; } serializer = methodInfo.Invoke(null, null); } else { if (!fieldInfo.IsStatic) { goto IL_004d; } serializer = fieldInfo.GetValue(null); } goto IL_004f; IL_004d: serializer = null; goto IL_004f; IL_004f: _serializer = serializer; return _serializer; } catch (TargetInvocationException ex) when (ex.InnerException != null) { throw ex.InnerException; } } internal void EmitProvider(CompilerContext ctx) { EmitProvider(ctx.IL); } private void EmitProvider(ILGenerator il) { MemberInfo underlyingProvider = RuntimeTypeModel.GetUnderlyingProvider(Provider, ForType); RuntimeTypeModel.EmitProvider(underlyingProvider, il); } public static RepeatedSerializerStub Create(Type forType, MemberInfo provider) { if ((object)provider != null) { return new RepeatedSerializerStub(forType, provider); } return Empty; } private RepeatedSerializerStub(Type forType, MemberInfo provider) { ForType = forType; Provider = provider; IsMap = CheckIsMap(provider, out var itemType); ItemType = itemType; } private static bool CheckIsMap(MemberInfo provider, out Type itemType) { Type type = ((provider is MethodInfo methodInfo) ? methodInfo.ReturnType : ((provider is FieldInfo fieldInfo) ? fieldInfo.FieldType : ((provider is PropertyInfo propertyInfo) ? propertyInfo.PropertyType : ((!(provider is Type type2)) ? null : type2)))); Type type3 = type; while ((object)type3 != null && type3 != typeof(object)) { if (type3.IsGenericType) { Type genericTypeDefinition = type3.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(MapSerializer<, , >)) { Type[] genericArguments = type3.GetGenericArguments(); itemType = typeof(KeyValuePair<, >).MakeGenericType(genericArguments[1], genericArguments[2]); return true; } if (genericTypeDefinition == typeof(RepeatedSerializer<, >)) { Type[] genericArguments2 = type3.GetGenericArguments(); itemType = genericArguments2[1]; return false; } } type3 = type3.BaseType; } itemType = null; return false; } internal void ResolveMapTypes(out Type keyType, out Type valueType) { keyType = (valueType = null); if (IsMap) { Type[] genericArguments = ItemType.GetGenericArguments(); keyType = genericArguments[0]; valueType = genericArguments[1]; } } } } namespace ProtoBuf.Meta { internal abstract class AttributeMap { private sealed class ReflectionAttributeMap : AttributeMap { private readonly Attribute attribute; public override object Target => attribute; public override Type AttributeType => attribute.GetType(); public ReflectionAttributeMap(Attribute attribute) { this.attribute = attribute; } public override bool TryGet(string key, bool publicOnly, out object value) { MemberInfo[] instanceFieldsAndProperties = Helpers.GetInstanceFieldsAndProperties(attribute.GetType(), publicOnly); MemberInfo[] array = instanceFieldsAndProperties; foreach (MemberInfo memberInfo in array) { if (string.Equals(memberInfo.Name, key, StringComparison.OrdinalIgnoreCase)) { if (memberInfo is PropertyInfo propertyInfo) { value = propertyInfo.GetValue(attribute, null); return true; } if (memberInfo is FieldInfo fieldInfo) { value = fieldInfo.GetValue(attribute); return true; } throw new NotSupportedException(memberInfo.GetType().Name); } } value = null; return false; } } public abstract Type AttributeType { get; } public abstract object Target { get; } [Obsolete("Please use AttributeType instead")] public new Type GetType() { return AttributeType; } public override string ToString() { return AttributeType?.FullName ?? ""; } public abstract bool TryGet(string key, bool publicOnly, out object value); public bool TryGet(string key, out object value) { return TryGet(key, publicOnly: true, out value); } public static AttributeMap[] Create(Type type, bool inherit) { object[] customAttributes = type.GetCustomAttributes(inherit); AttributeMap[] array = new AttributeMap[customAttributes.Length]; for (int i = 0; i < customAttributes.Length; i++) { array[i] = new ReflectionAttributeMap((Attribute)customAttributes[i]); } return array; } public static AttributeMap[] Create(MemberInfo member, bool inherit) { object[] customAttributes = member.GetCustomAttributes(inherit); AttributeMap[] array = new AttributeMap[customAttributes.Length]; for (int i = 0; i < customAttributes.Length; i++) { array[i] = new ReflectionAttributeMap((Attribute)customAttributes[i]); } return array; } public static AttributeMap[] Create(Assembly assembly) { object[] customAttributes = assembly.GetCustomAttributes(inherit: false); AttributeMap[] array = new AttributeMap[customAttributes.Length]; for (int i = 0; i < customAttributes.Length; i++) { array[i] = new ReflectionAttributeMap((Attribute)customAttributes[i]); } return array; } } public sealed class AutoCompileTypeModel : TypeModel { private static readonly Hashtable s_assemblyModels = new Hashtable(); public static TypeModel Instance { get; } = (TypeModel)(object)new AutoCompileTypeModel(); public static TypeModel CreateForAssembly<T>() { return CreateForAssembly(typeof(T).Assembly, null); } public static TypeModel CreateForAssembly(Type type) { if ((object)type == null) { ThrowHelper.ThrowArgumentNullException("type"); } return CreateForAssembly(type.Assembly, null); } public static TypeModel CreateForAssembly(Assembly assembly) { return CreateForAssembly(assembly, null); } public static TypeModel CreateForAssembly(Assembly assembly, RuntimeTypeModel.CompilerOptions options) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown if ((object)assembly == null) { ThrowHelper.ThrowArgumentNullException("assembly"); } if (options == null) { TypeModel val = (TypeModel)s_assemblyModels[assembly]; if (val != null) { return val; } } return CreateForAssemblyImpl(assembly, options); } private AutoCompileTypeModel() { } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static TypeModel ForAssembly(Type type) { if ((object)type != null) { return CreateForAssembly(type.Assembly, null); } return NullModel.Singleton; } public override string GetSchema(SchemaGenerationOptions options) { return ForAssembly(options.HasTypes ? options.Types.First() : null).GetSchema(options); } protected override ISerializer<T> GetSerializer<T>() { return ForAssembly(typeof(T)).GetSerializerCore<T>((CompatibilityLevel)0); } internal override bool IsKnownType<T>(CompatibilityLevel ambient) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) return ForAssembly(typeof(T)).IsKnownType<T>(ambient); } private static TypeModel CreateForAssemblyImpl(Assembly assembly, RuntimeTypeModel.CompilerOptions options) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown if ((object)assembly == null) { throw new ArgumentNullException("assembly"); } lock (assembly) { TypeModel val = (TypeModel)s_assemblyModels[assembly]; if (val != null) { return val; } RuntimeTypeModel runtimeTypeModel = null; Type[] types = assembly.GetTypes(); foreach (Type type in types) { if (!type.IsGenericTypeDefinition && RuntimeTypeModel.IsFullyPublic(type) && type.IsDefined(typeof(ProtoContractAttribute), inherit: true) && (options == null || options.OnIncludeType(type))) { (runtimeTypeModel ?? (runtimeTypeModel = RuntimeTypeModel.Create("CreateForAssemblyImpl"))).Add(type, applyDefaultBehaviour: true); } } if (runtimeTypeModel == null) { throw new InvalidOperationException("No types marked [ProtoContract] found in assembly '" + assembly.GetName().Name + "'"); } TypeModel val2 = runtimeTypeModel.Compile(options); s_assemblyModels[assembly] = val2; return val2; } } } public class CallbackSet { private readonly MetaType metaType; private MethodInfo beforeSerialize; private MethodInfo afterSerialize; private MethodInfo beforeDeserialize; private MethodInfo afterDeserialize; internal unsafe MethodInfo this[CallbackType callbackType] => (int)callbackType switch { 0 => beforeSerialize, 1 => afterSerialize, 2 => beforeDeserialize, 3 => afterDeserialize, _ => throw new ArgumentException("Callback type not supported: " + ((object)(*(CallbackType*)(&callbackType))/*cast due to .constrained prefix*/).ToString(), "callbackType"), }; public MethodInfo BeforeSerialize { get { return beforeSerialize; } set { beforeSerialize = SanityCheckCallback(value); } } public MethodInfo BeforeDeserialize { get { return beforeDeserialize; } set { beforeDeserialize = SanityCheckCallback(value); } } public MethodInfo AfterSerialize { get { return afterSerialize; } set { afterSerialize = SanityCheckCallback(value); } } public MethodInfo AfterDeserialize { get { return afterDeserialize; } set { afterDeserialize = SanityCheckCallback(value); } } public bool NonTrivial { get { if ((object)beforeSerialize == null && (object)beforeDeserialize == null && (object)afterSerialize == null) { return (object)afterDeserialize != null; } return true; } } internal CallbackSet(MetaType metaType) { this.metaType = metaType ?? throw new ArgumentNullException("metaType"); } internal static bool CheckCallbackParameters(MethodInfo method) { ParameterInfo[] parameters = method.GetParameters(); for (int i = 0; i < parameters.Length; i++) { Type parameterType = parameters[i].ParameterType; if (!(parameterType == typeof(SerializationContext)) && !(parameterType == typeof(Type)) && !(parameterType == typeof(StreamingContext))) { return false; } } return true; } private MethodInfo SanityCheckCallback(MethodInfo callback) { metaType.ThrowIfFrozen(); if ((object)callback == null) { return callback; } if (callback.IsStatic) { throw new ArgumentException("Callbacks cannot be static", "callback"); } if (callback.ReturnType != typeof(void) || !CheckCallbackParameters(callback)) { throw CreateInvalidCallbackSignature(callback); } return callback; } internal static Exception CreateInvalidCallbackSignature(MethodInfo method) { return new NotSupportedException("Invalid callback signature in " + method.DeclaringType.FullName + "." + method.Name); } } [StructLayout(LayoutKind.Auto)] public readonly struct EnumMember : IEquatable<EnumMember>, IComparable<EnumMember> { public string Name { get; } public object Value { get; } internal bool HasValue { get { if (Value != null) { return !string.IsNullOrWhiteSpace(Name); } return false; } } public EnumMember(object value, string name) { Name = name; Value = value; } internal int? TryGetInt32() { return TryGetInt32(Value); } internal static int? TryGetInt32(object value) { if (value != null) { Type type = value.GetType(); if (type.IsEnum) { type = Enum.GetUnderlyingType(type); } switch (Type.GetTypeCode(type)) { case TypeCode.SByte: return (sbyte)value; case TypeCode.Int16: return (short)value; case TypeCode.Int32: return (int)value; case TypeCode.Byte: return (byte)value; case TypeCode.UInt16: return (ushort)value; case TypeCode.UInt32: { uint num3 = (uint)value; if (num3 <= int.MaxValue) { return (int)num3; } break; } case TypeCode.UInt64: { ulong num2 = (ulong)value; if (num2 <= int.MaxValue) { return (int)num2; } break; } case TypeCode.Int64: { long num = (long)value; if (num >= int.MinValue && num <= int.MaxValue) { return (int)num; } break; } } } return null; } public EnumMember WithName(string name) { return new EnumMember(Value, name); } public EnumMember WithValue(object value) { return new EnumMember(value, Name); } public EnumMember Normalize(Type type) { return WithValue(Normalize(Value, type)); } public bool Equals<T>(T value) where T : unmanaged { return object.Equals(Normalize(Value, typeof(T)), Normalize(value, typeof(T))); } public override string ToString() { return $"{Name}={Value}"; } public override int GetHashCode() { return (Name?.GetHashCode() ?? 0) ^ (Value?.GetHashCode() ?? 0); } public override bool Equals(object obj) { if (obj is EnumMember other) { return Equals(other); } return false; } public bool Equals(EnumMember other) { if (string.Equals(Name, other.Name)) { return object.Equals(Value, other.Value); } return false; } public static bool operator ==(EnumMember x, EnumMember y) { return x.Equals(y); } public static bool operator !=(EnumMember x, EnumMember y) { return !x.Equals(y); } private static object Normalize(object value, Type type) { return Convert.ChangeType(value, type.IsEnum ? Enum.GetUnderlyingType(type) : type); } public static EnumMember Create<T>(T value) where T : unmanaged { return new EnumMember(value, value.ToString()).Normalize(typeof(T)); } internal void Validate() { if (string.IsNullOrWhiteSpace(Name)) { ThrowHelper.ThrowInvalidOperationException("All enum declarations must have valid names", (Exception)null); } } public int CompareTo(EnumMember other) { int? num = TryGetInt32(); int? num2 = other.TryGetInt32(); if (!num.HasValue && !num2.HasValue) { return 0; } if (!num.HasValue) { return 1; } if (!num2.HasValue) { return -1; } if (num.Value < 0 && num2.Value >= 0) { return 1; } if (num2.Value < 0 && num.Value >= 0) { return -1; } return num.Value.CompareTo(num2.Value); } } public sealed class MetaType : ISerializerProxy { internal sealed class Comparer : IComparer, IComparer<MetaType> { private readonly HashSet<Type> _callstack; internal Comparer(HashSet<Type> callstack) { _callstack = callstack; } public int Compare(object x, object y) { return Compare(x as MetaType, y as MetaType); } public int Compare(MetaType x, MetaType y) { if (x == y) { return 0; } if (x == null) { return -1; } if (y == null) { return 1; } return string.Compare(x.GetSchemaTypeName(_callstack), y.GetSchemaTypeName(_callstack), StringComparison.Ordinal); } } [Flags] internal enum AttributeFamily { None = 0, ProtoBuf = 1, DataContractSerializer = 2, XmlSerializer = 4, AutoTuple = 8 } private enum TypeOptions : ushort { None = 0, Pending = 1, Frozen = 4, PrivateOnApi = 8, SkipConstructor = 0x10, AutoTuple = 0x40, IgnoreListHandling = 0x80, IsGroup = 0x100, IgnoreUnknownSubTypes = 0x200 } private class ExtraLayerValueMembers : IEnumerable<NullWrappedValueMemberData>, IEnumerable { private readonly Dictionary<string, Type> _schemaMemberTypeMap = new Dictionary<string, Type>(); private readonly Dictionary<string, NullWrappedValueMemberData> _wrappedSchemaMembers = new Dictionary<string, NullWrappedValueMemberData>(); public bool IsEmpty() { return _wrappedSchemaMembers.Count == 0; } public NullWrappedValueMemberData Add(string schemaTypeName, ValueMember valueMember) { if (!_schemaMemberTypeMap.ContainsKey(schemaTypeName)) { NullWrappedValueMemberData nullWrappedValueMemberData = new NullWrappedValueMemberData(valueMember, schemaTypeName); _schemaMemberTypeMap[schemaTypeName] = nullWrappedValueMemberData.ItemType; _wrappedSchemaMembers[nullWrappedValueMemberData.WrappedSchemaTypeName] = nullWrappedValueMemberData; return nullWrappedValueMemberData; } Type type = _schemaMemberTypeMap[schemaTypeName]; if (type == valueMember.ItemType) { NullWrappedValueMemberData nullWrappedValueMemberData2 = new NullWrappedValueMemberData(valueMember, schemaTypeName); _wrappedSchemaMembers[nullWrappedValueMemberData2.WrappedSchemaTypeName] = nullWrappedValueMemberData2; return nullWrappedValueMemberData2; } if (string.IsNullOrEmpty(valueMember.Name) || valueMember.Member?.Name == valueMember.Name) { NullWrappedValueMemberData nullWrappedValueMemberData3 = new NullWrappedValueMemberData(valueMember, schemaTypeName, null, hasSchemaTypeNameCollision: true); _wrappedSchemaMembers[nullWrappedValueMemberData3.WrappedSchemaTypeName] = nullWrappedValueMemberData3; return nullWrappedValueMemberData3; } string name = valueMember.Name; if (_schemaMemberTypeMap.ContainsKey(name)) { NullWrappedValueMemberData nullWrappedValueMemberData4 = new NullWrappedValueMemberData(valueMember, schemaTypeName, name, hasSchemaTypeNameCollision: true); _wrappedSchemaMembers[nullWrappedValueMemberData4.WrappedSchemaTypeName] = nullWrappedValueMemberData4; return nullWrappedValueMemberData4; } NullWrappedValueMemberData nullWrappedValueMemberData5 = new NullWrappedValueMemberData(valueMember, schemaTypeName, name); _schemaMemberTypeMap[name] = nullWrappedValueMemberData5.ItemType; _wrappedSchemaMembers[nullWrappedValueMemberData5.WrappedSchemaTypeName] = nullWrappedValueMemberData5; return nullWrappedValueMemberData5; } public IEnumerator<NullWrappedValueMemberData> GetEnumerator() { return _wrappedSchemaMembers.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private MetaType baseType; private CompatibilityLevel _compatibilityLevel; private List<SubType> _subTypes; private CallbackSet callbacks; private string name; private string origin; private MethodInfo factory; private readonly RuntimeTypeModel model; private IProtoTypeSerializer _serializer; private Type constructType; internal Type surrogateType; internal DataFormat surrogateDataFormat; private MethodInfo underlyingToSurrogate; private MethodInfo surrogateToUnderlying; private List<ValueMember> _fields; private List<EnumMember> _enums = new List<EnumMember>(); private volatile TypeOptions flags; private Type _serializerType; private List<ProtoReservedAttribute> _reservations; IRuntimeProtoSerializerNode ISerializerProxy.Serializer => Serializer; public MetaType BaseType => baseType; internal RuntimeTypeModel Model => model; public CompatibilityLevel CompatibilityLevel { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return _compatibilityLevel; } set { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (value != _compatibilityLevel) { if (HasFields) { ThrowHelper.ThrowInvalidOperationException($"{CompatibilityLevel} cannot be set once fields have been defined", (Exception)null); } CompatibilityLevelAttribute.AssertValid(value); _compatibilityLevel = value; } } } public bool IncludeSerializerMethod { get { return !HasFlag(TypeOptions.PrivateOnApi); } set { SetFlag(TypeOptions.PrivateOnApi, !value, throwIfFrozen: true); } } public bool AsReferenceDefault { get { return false; } [Obsolete("Reference-tracking and dynamic-type are not currently implemented in this build; they may be reinstated later; this is partly due to doubts over whether the features are adviseable, and partly over confidence in testing all the scenarios (it takes time; that time hasn't get happened); feedback is invited", true)] set { if (value != AsReferenceDefault) { ThrowHelper.ThrowNotSupportedException(); } } } public bool HasCallbacks { get { if (callbacks != null) { return callbacks.NonTrivial; } return false; } } public bool HasSubtypes { get { if (_subTypes != null) { return _subTypes.Count != 0; } return false; } } public int SubtypesCount => _subTypes?.Count ?? 0; public CallbackSet Callbacks => callbacks ?? (callbacks = new CallbackSet(this)); private bool IsValueType => Type.IsValueType; public string Name { get { return name; } set { ThrowIfFrozen(); name = value; } } public string Origin { get { return origin; } set { ThrowIfFrozen(); origin = value; } } public Type Type { get; } internal IProtoTypeSerializer Serializer { get { if (_serializer == null) { int opaqueToken = 0; try { model.TakeLock(ref opaqueToken); if (_serializer == null) { SetFlag(TypeOptions.Frozen, value: true, throwIfFrozen: false); _serializer = BuildSerializer(); if (model.AutoCompile) { CompileInPlace(); } } } finally { model.ReleaseLock(opaqueToken); } } return _serializer; } } public bool UseConstructor { get { return !HasFlag(TypeOptions.SkipConstructor); } set { SetFlag(TypeOptions.SkipConstructor, !value, throwIfFrozen: true); } } public Type ConstructType { get { return constructType; } set { ThrowIfFrozen(); constructType = value; } } internal bool HasSurrogate => (object)surrogateType != null; public ValueMember this[int fieldNumber] { get { if (HasFields) { foreach (ValueMember field in Fields) { if (field.FieldNumber == fieldNumber) { return field; } } } return null; } } public ValueMember this[MemberInfo member] { get { if ((object)member == null || !HasFields) { return null; } foreach (ValueMember field in Fields) { if (field.Member == member || field.BackingMember == member) { return field; } } return null; } } internal bool HasFields { get { if (_fields != null) { return _fields.Count != 0; } return false; } } internal List<ValueMember> Fields => _fields ?? (_fields = new List<ValueMember>()); internal List<EnumMember> Enums => _enums ?? (_enums = new List<EnumMember>()); internal bool HasEnums { get { if (_enums != null) { return _enums.Count != 0; } return false; } } public bool EnumPassthru { [Obsolete("Enum value maps have been deprecated and are no longer supported; all enums are now effectively pass-thru; custom maps should be applied via shadow properties; in C#, lambda-based 'switch expressions' make for very convenient shadow properties", false)] get { return Type.IsEnum; } [Obsolete("Enum value maps have been deprecated and are no longer supported; all enums are now effectively pass-thru; custom maps should be applied via shadow properties; in C#, lambda-based 'switch expressions' make for very convenient shadow properties", true)] set { if (value != EnumPassthru) { ThrowHelper.ThrowNotSupportedException(); } } } public bool IgnoreListHandling { get { return HasFlag(TypeOptions.IgnoreListHandling); } set { SetFlag(TypeOptions.IgnoreListHandling, value, throwIfFrozen: true); model.ResetServiceCache(Type); } } public bool IgnoreUnknownSubTypes { get { return HasFlag(TypeOptions.IgnoreUnknownSubTypes); } set { SetFlag(TypeOptions.IgnoreUnknownSubTypes, value, throwIfFrozen: true); } } internal bool Pending { get { return HasFlag(TypeOptions.Pending); } set { SetFlag(TypeOptions.Pending, value, throwIfFrozen: false); } } public Type SerializerType { get { return _serializerType; } set { if (value != _serializerType) { if (!value.IsClass) { ThrowHelper.ThrowArgumentException("Custom serializer providers must be classes", "SerializerType"); } ThrowIfFrozen(); _serializerType = value; } } } internal bool IsAutoTuple => HasFlag(TypeOptions.AutoTuple); public bool IsGroup { get { return HasFlag(TypeOptions.IsGroup); } set { SetFlag(TypeOptions.IsGroup, value, throwIfFrozen: true); } } internal bool HasReservations => (_reservations?.Count ?? 0) != 0; public override string ToString() { return Type.ToString(); } private bool IsValidSubType(Type subType) { if ((object)subType != null && !subType.IsValueType) { return Type.IsAssignableFrom(subType); } return false; } public MetaType AddSubType(int fieldNumber, Type derivedType) { return AddSubType(fieldNumber, derivedType, (DataFormat)0); } private static void ThrowSubTypeWithSurrogate(Type type) { ThrowHelper.ThrowInvalidOperationException("Types with surrogates cannot be used in inheritance hierarchies: " + TypeHelper.NormalizeName(type), (Exception)null); } public MetaType AddSubType(int fieldNumber, Type derivedType, DataFormat dataFormat) { //IL_00ef: Unknown result type (might be due to invalid IL or missing references) if ((object)derivedType == null) { throw new ArgumentNullException("derivedType"); } if (fieldNumber < 1) { throw new ArgumentOutOfRangeException("fieldNumber"); } if ((!Type.IsClass && !Type.IsInterface) || Type.IsSealed) { throw new InvalidOperationException("Sub-types can only be added to non-sealed classes: " + TypeHelper.NormalizeName(Type)); } if (!IsValidSubType(derivedType)) { throw new ArgumentException(TypeHelper.NormalizeName(derivedType) + " is not a valid sub-type of " + TypeHelper.NormalizeName(Type), "derivedType"); } int opaqueToken = 0; try { model.TakeLock(ref opaqueToken); MetaType metaType = model[derivedType]; ThrowIfFrozen(); metaType.ThrowIfFrozen(); if (IsAutoTuple || metaType.IsAutoTuple) { ThrowTupleTypeWithInheritance(derivedType); } if ((object)surrogateType != null) { ThrowSubTypeWithSurrogate(Type); } if ((object)metaType.surrogateType != null) { ThrowSubTypeWithSurrogate(derivedType); } SubType item = new SubType(fieldNumber, metaType, dataFormat); ThrowIfFrozen(); metaType.SetBaseType(this); (_subTypes ?? (_subTypes = new List<SubType>())).Add(item); return this; } finally { model.ReleaseLock(opaqueToken); } } private static void ThrowTupleTypeWithInheritance(Type type) { ThrowHelper.ThrowInvalidOperationException("Tuple-based types cannot be used in inheritance hierarchies: " + TypeHelper.NormalizeName(type), (Exception)null); } private void SetBaseType(MetaType baseType) { if (baseType == null) { throw new ArgumentNullException("baseType"); } if (this.baseType == baseType) { return; } if (this.baseType != null) { throw new InvalidOperationException("Type '" + this.baseType.Type.FullName + "' can only participate in one inheritance hierarchy"); } for (MetaType metaType = baseType; metaType != null; metaType = metaType.baseType) { if (metaType == this) { throw new InvalidOperationException("Cyclic inheritance of '" + this.baseType.Type.FullName + "' is not allowed"); } } this.baseType = baseType; } public MetaType SetCallbacks(MethodInfo beforeSerialize, MethodInfo afterSerialize, MethodInfo beforeDeserialize, MethodInfo afterDeserialize) { CheckSetCallbacks(); CallbackSet callbackSet = Callbacks; callbackSet.BeforeSerialize = beforeSerialize; callbackSet.AfterSerialize = afterSerialize; callbackSet.BeforeDeserialize = beforeDeserialize; callbackSet.AfterDeserialize = afterDeserialize; return this; } private void CheckSetCallbacks() { ThrowIfFrozen(); ThrowIfAutoTuple(); } public MetaType SetCallbacks(string beforeSerialize, string afterSerialize, string beforeDeserialize, string afterDeserialize) { CheckSetCallbacks(); CallbackSet callbackSet = Callbacks; callbackSet.BeforeSerialize = ResolveMethod(beforeSerialize, instance: true); callbackSet.AfterSerialize = ResolveMethod(afterSerialize, instance: true); callbackSet.BeforeDeserialize = ResolveMethod(beforeDeserialize, instance: true); callbackSet.AfterDeserialize = ResolveMethod(afterDeserialize, instance: true); return this; } public string GetSchemaTypeName() { return GetSchemaTypeName(null); } internal string GetSchemaTypeName(HashSet<Type> callstack) { if (callstack == null) { callstack = new HashSet<Type>(); } if (!callstack.Add(Type)) { return Type.Name; } try { if ((object)surrogateType != null && !callstack.Contains(surrogateType)) { return model[surrogateType].GetSchemaTypeName(callstack); } if (!string.IsNullOrEmpty(name)) { return name; } string text = Type.Name; if (Type.IsArray) { return GetArrayName(Type.GetElementType()); } if (Type.IsGenericType) { StringBuilder stringBuilder = new StringBuilder(text); int num = text.IndexOf('`'); if (num >= 0) { stringBuilder.Length = num; } Type[] genericArguments = Type.GetGenericArguments(); foreach (Type type in genericArguments) { stringBuilder.Append('_'); Type type2 = type; MetaType metaType; if (((TypeModel)model).IsDefined(type2) && (metaType = model[type2]) != null) { stringBuilder.Append(LastPart(metaType.GetSchemaTypeName(callstack))); continue; } if (type2.IsArray) { stringBuilder.Append(GetArrayName(type2.GetElementType())); continue; } metaType = null; try { metaType = model.Add(type2, applyDefaultBehaviour: true, (CompatibilityLevel)0); } catch { } if (metaType != null) { stringBuilder.Append(metaType.GetSchemaTypeName(callstack)); } else { stringBuilder.Append(type2.Name); } } return stringBuilder.ToString(); } return text; } finally { callstack.Remove(Type); } string GetArrayName(Type elementType) { MetaType metaType2; string text2 = ((((TypeModel)model).IsDefined(elementType) && (metaType2 = model[elementType]) != null) ? metaType2.GetSchemaTypeName(callstack) : elementType.Name); return "Array_" + text2; } static string LastPart(string value) { if (string.IsNullOrWhiteSpace(value)) { return value; } int num2 = value.LastIndexOf('.'); if (num2 >= 0) { return value.Substring(num2 + 1); } return value; } } internal string GuessPackage() { string text = Name; if (string.IsNullOrWhiteSpace(text)) { return null; } if (text[0] != '.') { return null; } return text[..text.LastIndexOf('.')].Trim('.').Trim(); } public MetaType SetFactory(MethodInfo factory) { RuntimeTypeModel.VerifyFactory(factory, Type); ThrowIfFrozen(); ThrowIfAutoTuple(); this.factory = factory; return this; } public MetaType SetFactory(string factory) { return SetFactory(ResolveMethod(factory, instance: false)); } private MethodInfo ResolveMethod(string name, bool instance) { if (string.IsNullOrEmpty(name)) { return null; } if (!instance) { return Helpers.GetStaticMethod(Type, name); } return Helpers.GetInstanceMethod(Type, name); } internal static Exception InbuiltType(Type type, Exception innerException = null) { string message = "Data of this type has inbuilt behaviour, and cannot be added to a model in this way: " + type.FullName; if (innerException != null) { return new ArgumentException(message, innerException); } return new ArgumentException(message); } internal MetaType(RuntimeTypeModel model, Type type, MethodInfo factory) { this.factory = factory; if (model == null) { throw new ArgumentNullException("model"); } if ((object)type == null) { throw new ArgumentNullException("type"); } IRuntimeProtoSerializerNode runtimeProtoSerializerNode = model.TryGetBasicTypeSerializer(type); if (runtimeProtoSerializerNode != null) { throw InbuiltType(type); } Type = type; if (type.IsArray) { SetFlag(TypeOptions.Frozen, value: true, throwIfFrozen: false); } this.model = model; } internal void ThrowIfFrozen() { if ((flags & TypeOptions.Frozen) != TypeOptions.None) { throw new InvalidOperationException("The type cannot be changed once a serializer has been generated for " + Type.FullName); } } internal Type GetInheritanceRoot() { if (Type.IsValueType) { return null; } MetaType rootType = GetRootType(this); if (rootType != this) { return rootType.Type; } if (_subTypes != null && _subTypes.Count != 0) { return rootType.Type; } return null; } private SerializerFeatures GetFeatures() { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) if (Type.IsEnum) { return (SerializerFeatures)48; } if (!Type.IsValueType) { MetaType rootType = GetRootType(this); if (rootType != this) { return rootType.GetFeatures(); } } SerializerFeatures val = (SerializerFeatures)64; return (SerializerFeatures)(val | (IsGroup ? 19 : 18)); } private bool HasRealInheritance() { if (baseType == null || baseType == this) { return (_subTypes?.Count ?? 0) > 0; } return true; } private IProtoTypeSerializer BuildSerializer() { //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_026b: Unknown result type (might be due to invalid IL or missing references) //IL_0279: Unknown result type (might be due to invalid IL or missing references) //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_01a0: Unknown result type (might be due to invalid IL or missing references) //IL_047f: Unknown result type (might be due to invalid IL or missing references) if ((object)SerializerType != null) { return ExternalSerializer.Create(Type, SerializerType); } Validate(); RepeatedSerializerStub repeatedSerializerStub = model.TryGetRepeatedProvider(Type, (CompatibilityLevel)0); if (repeatedSerializerStub != null) { if ((object)surrogateType != null) { throw new ArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot use a surrogate"); } if (_subTypes != null && _subTypes.Count != 0) { throw new ArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot be subclassed"); } ValueMember valueMember = new ValueMember(model, 1, Type, repeatedSerializerStub.ItemType, null, (DataFormat)0) { CompatibilityLevel = CompatibilityLevel }; return TypeSerializer.Create(Type, new int[1] { 1 }, new IRuntimeProtoSerializerNode[1] { valueMember.Serializer }, null, isRootType: true, useConstructor: true, !IgnoreUnknownSubTypes, null, constructType, factory, GetInheritanceRoot(), GetFeatures()); } bool flag = HasRealInheritance(); if ((object)surrogateType != null) { if (flag) { ThrowSubTypeWithSurrogate(Type); } WireType defaultWireType; IRuntimeProtoSerializerNode runtimeProtoSerializerNode = ValueMember.TryGetCoreSerializer(Model, surrogateDataFormat, CompatibilityLevel, surrogateType, out defaultWireType, asReference: false, dynamicType: false, overwriteList: false, allowComplexTypes: false); SerializerFeatures features; if (runtimeProtoSerializerNode != null) { try { features = ExternalSerializer.Create(surrogateType, typeof(PrimaryTypeProvider)).Features; } catch (Exception innerException) { throw InbuiltType(surrogateType, innerException); } } else { MetaType metaType = model[surrogateType]; MetaType metaType2; while ((metaType2 = metaType.baseType) != null) { if (metaType.HasRealInheritance()) { ThrowSubTypeWithSurrogate(metaType.Type); } metaType = metaType2; } IProtoTypeSerializer serializer = metaType.Serializer; features = serializer.Features; runtimeProtoSerializerNode = serializer; } return (IProtoTypeSerializer)Activator.CreateInstance(typeof(SurrogateSerializer<>).MakeGenericType(Type), surrogateType, underlyingToSurrogate, surrogateToUnderlying, runtimeProtoSerializerNode, features); } if (IsAutoTuple) { if (flag) { ThrowTupleTypeWithInheritance(Type); } MemberInfo[] mappedMembers; ConstructorInfo constructorInfo = ResolveTupleConstructor(Type, out mappedMembers) ?? throw new InvalidOperationException(); return (IProtoTypeSerializer)Activator.CreateInstance(typeof(TupleSerializer<>).MakeGenericType(Type), model, constructorInfo, mappedMembers, GetFeatures(), CompatibilityLevel); } if (HasFields) { Fields.TrimExcess(); } if (HasEnums) { Enums.TrimExcess(); } int num = _fields?.Count ?? 0; int num2 = _subTypes?.Count ?? 0; int[] array = new int[num + num2]; IRuntimeProtoSerializerNode[] array2 = new IRuntimeProtoSerializerNode[num + num2]; int num3 = 0; if (num2 != 0) { foreach (SubType subType in _subTypes) { if (!subType.DerivedType.IgnoreListHandling && model.TryGetRepeatedProvider(subType.DerivedType.Type, (CompatibilityLevel)0) != null) { ThrowHelper.ThrowArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot be used as a subclass"); } array[num3] = subType.FieldNumber; array2[num3++] = subType.GetSerializer(Type); } } if (num != 0) { foreach (ValueMember field in _fields) { array[num3] = field.FieldNumber; array2[num3++] = field.Serializer
System.Collections.Immutable.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Threading; using FxResources.System.Collections.Immutable; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("System.Collections.Immutable.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001004b86c4cb78549b34bab61a3b1800e23bfeb5b3ec390074041536a7e3cbd97f5f04cf0f857155a8928eaa29ebfd11cfbbad3ba70efea7bda3226c6a8d370a4cd303f714486b6ebc225985a638471e6ef571cc92a4613c00b8fa65d61ccee0cbe5f36330c9a01f4183559f1bef24cc2917c6d913e3a541333a1d05d9bed22b38cb")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Collections.Immutable")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("This package provides collections that are thread safe and guaranteed to never change their contents, also known as immutable collections. Like strings, any methods that perform modifications will not change the existing instance but instead return a new instance. For efficiency reasons, the implementation uses a sharing mechanism to ensure that newly created instances share as much data as possible with the previous instance while ensuring that operations have a predictable time complexity.\r\n\r\nThe System.Collections.Immutable library is built-in as part of the shared framework in .NET Runtime. The package can be installed when you need to use it in other target frameworks.")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Collections.Immutable")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.System.Collections.Immutable { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string Arg_KeyNotFoundWithKey => GetResourceString("Arg_KeyNotFoundWithKey"); internal static string ArrayInitializedStateNotEqual => GetResourceString("ArrayInitializedStateNotEqual"); internal static string ArrayLengthsNotEqual => GetResourceString("ArrayLengthsNotEqual"); internal static string CannotFindOldValue => GetResourceString("CannotFindOldValue"); internal static string CapacityMustBeGreaterThanOrEqualToCount => GetResourceString("CapacityMustBeGreaterThanOrEqualToCount"); internal static string CapacityMustEqualCountOnMove => GetResourceString("CapacityMustEqualCountOnMove"); internal static string CollectionModifiedDuringEnumeration => GetResourceString("CollectionModifiedDuringEnumeration"); internal static string DuplicateKey => GetResourceString("DuplicateKey"); internal static string InvalidEmptyOperation => GetResourceString("InvalidEmptyOperation"); internal static string InvalidOperationOnDefaultArray => GetResourceString("InvalidOperationOnDefaultArray"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string? EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type? StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class NonVersionableAttribute : Attribute { } } namespace System.Linq { public static class ImmutableArrayExtensions { public static IEnumerable<TResult> Select<T, TResult>(this ImmutableArray<T> immutableArray, Func<T, TResult> selector) { immutableArray.ThrowNullRefIfNotInitialized(); return immutableArray.array.Select(selector); } public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(this ImmutableArray<TSource> immutableArray, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector) { immutableArray.ThrowNullRefIfNotInitialized(); if (collectionSelector == null || resultSelector == null) { return Enumerable.SelectMany(immutableArray, collectionSelector, resultSelector); } if (immutableArray.Length != 0) { return immutableArray.SelectManyIterator(collectionSelector, resultSelector); } return Enumerable.Empty<TResult>(); } public static IEnumerable<T> Where<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { immutableArray.ThrowNullRefIfNotInitialized(); return immutableArray.array.Where(predicate); } public static bool Any<T>(this ImmutableArray<T> immutableArray) { return immutableArray.Length > 0; } public static bool Any<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { immutableArray.ThrowNullRefIfNotInitialized(); Requires.NotNull(predicate, "predicate"); T[] array = immutableArray.array; foreach (T arg in array) { if (predicate(arg)) { return true; } } return false; } public static bool All<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { immutableArray.ThrowNullRefIfNotInitialized(); Requires.NotNull(predicate, "predicate"); T[] array = immutableArray.array; foreach (T arg in array) { if (!predicate(arg)) { return false; } } return true; } public static bool SequenceEqual<TDerived, TBase>(this ImmutableArray<TBase> immutableArray, ImmutableArray<TDerived> items, IEqualityComparer<TBase>? comparer = null) where TDerived : TBase { immutableArray.ThrowNullRefIfNotInitialized(); items.ThrowNullRefIfNotInitialized(); if (immutableArray.array == items.array) { return true; } if (immutableArray.Length != items.Length) { return false; } if (comparer == null) { comparer = EqualityComparer<TBase>.Default; } for (int i = 0; i < immutableArray.Length; i++) { if (!comparer.Equals(immutableArray.array[i], (TBase)(object)items.array[i])) { return false; } } return true; } public static bool SequenceEqual<TDerived, TBase>(this ImmutableArray<TBase> immutableArray, IEnumerable<TDerived> items, IEqualityComparer<TBase>? comparer = null) where TDerived : TBase { Requires.NotNull(items, "items"); if (comparer == null) { comparer = EqualityComparer<TBase>.Default; } int num = 0; int length = immutableArray.Length; foreach (TDerived item in items) { if (num == length) { return false; } if (!comparer.Equals(immutableArray[num], (TBase)(object)item)) { return false; } num++; } return num == length; } public static bool SequenceEqual<TDerived, TBase>(this ImmutableArray<TBase> immutableArray, ImmutableArray<TDerived> items, Func<TBase, TBase, bool> predicate) where TDerived : TBase { Requires.NotNull(predicate, "predicate"); immutableArray.ThrowNullRefIfNotInitialized(); items.ThrowNullRefIfNotInitialized(); if (immutableArray.array == items.array) { return true; } if (immutableArray.Length != items.Length) { return false; } int i = 0; for (int length = immutableArray.Length; i < length; i++) { if (!predicate(immutableArray[i], (TBase)(object)items[i])) { return false; } } return true; } public static T? Aggregate<T>(this ImmutableArray<T> immutableArray, Func<T, T, T> func) { Requires.NotNull(func, "func"); if (immutableArray.Length == 0) { return default(T); } T val = immutableArray[0]; int i = 1; for (int length = immutableArray.Length; i < length; i++) { val = func(val, immutableArray[i]); } return val; } public static TAccumulate Aggregate<TAccumulate, T>(this ImmutableArray<T> immutableArray, TAccumulate seed, Func<TAccumulate, T, TAccumulate> func) { Requires.NotNull(func, "func"); TAccumulate val = seed; T[] array = immutableArray.array; foreach (T arg in array) { val = func(val, arg); } return val; } public static TResult Aggregate<TAccumulate, TResult, T>(this ImmutableArray<T> immutableArray, TAccumulate seed, Func<TAccumulate, T, TAccumulate> func, Func<TAccumulate, TResult> resultSelector) { Requires.NotNull(resultSelector, "resultSelector"); return resultSelector(immutableArray.Aggregate(seed, func)); } public static T ElementAt<T>(this ImmutableArray<T> immutableArray, int index) { return immutableArray[index]; } public static T? ElementAtOrDefault<T>(this ImmutableArray<T> immutableArray, int index) { if (index < 0 || index >= immutableArray.Length) { return default(T); } return immutableArray[index]; } public static T First<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { Requires.NotNull(predicate, "predicate"); T[] array = immutableArray.array; foreach (T val in array) { if (predicate(val)) { return val; } } return Enumerable.Empty<T>().First(); } public static T First<T>(this ImmutableArray<T> immutableArray) { if (immutableArray.Length <= 0) { return immutableArray.array.First(); } return immutableArray[0]; } public static T? FirstOrDefault<T>(this ImmutableArray<T> immutableArray) { if (immutableArray.array.Length == 0) { return default(T); } return immutableArray.array[0]; } public static T? FirstOrDefault<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { Requires.NotNull(predicate, "predicate"); T[] array = immutableArray.array; foreach (T val in array) { if (predicate(val)) { return val; } } return default(T); } public static T Last<T>(this ImmutableArray<T> immutableArray) { if (immutableArray.Length <= 0) { return immutableArray.array.Last(); } return immutableArray[immutableArray.Length - 1]; } public static T Last<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { Requires.NotNull(predicate, "predicate"); for (int num = immutableArray.Length - 1; num >= 0; num--) { if (predicate(immutableArray[num])) { return immutableArray[num]; } } return Enumerable.Empty<T>().Last(); } public static T? LastOrDefault<T>(this ImmutableArray<T> immutableArray) { immutableArray.ThrowNullRefIfNotInitialized(); return immutableArray.array.LastOrDefault(); } public static T? LastOrDefault<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { Requires.NotNull(predicate, "predicate"); for (int num = immutableArray.Length - 1; num >= 0; num--) { if (predicate(immutableArray[num])) { return immutableArray[num]; } } return default(T); } public static T Single<T>(this ImmutableArray<T> immutableArray) { immutableArray.ThrowNullRefIfNotInitialized(); return immutableArray.array.Single(); } public static T Single<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { Requires.NotNull(predicate, "predicate"); bool flag = true; T result = default(T); T[] array = immutableArray.array; foreach (T val in array) { if (predicate(val)) { if (!flag) { ImmutableArray.TwoElementArray.Single(); } flag = false; result = val; } } if (flag) { Enumerable.Empty<T>().Single(); } return result; } public static T? SingleOrDefault<T>(this ImmutableArray<T> immutableArray) { immutableArray.ThrowNullRefIfNotInitialized(); return immutableArray.array.SingleOrDefault(); } public static T? SingleOrDefault<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { Requires.NotNull(predicate, "predicate"); bool flag = true; T result = default(T); T[] array = immutableArray.array; foreach (T val in array) { if (predicate(val)) { if (!flag) { ImmutableArray.TwoElementArray.Single(); } flag = false; result = val; } } return result; } public static Dictionary<TKey, T> ToDictionary<TKey, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector) where TKey : notnull { return immutableArray.ToDictionary(keySelector, EqualityComparer<TKey>.Default); } public static Dictionary<TKey, TElement> ToDictionary<TKey, TElement, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector, Func<T, TElement> elementSelector) where TKey : notnull { return immutableArray.ToDictionary(keySelector, elementSelector, EqualityComparer<TKey>.Default); } public static Dictionary<TKey, T> ToDictionary<TKey, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector, IEqualityComparer<TKey>? comparer) where TKey : notnull { Requires.NotNull(keySelector, "keySelector"); Dictionary<TKey, T> dictionary = new Dictionary<TKey, T>(immutableArray.Length, comparer); ImmutableArray<T>.Enumerator enumerator = immutableArray.GetEnumerator(); while (enumerator.MoveNext()) { T current = enumerator.Current; dictionary.Add(keySelector(current), current); } return dictionary; } public static Dictionary<TKey, TElement> ToDictionary<TKey, TElement, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector, Func<T, TElement> elementSelector, IEqualityComparer<TKey>? comparer) where TKey : notnull { Requires.NotNull(keySelector, "keySelector"); Requires.NotNull(elementSelector, "elementSelector"); Dictionary<TKey, TElement> dictionary = new Dictionary<TKey, TElement>(immutableArray.Length, comparer); T[] array = immutableArray.array; foreach (T arg in array) { dictionary.Add(keySelector(arg), elementSelector(arg)); } return dictionary; } public static T[] ToArray<T>(this ImmutableArray<T> immutableArray) { immutableArray.ThrowNullRefIfNotInitialized(); if (immutableArray.array.Length == 0) { return ImmutableArray<T>.Empty.array; } return (T[])immutableArray.array.Clone(); } public static T First<T>(this ImmutableArray<T>.Builder builder) { Requires.NotNull(builder, "builder"); if (!builder.Any()) { throw new InvalidOperationException(); } return builder[0]; } public static T? FirstOrDefault<T>(this ImmutableArray<T>.Builder builder) { Requires.NotNull(builder, "builder"); if (!builder.Any()) { return default(T); } return builder[0]; } public static T Last<T>(this ImmutableArray<T>.Builder builder) { Requires.NotNull(builder, "builder"); if (!builder.Any()) { throw new InvalidOperationException(); } return builder[builder.Count - 1]; } public static T? LastOrDefault<T>(this ImmutableArray<T>.Builder builder) { Requires.NotNull(builder, "builder"); if (!builder.Any()) { return default(T); } return builder[builder.Count - 1]; } public static bool Any<T>(this ImmutableArray<T>.Builder builder) { Requires.NotNull(builder, "builder"); return builder.Count > 0; } private static IEnumerable<TResult> SelectManyIterator<TSource, TCollection, TResult>(this ImmutableArray<TSource> immutableArray, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector) { TSource[] array = immutableArray.array; foreach (TSource item in array) { foreach (TCollection item2 in collectionSelector(item)) { yield return resultSelector(item, item2); } } } } } namespace System.Collections.Immutable { internal static class AllocFreeConcurrentStack<T> { private const int MaxSize = 35; private static readonly Type s_typeOfT = typeof(T); private static Stack<RefAsValueType<T>> ThreadLocalStack { get { Dictionary<Type, object> dictionary = AllocFreeConcurrentStack.t_stacks ?? (AllocFreeConcurrentStack.t_stacks = new Dictionary<Type, object>()); if (!dictionary.TryGetValue(s_typeOfT, out var value)) { value = new Stack<RefAsValueType<T>>(35); dictionary.Add(s_typeOfT, value); } return (Stack<RefAsValueType<T>>)value; } } public static void TryAdd(T item) { Stack<RefAsValueType<T>> threadLocalStack = ThreadLocalStack; if (threadLocalStack.Count < 35) { threadLocalStack.Push(new RefAsValueType<T>(item)); } } public static bool TryTake([MaybeNullWhen(false)] out T item) { Stack<RefAsValueType<T>> threadLocalStack = ThreadLocalStack; if (threadLocalStack != null && threadLocalStack.Count > 0) { item = threadLocalStack.Pop().Value; return true; } item = default(T); return false; } } internal static class AllocFreeConcurrentStack { [ThreadStatic] internal static Dictionary<Type, object>? t_stacks; } internal sealed class DictionaryEnumerator<TKey, TValue> : IDictionaryEnumerator, IEnumerator where TKey : notnull { private readonly IEnumerator<KeyValuePair<TKey, TValue>> _inner; public DictionaryEntry Entry => new DictionaryEntry(_inner.Current.Key, _inner.Current.Value); public object Key => _inner.Current.Key; public object? Value => _inner.Current.Value; public object Current => Entry; internal DictionaryEnumerator(IEnumerator<KeyValuePair<TKey, TValue>> inner) { Requires.NotNull(inner, "inner"); _inner = inner; } public bool MoveNext() { return _inner.MoveNext(); } public void Reset() { _inner.Reset(); } } internal struct DisposableEnumeratorAdapter<T, TEnumerator> : IDisposable where TEnumerator : struct, IEnumerator<T> { private readonly IEnumerator<T> _enumeratorObject; private TEnumerator _enumeratorStruct; public T Current { get { if (_enumeratorObject == null) { return _enumeratorStruct.Current; } return _enumeratorObject.Current; } } internal DisposableEnumeratorAdapter(TEnumerator enumerator) { _enumeratorStruct = enumerator; _enumeratorObject = null; } internal DisposableEnumeratorAdapter(IEnumerator<T> enumerator) { _enumeratorStruct = default(TEnumerator); _enumeratorObject = enumerator; } public bool MoveNext() { if (_enumeratorObject == null) { return _enumeratorStruct.MoveNext(); } return _enumeratorObject.MoveNext(); } public void Dispose() { if (_enumeratorObject != null) { _enumeratorObject.Dispose(); } else { _enumeratorStruct.Dispose(); } } public DisposableEnumeratorAdapter<T, TEnumerator> GetEnumerator() { return this; } } internal interface IBinaryTree { int Height { get; } bool IsEmpty { get; } int Count { get; } IBinaryTree? Left { get; } IBinaryTree? Right { get; } } internal interface IBinaryTree<out T> : IBinaryTree { T Value { get; } new IBinaryTree<T>? Left { get; } new IBinaryTree<T>? Right { get; } } internal interface IImmutableArray { Array? Array { get; } } public interface IImmutableDictionary<TKey, TValue> : IReadOnlyDictionary<TKey, TValue>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, IReadOnlyCollection<KeyValuePair<TKey, TValue>> { IImmutableDictionary<TKey, TValue> Clear(); IImmutableDictionary<TKey, TValue> Add(TKey key, TValue value); IImmutableDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs); IImmutableDictionary<TKey, TValue> SetItem(TKey key, TValue value); IImmutableDictionary<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items); IImmutableDictionary<TKey, TValue> RemoveRange(IEnumerable<TKey> keys); IImmutableDictionary<TKey, TValue> Remove(TKey key); bool Contains(KeyValuePair<TKey, TValue> pair); bool TryGetKey(TKey equalKey, out TKey actualKey); } internal interface IImmutableDictionaryInternal<TKey, TValue> { bool ContainsValue(TValue value); } public interface IImmutableList<T> : IReadOnlyList<T>, IEnumerable<T>, IEnumerable, IReadOnlyCollection<T> { IImmutableList<T> Clear(); int IndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer); int LastIndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer); IImmutableList<T> Add(T value); IImmutableList<T> AddRange(IEnumerable<T> items); IImmutableList<T> Insert(int index, T element); IImmutableList<T> InsertRange(int index, IEnumerable<T> items); IImmutableList<T> Remove(T value, IEqualityComparer<T>? equalityComparer); IImmutableList<T> RemoveAll(Predicate<T> match); IImmutableList<T> RemoveRange(IEnumerable<T> items, IEqualityComparer<T>? equalityComparer); IImmutableList<T> RemoveRange(int index, int count); IImmutableList<T> RemoveAt(int index); IImmutableList<T> SetItem(int index, T value); IImmutableList<T> Replace(T oldValue, T newValue, IEqualityComparer<T>? equalityComparer); } internal interface IImmutableListQueries<T> : IReadOnlyList<T>, IEnumerable<T>, IEnumerable, IReadOnlyCollection<T> { ImmutableList<TOutput> ConvertAll<TOutput>(Func<T, TOutput> converter); void ForEach(Action<T> action); ImmutableList<T> GetRange(int index, int count); void CopyTo(T[] array); void CopyTo(T[] array, int arrayIndex); void CopyTo(int index, T[] array, int arrayIndex, int count); bool Exists(Predicate<T> match); T? Find(Predicate<T> match); ImmutableList<T> FindAll(Predicate<T> match); int FindIndex(Predicate<T> match); int FindIndex(int startIndex, Predicate<T> match); int FindIndex(int startIndex, int count, Predicate<T> match); T? FindLast(Predicate<T> match); int FindLastIndex(Predicate<T> match); int FindLastIndex(int startIndex, Predicate<T> match); int FindLastIndex(int startIndex, int count, Predicate<T> match); bool TrueForAll(Predicate<T> match); int BinarySearch(T item); int BinarySearch(T item, IComparer<T>? comparer); int BinarySearch(int index, int count, T item, IComparer<T>? comparer); } public interface IImmutableQueue<T> : IEnumerable<T>, IEnumerable { bool IsEmpty { get; } IImmutableQueue<T> Clear(); T Peek(); IImmutableQueue<T> Enqueue(T value); IImmutableQueue<T> Dequeue(); } public interface IImmutableSet<T> : IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable { IImmutableSet<T> Clear(); bool Contains(T value); IImmutableSet<T> Add(T value); IImmutableSet<T> Remove(T value); bool TryGetValue(T equalValue, out T actualValue); IImmutableSet<T> Intersect(IEnumerable<T> other); IImmutableSet<T> Except(IEnumerable<T> other); IImmutableSet<T> SymmetricExcept(IEnumerable<T> other); IImmutableSet<T> Union(IEnumerable<T> other); bool SetEquals(IEnumerable<T> other); bool IsProperSubsetOf(IEnumerable<T> other); bool IsProperSupersetOf(IEnumerable<T> other); bool IsSubsetOf(IEnumerable<T> other); bool IsSupersetOf(IEnumerable<T> other); bool Overlaps(IEnumerable<T> other); } public interface IImmutableStack<T> : IEnumerable<T>, IEnumerable { bool IsEmpty { get; } IImmutableStack<T> Clear(); IImmutableStack<T> Push(T value); IImmutableStack<T> Pop(); T Peek(); } [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableEnumerableDebuggerProxy<>))] public sealed class ImmutableHashSet<T> : IImmutableSet<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable, IHashKeyCollection<T>, ICollection<T>, ISet<T>, ICollection, IStrongEnumerable<T, ImmutableHashSet<T>.Enumerator> { private sealed class HashBucketByValueEqualityComparer : IEqualityComparer<HashBucket> { private static readonly IEqualityComparer<HashBucket> s_defaultInstance = new HashBucketByValueEqualityComparer(EqualityComparer<T>.Default); private readonly IEqualityComparer<T> _valueComparer; internal static IEqualityComparer<HashBucket> DefaultInstance => s_defaultInstance; internal HashBucketByValueEqualityComparer(IEqualityComparer<T> valueComparer) { Requires.NotNull(valueComparer, "valueComparer"); _valueComparer = valueComparer; } public bool Equals(HashBucket x, HashBucket y) { return x.EqualsByValue(y, _valueComparer); } public int GetHashCode(HashBucket obj) { throw new NotSupportedException(); } } private sealed class HashBucketByRefEqualityComparer : IEqualityComparer<HashBucket> { private static readonly IEqualityComparer<HashBucket> s_defaultInstance = new HashBucketByRefEqualityComparer(); internal static IEqualityComparer<HashBucket> DefaultInstance => s_defaultInstance; private HashBucketByRefEqualityComparer() { } public bool Equals(HashBucket x, HashBucket y) { return x.EqualsByRef(y); } public int GetHashCode(HashBucket obj) { throw new NotSupportedException(); } } [DebuggerDisplay("Count = {Count}")] public sealed class Builder : IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable, ISet<T>, ICollection<T> { private SortedInt32KeyNode<HashBucket> _root = SortedInt32KeyNode<HashBucket>.EmptyNode; private IEqualityComparer<T> _equalityComparer; private readonly IEqualityComparer<HashBucket> _hashBucketEqualityComparer; private int _count; private ImmutableHashSet<T> _immutable; private int _version; public int Count => _count; bool ICollection<T>.IsReadOnly => false; public IEqualityComparer<T> KeyComparer { get { return _equalityComparer; } set { Requires.NotNull(value, "value"); if (value != _equalityComparer) { MutationResult mutationResult = ImmutableHashSet<T>.Union((IEnumerable<T>)this, new MutationInput(SortedInt32KeyNode<HashBucket>.EmptyNode, value, _hashBucketEqualityComparer, 0)); _immutable = null; _equalityComparer = value; Root = mutationResult.Root; _count = mutationResult.Count; } } } internal int Version => _version; private MutationInput Origin => new MutationInput(Root, _equalityComparer, _hashBucketEqualityComparer, _count); private SortedInt32KeyNode<HashBucket> Root { get { return _root; } set { _version++; if (_root != value) { _root = value; _immutable = null; } } } internal Builder(ImmutableHashSet<T> set) { Requires.NotNull(set, "set"); _root = set._root; _count = set._count; _equalityComparer = set._equalityComparer; _hashBucketEqualityComparer = set._hashBucketEqualityComparer; _immutable = set; } public Enumerator GetEnumerator() { return new Enumerator(_root, this); } public ImmutableHashSet<T> ToImmutable() { return _immutable ?? (_immutable = ImmutableHashSet<T>.Wrap(_root, _equalityComparer, _count)); } public bool TryGetValue(T equalValue, out T actualValue) { int key = ((equalValue != null) ? _equalityComparer.GetHashCode(equalValue) : 0); if (_root.TryGetValue(key, out var value)) { return value.TryExchange(equalValue, _equalityComparer, out actualValue); } actualValue = equalValue; return false; } public bool Add(T item) { MutationResult result = ImmutableHashSet<T>.Add(item, Origin); Apply(result); return result.Count != 0; } public bool Remove(T item) { MutationResult result = ImmutableHashSet<T>.Remove(item, Origin); Apply(result); return result.Count != 0; } public bool Contains(T item) { return ImmutableHashSet<T>.Contains(item, Origin); } public void Clear() { _count = 0; Root = SortedInt32KeyNode<HashBucket>.EmptyNode; } public void ExceptWith(IEnumerable<T> other) { MutationResult result = ImmutableHashSet<T>.Except(other, _equalityComparer, _hashBucketEqualityComparer, _root); Apply(result); } public void IntersectWith(IEnumerable<T> other) { MutationResult result = ImmutableHashSet<T>.Intersect(other, Origin); Apply(result); } public bool IsProperSubsetOf(IEnumerable<T> other) { return ImmutableHashSet<T>.IsProperSubsetOf(other, Origin); } public bool IsProperSupersetOf(IEnumerable<T> other) { return ImmutableHashSet<T>.IsProperSupersetOf(other, Origin); } public bool IsSubsetOf(IEnumerable<T> other) { return ImmutableHashSet<T>.IsSubsetOf(other, Origin); } public bool IsSupersetOf(IEnumerable<T> other) { return ImmutableHashSet<T>.IsSupersetOf(other, Origin); } public bool Overlaps(IEnumerable<T> other) { return ImmutableHashSet<T>.Overlaps(other, Origin); } public bool SetEquals(IEnumerable<T> other) { if (this == other) { return true; } return ImmutableHashSet<T>.SetEquals(other, Origin); } public void SymmetricExceptWith(IEnumerable<T> other) { MutationResult result = ImmutableHashSet<T>.SymmetricExcept(other, Origin); Apply(result); } public void UnionWith(IEnumerable<T> other) { MutationResult result = ImmutableHashSet<T>.Union(other, Origin); Apply(result); } void ICollection<T>.Add(T item) { Add(item); } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex"); using Enumerator enumerator = GetEnumerator(); while (enumerator.MoveNext()) { T current = enumerator.Current; array[arrayIndex++] = current; } } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private void Apply(MutationResult result) { Root = result.Root; if (result.CountType == CountType.Adjustment) { _count += result.Count; } else { _count = result.Count; } } } public struct Enumerator : IEnumerator<T>, IEnumerator, IDisposable, IStrongEnumerator<T> { private readonly Builder _builder; private SortedInt32KeyNode<HashBucket>.Enumerator _mapEnumerator; private HashBucket.Enumerator _bucketEnumerator; private int _enumeratingBuilderVersion; public T Current { get { _mapEnumerator.ThrowIfDisposed(); return _bucketEnumerator.Current; } } object? IEnumerator.Current => Current; internal Enumerator(SortedInt32KeyNode<HashBucket> root, Builder? builder = null) { _builder = builder; _mapEnumerator = new SortedInt32KeyNode<HashBucket>.Enumerator(root); _bucketEnumerator = default(HashBucket.Enumerator); _enumeratingBuilderVersion = builder?.Version ?? (-1); } public bool MoveNext() { ThrowIfChanged(); if (_bucketEnumerator.MoveNext()) { return true; } if (_mapEnumerator.MoveNext()) { _bucketEnumerator = new HashBucket.Enumerator(_mapEnumerator.Current.Value); return _bucketEnumerator.MoveNext(); } return false; } public void Reset() { _enumeratingBuilderVersion = ((_builder != null) ? _builder.Version : (-1)); _mapEnumerator.Reset(); _bucketEnumerator.Dispose(); _bucketEnumerator = default(HashBucket.Enumerator); } public void Dispose() { _mapEnumerator.Dispose(); _bucketEnumerator.Dispose(); } private void ThrowIfChanged() { if (_builder != null && _builder.Version != _enumeratingBuilderVersion) { throw new InvalidOperationException(System.SR.CollectionModifiedDuringEnumeration); } } } internal enum OperationResult { SizeChanged, NoChangeRequired } internal readonly struct HashBucket { internal struct Enumerator : IEnumerator<T>, IEnumerator, IDisposable { private enum Position { BeforeFirst, First, Additional, End } private readonly HashBucket _bucket; private bool _disposed; private Position _currentPosition; private ImmutableList<T>.Enumerator _additionalEnumerator; object? IEnumerator.Current => Current; public T Current { get { ThrowIfDisposed(); return _currentPosition switch { Position.First => _bucket._firstValue, Position.Additional => _additionalEnumerator.Current, _ => throw new InvalidOperationException(), }; } } internal Enumerator(HashBucket bucket) { _disposed = false; _bucket = bucket; _currentPosition = Position.BeforeFirst; _additionalEnumerator = default(ImmutableList<T>.Enumerator); } public bool MoveNext() { ThrowIfDisposed(); if (_bucket.IsEmpty) { _currentPosition = Position.End; return false; } switch (_currentPosition) { case Position.BeforeFirst: _currentPosition = Position.First; return true; case Position.First: if (_bucket._additionalElements.IsEmpty) { _currentPosition = Position.End; return false; } _currentPosition = Position.Additional; _additionalEnumerator = new ImmutableList<T>.Enumerator(_bucket._additionalElements); return _additionalEnumerator.MoveNext(); case Position.Additional: return _additionalEnumerator.MoveNext(); case Position.End: return false; default: throw new InvalidOperationException(); } } public void Reset() { ThrowIfDisposed(); _additionalEnumerator.Dispose(); _currentPosition = Position.BeforeFirst; } public void Dispose() { _disposed = true; _additionalEnumerator.Dispose(); } private void ThrowIfDisposed() { if (_disposed) { Requires.FailObjectDisposed(this); } } } private readonly T _firstValue; private readonly ImmutableList<T>.Node _additionalElements; internal bool IsEmpty => _additionalElements == null; private HashBucket(T firstElement, ImmutableList<T>.Node additionalElements = null) { _firstValue = firstElement; _additionalElements = additionalElements ?? ImmutableList<T>.Node.EmptyNode; } public Enumerator GetEnumerator() { return new Enumerator(this); } public override bool Equals(object? obj) { throw new NotSupportedException(); } public override int GetHashCode() { throw new NotSupportedException(); } internal bool EqualsByRef(HashBucket other) { if ((object)_firstValue == (object)other._firstValue) { return _additionalElements == other._additionalElements; } return false; } internal bool EqualsByValue(HashBucket other, IEqualityComparer<T> valueComparer) { if (valueComparer.Equals(_firstValue, other._firstValue)) { return _additionalElements == other._additionalElements; } return false; } internal HashBucket Add(T value, IEqualityComparer<T> valueComparer, out OperationResult result) { if (IsEmpty) { result = OperationResult.SizeChanged; return new HashBucket(value); } if (valueComparer.Equals(value, _firstValue) || _additionalElements.IndexOf(value, valueComparer) >= 0) { result = OperationResult.NoChangeRequired; return this; } result = OperationResult.SizeChanged; return new HashBucket(_firstValue, _additionalElements.Add(value)); } internal bool Contains(T value, IEqualityComparer<T> valueComparer) { if (IsEmpty) { return false; } if (!valueComparer.Equals(value, _firstValue)) { return _additionalElements.IndexOf(value, valueComparer) >= 0; } return true; } internal bool TryExchange(T value, IEqualityComparer<T> valueComparer, out T existingValue) { if (!IsEmpty) { if (valueComparer.Equals(value, _firstValue)) { existingValue = _firstValue; return true; } int num = _additionalElements.IndexOf(value, valueComparer); if (num >= 0) { existingValue = _additionalElements.ItemRef(num); return true; } } existingValue = value; return false; } internal HashBucket Remove(T value, IEqualityComparer<T> equalityComparer, out OperationResult result) { if (IsEmpty) { result = OperationResult.NoChangeRequired; return this; } if (equalityComparer.Equals(_firstValue, value)) { if (_additionalElements.IsEmpty) { result = OperationResult.SizeChanged; return default(HashBucket); } int count = _additionalElements.Left.Count; result = OperationResult.SizeChanged; return new HashBucket(_additionalElements.Key, _additionalElements.RemoveAt(count)); } int num = _additionalElements.IndexOf(value, equalityComparer); if (num < 0) { result = OperationResult.NoChangeRequired; return this; } result = OperationResult.SizeChanged; return new HashBucket(_firstValue, _additionalElements.RemoveAt(num)); } internal void Freeze() { _additionalElements?.Freeze(); } } private readonly struct MutationInput { private readonly SortedInt32KeyNode<HashBucket> _root; private readonly IEqualityComparer<T> _equalityComparer; private readonly int _count; private readonly IEqualityComparer<HashBucket> _hashBucketEqualityComparer; internal SortedInt32KeyNode<HashBucket> Root => _root; internal IEqualityComparer<T> EqualityComparer => _equalityComparer; internal int Count => _count; internal IEqualityComparer<HashBucket> HashBucketEqualityComparer => _hashBucketEqualityComparer; internal MutationInput(ImmutableHashSet<T> set) { Requires.NotNull(set, "set"); _root = set._root; _equalityComparer = set._equalityComparer; _count = set._count; _hashBucketEqualityComparer = set._hashBucketEqualityComparer; } internal MutationInput(SortedInt32KeyNode<HashBucket> root, IEqualityComparer<T> equalityComparer, IEqualityComparer<HashBucket> hashBucketEqualityComparer, int count) { Requires.NotNull(root, "root"); Requires.NotNull(equalityComparer, "equalityComparer"); Requires.Range(count >= 0, "count"); Requires.NotNull(hashBucketEqualityComparer, "hashBucketEqualityComparer"); _root = root; _equalityComparer = equalityComparer; _count = count; _hashBucketEqualityComparer = hashBucketEqualityComparer; } } private enum CountType { Adjustment, FinalValue } private readonly struct MutationResult { private readonly SortedInt32KeyNode<HashBucket> _root; private readonly int _count; private readonly CountType _countType; internal SortedInt32KeyNode<HashBucket> Root => _root; internal int Count => _count; internal CountType CountType => _countType; internal MutationResult(SortedInt32KeyNode<HashBucket> root, int count, CountType countType = CountType.Adjustment) { Requires.NotNull(root, "root"); _root = root; _count = count; _countType = countType; } internal ImmutableHashSet<T> Finalize(ImmutableHashSet<T> priorSet) { Requires.NotNull(priorSet, "priorSet"); int num = Count; if (CountType == CountType.Adjustment) { num += priorSet._count; } return priorSet.Wrap(Root, num); } } private readonly struct NodeEnumerable : IEnumerable<T>, IEnumerable { private readonly SortedInt32KeyNode<HashBucket> _root; internal NodeEnumerable(SortedInt32KeyNode<HashBucket> root) { Requires.NotNull(root, "root"); _root = root; } public Enumerator GetEnumerator() { return new Enumerator(_root); } [ExcludeFromCodeCoverage] IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } [ExcludeFromCodeCoverage] IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public static readonly ImmutableHashSet<T> Empty = new ImmutableHashSet<T>(SortedInt32KeyNode<HashBucket>.EmptyNode, EqualityComparer<T>.Default, 0); private static readonly Action<KeyValuePair<int, HashBucket>> s_FreezeBucketAction = delegate(KeyValuePair<int, HashBucket> kv) { kv.Value.Freeze(); }; private readonly IEqualityComparer<T> _equalityComparer; private readonly int _count; private readonly SortedInt32KeyNode<HashBucket> _root; private readonly IEqualityComparer<HashBucket> _hashBucketEqualityComparer; public int Count => _count; public bool IsEmpty => Count == 0; public IEqualityComparer<T> KeyComparer => _equalityComparer; [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot => this; [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized => true; internal IBinaryTree Root => _root; private MutationInput Origin => new MutationInput(this); bool ICollection<T>.IsReadOnly => true; internal ImmutableHashSet(IEqualityComparer<T> equalityComparer) : this(SortedInt32KeyNode<HashBucket>.EmptyNode, equalityComparer, 0) { } private ImmutableHashSet(SortedInt32KeyNode<HashBucket> root, IEqualityComparer<T> equalityComparer, int count) { Requires.NotNull(root, "root"); Requires.NotNull(equalityComparer, "equalityComparer"); root.Freeze(s_FreezeBucketAction); _root = root; _count = count; _equalityComparer = equalityComparer; _hashBucketEqualityComparer = GetHashBucketEqualityComparer(equalityComparer); } public ImmutableHashSet<T> Clear() { if (!IsEmpty) { return Empty.WithComparer(_equalityComparer); } return this; } IImmutableSet<T> IImmutableSet<T>.Clear() { return Clear(); } public Builder ToBuilder() { return new Builder(this); } public ImmutableHashSet<T> Add(T item) { return Add(item, Origin).Finalize(this); } public ImmutableHashSet<T> Remove(T item) { return Remove(item, Origin).Finalize(this); } public bool TryGetValue(T equalValue, out T actualValue) { int key = ((equalValue != null) ? _equalityComparer.GetHashCode(equalValue) : 0); if (_root.TryGetValue(key, out var value)) { return value.TryExchange(equalValue, _equalityComparer, out actualValue); } actualValue = equalValue; return false; } public ImmutableHashSet<T> Union(IEnumerable<T> other) { Requires.NotNull(other, "other"); return Union(other, avoidWithComparer: false); } public ImmutableHashSet<T> Intersect(IEnumerable<T> other) { Requires.NotNull(other, "other"); return Intersect(other, Origin).Finalize(this); } public ImmutableHashSet<T> Except(IEnumerable<T> other) { Requires.NotNull(other, "other"); return Except(other, _equalityComparer, _hashBucketEqualityComparer, _root).Finalize(this); } public ImmutableHashSet<T> SymmetricExcept(IEnumerable<T> other) { Requires.NotNull(other, "other"); return SymmetricExcept(other, Origin).Finalize(this); } public bool SetEquals(IEnumerable<T> other) { Requires.NotNull(other, "other"); if (this == other) { return true; } return SetEquals(other, Origin); } public bool IsProperSubsetOf(IEnumerable<T> other) { Requires.NotNull(other, "other"); return IsProperSubsetOf(other, Origin); } public bool IsProperSupersetOf(IEnumerable<T> other) { Requires.NotNull(other, "other"); return IsProperSupersetOf(other, Origin); } public bool IsSubsetOf(IEnumerable<T> other) { Requires.NotNull(other, "other"); return IsSubsetOf(other, Origin); } public bool IsSupersetOf(IEnumerable<T> other) { Requires.NotNull(other, "other"); return IsSupersetOf(other, Origin); } public bool Overlaps(IEnumerable<T> other) { Requires.NotNull(other, "other"); return Overlaps(other, Origin); } IImmutableSet<T> IImmutableSet<T>.Add(T item) { return Add(item); } IImmutableSet<T> IImmutableSet<T>.Remove(T item) { return Remove(item); } IImmutableSet<T> IImmutableSet<T>.Union(IEnumerable<T> other) { return Union(other); } IImmutableSet<T> IImmutableSet<T>.Intersect(IEnumerable<T> other) { return Intersect(other); } IImmutableSet<T> IImmutableSet<T>.Except(IEnumerable<T> other) { return Except(other); } IImmutableSet<T> IImmutableSet<T>.SymmetricExcept(IEnumerable<T> other) { return SymmetricExcept(other); } public bool Contains(T item) { return Contains(item, Origin); } public ImmutableHashSet<T> WithComparer(IEqualityComparer<T>? equalityComparer) { if (equalityComparer == null) { equalityComparer = EqualityComparer<T>.Default; } if (equalityComparer == _equalityComparer) { return this; } ImmutableHashSet<T> immutableHashSet = new ImmutableHashSet<T>(equalityComparer); return immutableHashSet.Union(this, avoidWithComparer: true); } bool ISet<T>.Add(T item) { throw new NotSupportedException(); } void ISet<T>.ExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } void ISet<T>.IntersectWith(IEnumerable<T> other) { throw new NotSupportedException(); } void ISet<T>.SymmetricExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } void ISet<T>.UnionWith(IEnumerable<T> other) { throw new NotSupportedException(); } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex"); using Enumerator enumerator = GetEnumerator(); while (enumerator.MoveNext()) { T current = enumerator.Current; array[arrayIndex++] = current; } } void ICollection<T>.Add(T item) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } void ICollection.CopyTo(Array array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex"); using Enumerator enumerator = GetEnumerator(); while (enumerator.MoveNext()) { T current = enumerator.Current; array.SetValue(current, arrayIndex++); } } public Enumerator GetEnumerator() { return new Enumerator(_root); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { if (!IsEmpty) { return GetEnumerator(); } return Enumerable.Empty<T>().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private static bool IsSupersetOf(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { if (!Contains(item, origin)) { return false; } } return true; } private static MutationResult Add(T item, MutationInput origin) { int num = ((item != null) ? origin.EqualityComparer.GetHashCode(item) : 0); OperationResult result; HashBucket newBucket = origin.Root.GetValueOrDefault(num).Add(item, origin.EqualityComparer, out result); if (result == OperationResult.NoChangeRequired) { return new MutationResult(origin.Root, 0); } SortedInt32KeyNode<HashBucket> root = UpdateRoot(origin.Root, num, origin.HashBucketEqualityComparer, newBucket); return new MutationResult(root, 1); } private static MutationResult Remove(T item, MutationInput origin) { OperationResult result = OperationResult.NoChangeRequired; int num = ((item != null) ? origin.EqualityComparer.GetHashCode(item) : 0); SortedInt32KeyNode<HashBucket> root = origin.Root; if (origin.Root.TryGetValue(num, out var value)) { HashBucket newBucket = value.Remove(item, origin.EqualityComparer, out result); if (result == OperationResult.NoChangeRequired) { return new MutationResult(origin.Root, 0); } root = UpdateRoot(origin.Root, num, origin.HashBucketEqualityComparer, newBucket); } return new MutationResult(root, (result == OperationResult.SizeChanged) ? (-1) : 0); } private static bool Contains(T item, MutationInput origin) { int key = ((item != null) ? origin.EqualityComparer.GetHashCode(item) : 0); if (origin.Root.TryGetValue(key, out var value)) { return value.Contains(item, origin.EqualityComparer); } return false; } private static MutationResult Union(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); int num = 0; SortedInt32KeyNode<HashBucket> sortedInt32KeyNode = origin.Root; foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { int num2 = ((item != null) ? origin.EqualityComparer.GetHashCode(item) : 0); OperationResult result; HashBucket newBucket = sortedInt32KeyNode.GetValueOrDefault(num2).Add(item, origin.EqualityComparer, out result); if (result == OperationResult.SizeChanged) { sortedInt32KeyNode = UpdateRoot(sortedInt32KeyNode, num2, origin.HashBucketEqualityComparer, newBucket); num++; } } return new MutationResult(sortedInt32KeyNode, num); } private static bool Overlaps(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); if (origin.Root.IsEmpty) { return false; } foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { if (Contains(item, origin)) { return true; } } return false; } private static bool SetEquals(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); HashSet<T> hashSet = new HashSet<T>(other, origin.EqualityComparer); if (origin.Count != hashSet.Count) { return false; } foreach (T item in hashSet) { if (!Contains(item, origin)) { return false; } } return true; } private static SortedInt32KeyNode<HashBucket> UpdateRoot(SortedInt32KeyNode<HashBucket> root, int hashCode, IEqualityComparer<HashBucket> hashBucketEqualityComparer, HashBucket newBucket) { bool mutated; if (newBucket.IsEmpty) { return root.Remove(hashCode, out mutated); } bool mutated2; return root.SetItem(hashCode, newBucket, hashBucketEqualityComparer, out mutated, out mutated2); } private static MutationResult Intersect(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); SortedInt32KeyNode<HashBucket> root = SortedInt32KeyNode<HashBucket>.EmptyNode; int num = 0; foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { if (Contains(item, origin)) { MutationResult mutationResult = Add(item, new MutationInput(root, origin.EqualityComparer, origin.HashBucketEqualityComparer, num)); root = mutationResult.Root; num += mutationResult.Count; } } return new MutationResult(root, num, CountType.FinalValue); } private static MutationResult Except(IEnumerable<T> other, IEqualityComparer<T> equalityComparer, IEqualityComparer<HashBucket> hashBucketEqualityComparer, SortedInt32KeyNode<HashBucket> root) { Requires.NotNull(other, "other"); Requires.NotNull(equalityComparer, "equalityComparer"); Requires.NotNull(root, "root"); int num = 0; SortedInt32KeyNode<HashBucket> sortedInt32KeyNode = root; foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { int num2 = ((item != null) ? equalityComparer.GetHashCode(item) : 0); if (sortedInt32KeyNode.TryGetValue(num2, out var value)) { OperationResult result; HashBucket newBucket = value.Remove(item, equalityComparer, out result); if (result == OperationResult.SizeChanged) { num--; sortedInt32KeyNode = UpdateRoot(sortedInt32KeyNode, num2, hashBucketEqualityComparer, newBucket); } } } return new MutationResult(sortedInt32KeyNode, num); } private static MutationResult SymmetricExcept(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); ImmutableHashSet<T> immutableHashSet = ImmutableHashSet.CreateRange(origin.EqualityComparer, other); int num = 0; SortedInt32KeyNode<HashBucket> root = SortedInt32KeyNode<HashBucket>.EmptyNode; foreach (T item in new NodeEnumerable(origin.Root)) { if (!immutableHashSet.Contains(item)) { MutationResult mutationResult = Add(item, new MutationInput(root, origin.EqualityComparer, origin.HashBucketEqualityComparer, num)); root = mutationResult.Root; num += mutationResult.Count; } } foreach (T item2 in immutableHashSet) { if (!Contains(item2, origin)) { MutationResult mutationResult2 = Add(item2, new MutationInput(root, origin.EqualityComparer, origin.HashBucketEqualityComparer, num)); root = mutationResult2.Root; num += mutationResult2.Count; } } return new MutationResult(root, num, CountType.FinalValue); } private static bool IsProperSubsetOf(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); if (origin.Root.IsEmpty) { return other.Any(); } HashSet<T> hashSet = new HashSet<T>(other, origin.EqualityComparer); if (origin.Count >= hashSet.Count) { return false; } int num = 0; bool flag = false; foreach (T item in hashSet) { if (Contains(item, origin)) { num++; } else { flag = true; } if (num == origin.Count && flag) { return true; } } return false; } private static bool IsProperSupersetOf(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); if (origin.Root.IsEmpty) { return false; } int num = 0; foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { num++; if (!Contains(item, origin)) { return false; } } return origin.Count > num; } private static bool IsSubsetOf(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); if (origin.Root.IsEmpty) { return true; } HashSet<T> hashSet = new HashSet<T>(other, origin.EqualityComparer); int num = 0; foreach (T item in hashSet) { if (Contains(item, origin)) { num++; } } return num == origin.Count; } private static ImmutableHashSet<T> Wrap(SortedInt32KeyNode<HashBucket> root, IEqualityComparer<T> equalityComparer, int count) { Requires.NotNull(root, "root"); Requires.NotNull(equalityComparer, "equalityComparer"); Requires.Range(count >= 0, "count"); return new ImmutableHashSet<T>(root, equalityComparer, count); } private static IEqualityComparer<HashBucket> GetHashBucketEqualityComparer(IEqualityComparer<T> valueComparer) { if (!ImmutableExtensions.IsValueType<T>()) { return HashBucketByRefEqualityComparer.DefaultInstance; } if (valueComparer == EqualityComparer<T>.Default) { return HashBucketByValueEqualityComparer.DefaultInstance; } return new HashBucketByValueEqualityComparer(valueComparer); } private ImmutableHashSet<T> Wrap(SortedInt32KeyNode<HashBucket> root, int adjustedCountIfDifferentRoot) { if (root == _root) { return this; } return new ImmutableHashSet<T>(root, _equalityComparer, adjustedCountIfDifferentRoot); } private ImmutableHashSet<T> Union(IEnumerable<T> items, bool avoidWithComparer) { Requires.NotNull(items, "items"); if (IsEmpty && !avoidWithComparer && items is ImmutableHashSet<T> immutableHashSet) { return immutableHashSet.WithComparer(KeyComparer); } return Union(items, Origin).Finalize(this); } } internal interface IStrongEnumerable<out T, TEnumerator> where TEnumerator : struct, IStrongEnumerator<T> { TEnumerator GetEnumerator(); } internal interface IStrongEnumerator<T> { T Current { get; } bool MoveNext(); } internal interface IOrderedCollection<out T> : IEnumerable<T>, IEnumerable { int Count { get; } T this[int index] { get; } } public static class ImmutableArray { internal static readonly byte[] TwoElementArray = new byte[2]; public static ImmutableArray<T> Create<T>() { return ImmutableArray<T>.Empty; } public static ImmutableArray<T> Create<T>(T item) { T[] items = new T[1] { item }; return new ImmutableArray<T>(items); } public static ImmutableArray<T> Create<T>(T item1, T item2) { T[] items = new T[2] { item1, item2 }; return new ImmutableArray<T>(items); } public static ImmutableArray<T> Create<T>(T item1, T item2, T item3) { T[] items = new T[3] { item1, item2, item3 }; return new ImmutableArray<T>(items); } public static ImmutableArray<T> Create<T>(T item1, T item2, T item3, T item4) { T[] items = new T[4] { item1, item2, item3, item4 }; return new ImmutableArray<T>(items); } public static ImmutableArray<T> Create<T>(ReadOnlySpan<T> items) { if (items.IsEmpty) { return ImmutableArray<T>.Empty; } T[] items2 = items.ToArray(); return new ImmutableArray<T>(items2); } public static ImmutableArray<T> Create<T>(Span<T> items) { return Create((ReadOnlySpan<T>)items); } public static ImmutableArray<T> ToImmutableArray<T>(this ReadOnlySpan<T> items) { return Create(items); } public static ImmutableArray<T> ToImmutableArray<T>(this Span<T> items) { return Create((ReadOnlySpan<T>)items); } public static ImmutableArray<T> CreateRange<T>(IEnumerable<T> items) { Requires.NotNull(items, "items"); if (items is IImmutableArray immutableArray) { Array array = immutableArray.Array; if (array == null) { throw new InvalidOperationException(System.SR.InvalidOperationOnDefaultArray); } return new ImmutableArray<T>((T[])array); } if (items.TryGetCount(out var count)) { return new ImmutableArray<T>(items.ToArray(count)); } return new ImmutableArray<T>(items.ToArray()); } public static ImmutableArray<T> Create<T>(params T[]? items) { if (items == null || items.Length == 0) { return ImmutableArray<T>.Empty; } T[] array = new T[items.Length]; Array.Copy(items, array, items.Length); return new ImmutableArray<T>(array); } public static ImmutableArray<T> Create<T>(T[] items, int start, int length) { Requires.NotNull(items, "items"); Requires.Range(start >= 0 && start <= items.Length, "start"); Requires.Range(length >= 0 && start + length <= items.Length, "length"); if (length == 0) { return Create<T>(); } T[] array = new T[length]; for (int i = 0; i < array.Length; i++) { array[i] = items[start + i]; } return new ImmutableArray<T>(array); } public static ImmutableArray<T> Create<T>(ImmutableArray<T> items, int start, int length) { Requires.Range(start >= 0 && start <= items.Length, "start"); Requires.Range(length >= 0 && start + length <= items.Length, "length"); if (length == 0) { return Create<T>(); } if (start == 0 && length == items.Length) { return items; } T[] array = new T[length]; Array.Copy(items.array, start, array, 0, length); return new ImmutableArray<T>(array); } public static ImmutableArray<TResult> CreateRange<TSource, TResult>(ImmutableArray<TSource> items, Func<TSource, TResult> selector) { Requires.NotNull(selector, "selector"); int length = items.Length; if (length == 0) { return Create<TResult>(); } TResult[] array = new TResult[length]; for (int i = 0; i < array.Length; i++) { array[i] = selector(items[i]); } return new ImmutableArray<TResult>(array); } public static ImmutableArray<TResult> CreateRange<TSource, TResult>(ImmutableArray<TSource> items, int start, int length, Func<TSource, TResult> selector) { int length2 = items.Length; Requires.Range(start >= 0 && start <= length2, "start"); Requires.Range(length >= 0 && start + length <= length2, "length"); Requires.NotNull(selector, "selector"); if (length == 0) { return Create<TResult>(); } TResult[] array = new TResult[length]; for (int i = 0; i < array.Length; i++) { array[i] = selector(items[i + start]); } return new ImmutableArray<TResult>(array); } public static ImmutableArray<TResult> CreateRange<TSource, TArg, TResult>(ImmutableArray<TSource> items, Func<TSource, TArg, TResult> selector, TArg arg) { Requires.NotNull(selector, "selector"); int length = items.Length; if (length == 0) { return Create<TResult>(); } TResult[] array = new TResult[length]; for (int i = 0; i < array.Length; i++) { array[i] = selector(items[i], arg); } return new ImmutableArray<TResult>(array); } public static ImmutableArray<TResult> CreateRange<TSource, TArg, TResult>(ImmutableArray<TSource> items, int start, int length, Func<TSource, TArg, TResult> selector, TArg arg) { int length2 = items.Length; Requires.Range(start >= 0 && start <= length2, "start"); Requires.Range(length >= 0 && start + length <= length2, "length"); Requires.NotNull(selector, "selector"); if (length == 0) { return Create<TResult>(); } TResult[] array = new TResult[length]; for (int i = 0; i < array.Length; i++) { array[i] = selector(items[i + start], arg); } return new ImmutableArray<TResult>(array); } public static ImmutableArray<T>.Builder CreateBuilder<T>() { return Create<T>().ToBuilder(); } public static ImmutableArray<T>.Builder CreateBuilder<T>(int initialCapacity) { return new ImmutableArray<T>.Builder(initialCapacity); } public static ImmutableArray<TSource> ToImmutableArray<TSource>(this IEnumerable<TSource> items) { if (items is ImmutableArray<TSource>) { return (ImmutableArray<TSource>)(object)items; } return CreateRange(items); } public static ImmutableArray<TSource> ToImmutableArray<TSource>(this ImmutableArray<TSource>.Builder builder) { Requires.NotNull(builder, "builder"); return builder.ToImmutable(); } public static int BinarySearch<T>(this ImmutableArray<T> array, T value) { return Array.BinarySearch(array.array, value); } public static int BinarySearch<T>(this ImmutableArray<T> array, T value, IComparer<T>? comparer) { return Array.BinarySearch(array.array, value, comparer); } public static int BinarySearch<T>(this ImmutableArray<T> array, int index, int length, T value) { return Array.BinarySearch(array.array, index, length, value); } public static int BinarySearch<T>(this ImmutableArray<T> array, int index, int length, T value, IComparer<T>? comparer) { return Array.BinarySearch(array.array, index, length, value, comparer); } } [DebuggerDisplay("{DebuggerDisplay,nq}")] [System.Runtime.Versioning.NonVersionable] public readonly struct ImmutableArray<T> : IReadOnlyList<T>, IEnumerable<T>, IEnumerable, IReadOnlyCollection<T>, IList<T>, ICollection<T>, IEquatable<ImmutableArray<T>>, IList, ICollection, IImmutableArray, IStructuralComparable, IStructuralEquatable, IImmutableList<T> { [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableArrayBuilderDebuggerProxy<>))] public sealed class Builder : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IReadOnlyList<T>, IReadOnlyCollection<T> { private T[] _elements; private int _count; public int Capacity { get { return _elements.Length; } set { if (value < _count) { throw new ArgumentException(System.SR.CapacityMustBeGreaterThanOrEqualToCount, "value"); } if (value == _elements.Length) { return; } if (value > 0) { T[] array = new T[value]; if (_count > 0) { Array.Copy(_elements, array, _count); } _elements = array; } else { _elements = ImmutableArray<T>.Empty.array; } } } public int Count { get { return _count; } set { Requires.Range(value >= 0, "value"); if (value < _count) { if (_count - value > 64) { Array.Clear(_elements, value, _count - value); } else { for (int i = value; i < Count; i++) { _elements[i] = default(T); } } } else if (value > _count) { EnsureCapacity(value); } _count = value; } } public T this[int index] { get { if (index >= Count) { ThrowIndexOutOfRangeException(); } return _elements[index]; } set { if (index >= Count) { ThrowIndexOutOfRangeException(); } _elements[index] = value; } } bool ICollection<T>.IsReadOnly => false; internal Builder(int capacity) { Requires.Range(capacity >= 0, "capacity"); _elements = new T[capacity]; _count = 0; } internal Builder() : this(8) { } private static void ThrowIndexOutOfRangeException() { throw new IndexOutOfRangeException(); } public ref readonly T ItemRef(int index) { if (index >= Count) { ThrowIndexOutOfRangeException(); } return ref _elements[index]; } public ImmutableArray<T> ToImmutable() { return new ImmutableArray<T>(ToArray()); } public ImmutableArray<T> MoveToImmutable() { if (Capacity != Count) { throw new InvalidOperationException(System.SR.CapacityMustEqualCountOnMove); } T[] elements = _elements; _elements = ImmutableArray<T>.Empty.array; _count = 0; return new ImmutableArray<T>(elements); } public void Clear() { Count = 0; } public void Insert(int index, T item) { Requires.Range(index >= 0 && index <= Count, "index"); EnsureCapacity(Count + 1); if (index < Count) { Array.Copy(_elements, index, _elements, index + 1, Count - index); } _count++; _elements[index] = item; } public void InsertRange(int index, IEnumerable<T> items) { Requires.Range(index >= 0 && index <= Count, "index"); Requires.NotNull(items, "items"); int count = ImmutableExtensions.GetCount(ref items); EnsureCapacity(Count + count); if (index != Count) { Array.Copy(_elements, index, _elements, index + count, _count - index); } if (!items.TryCopyTo(_elements, index)) { foreach (T item in items) { _elements[index++] = item; } } _count += count; } public void InsertRange(int index, ImmutableArray<T> items) { Requires.Range(index >= 0 && index <= Count, "index"); if (!items.IsEmpty) { EnsureCapacity(Count + items.Length); if (index != Count) { Array.Copy(_elements, index, _elements, index + items.Length, _count - index); } Array.Copy(items.array, 0, _elements, index, items.Length); _count += items.Length; } } public void Add(T item) { int num = _count + 1; EnsureCapacity(num); _elements[_count] = item; _count = num; } public void AddRange(IEnumerable<T> items) { Requires.NotNull(items, "items"); if (items.TryGetCount(out var count)) { EnsureCapacity(Count + count); if (items.TryCopyTo(_elements, _count)) { _count += count; return; } } foreach (T item in items) { Add(item); } } public void AddRange(params T[] items) { Requires.NotNull(items, "items"); int count = Count; Count += items.Length; Array.Copy(items, 0, _elements, count, items.Length); } public void AddRange<TDerived>(TDerived[] items) where TDerived : T { Requires.NotNull(items, "items"); int count = Count; Count += items.Length; Array.Copy(items, 0, _elements, count, items.Length); } public void AddRange(T[] items, int length) { Requires.NotNull(items, "items"); Requires.Range(length >= 0 && length <= items.Length, "length"); int count = Count; Count += length; Array.Copy(items, 0, _elements, count, length); } public void AddRange(ImmutableArray<T> items) { AddRange(items, items.Length); } public void AddRange(ImmutableArray<T> items, int length) { Requires.Range(length >= 0, "length"); if (items.array != null) { AddRange(items.array, length); } } public void AddRange(ReadOnlySpan<T> items) { int count = Count; Count += items.Length; items.CopyTo(new Span<T>(_elements, count, items.Length)); } public void AddRange<TDerived>(ReadOnlySpan<TDerived> items) where TDerived : T { int count = Count; Count += items.Length; Span<T> span = new Span<T>(_elements, count, items.Length); for (int i = 0; i < items.Length; i++) { span[i] = (T)(object)items[i]; } } public void AddRange<TDerived>(ImmutableArray<TDerived> items) where TDerived : T { if (items.array != null) { this.AddRange<TDerived>(items.array); } } public void AddRange(Builder items) { Requires.NotNull(items, "items"); AddRange(items._elements, items.Count); } public void AddRange<TDerived>(ImmutableArray<TDerived>.Builder items) where TDerived : T { Requires.NotNull(items, "items"); AddRange<TDerived>(items._elements, items.Count); } public bool Remove(T element) { int num = IndexOf(element); if (num >= 0) { RemoveAt(num); return true; } return false; } public bool Remove(T element, IEqualityComparer<T>? equalityComparer) { int num = IndexOf(element, 0, _count, equalityComparer); if (num >= 0) { RemoveAt(num); return true; } return false; } public void RemoveAll(Predicate<T> match) { List<int> list = null; for (int i = 0; i < _count; i++) { if (match(_elements[i])) { if (list == null) { list = new List<int>(); } list.Add(i); } } if (list != null) { RemoveAtRange(list); } } public void RemoveAt(int index) { Requires.Range(index >= 0 && index < Count, "index"); if (index < Count - 1) { Array.Copy(_elements, index + 1, _elements, index, Count - index - 1); } Count--; } public void RemoveRange(int index, int length) { Requires.Range(index >= 0 && index + length <= _count, "index"); if (length != 0) { if (index + length < _count) { Array.Copy(_elements, index + length, _elements, index, Count - index - length); } _count -= length; } } public void RemoveRange(IEnumerable<T> items) { RemoveRange(items, EqualityComparer<T>.Default); } public void RemoveRange(IEnumerable<T> items, IEqualityComparer<T>? equalityComparer) { Requires.NotNull(items, "items"); SortedSet<int> sortedSet = new SortedSet<int>(); foreach (T item in items) { int num = IndexOf(item, 0, _count, equalityComparer); while (num >= 0 && !sortedSet.Add(num) && num + 1 < _count) { num = IndexOf(item, num + 1, equalityComparer); } } RemoveAtRange(sortedSet); } public void Replace(T oldValue, T newValue) { Replace(oldValue, newValue, EqualityComparer<T>.Default); } public void Replace(T oldValue, T newValue, IEqualityComparer<T>? equalityComparer) { int num = IndexOf(oldValue, 0, _count, equalityComparer); if (num >= 0) { _elements[num] = newValue; } } public bool Contains(T item) { return IndexOf(item) >= 0; } public T[] ToArray() { if (Count == 0) { return ImmutableArray<T>.Empty.array; } T[] array = new T[Count]; Array.Copy(_elements, array, Count); return array; } public void CopyTo(T[] array, int index) { Requires.NotNull(array, "array"); Requires.Range(index >= 0 && index + Count <= array.Length, "index"); Array.Copy(_elements, 0, array, index, Count); } public void CopyTo(T[] destination) { Requires.NotNull(destination, "destination"); Array.Copy(_elements, 0, destination, 0, Count); } public void CopyTo(int sourceIndex, T[] destination, int destinationIndex, int length) { Requires.NotNull(destination, "destination"); Requires.Range(length >= 0, "length"); Requires.Range(sourceIndex >= 0 && sourceIndex + length <= Count, "sourceIndex"); Requires.Range(destinationIndex >= 0 && destinationIndex + length <= destination.Length, "destinationIndex"); Array.Copy(_elements, sourceIndex, destination, destinationIndex, length); } private void EnsureCapacity(int capacity) { if (_elements.Length < capacity) { int newSize = Math.Max(_elements.Length * 2, capacity); Array.Resize(ref _elements, newSize); } } public int IndexOf(T item) { return IndexOf(item, 0, _count, EqualityComparer<T>.Default); } public int IndexOf(T item, int startIndex) { return IndexOf(item, startIndex, Count - startIndex, EqualityComparer<T>.Default); } public int IndexOf(T item, int startIndex, int count) { return IndexOf(item, startIndex, count, EqualityComparer<T>.Default); } public int IndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer) { if (count == 0 && startIndex == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < Count, "startIndex"); Requires.Range(count >= 0 && startIndex + count <= Count, "count"); if (equalityComparer == null) { equalityComparer = EqualityComparer<T>.Default; } if (equalityComparer == EqualityComparer<T>.Default) { return Array.IndexOf(_elements, item, startIndex, count); } for (int i = startIndex; i < startIndex + count; i++) { if (equalityComparer.Equals(_elements[i], item)) { return i; } } return -1; } public int IndexOf(T item, int startIndex, IEqualityComparer<T>? equalityComparer) { return IndexOf(item, startIndex, Count - startIndex, equalityComparer); } public int LastIndexOf(T item) { if (Count == 0) { return -1; } return LastIndexOf(item, Count - 1, Count, EqualityComparer<T>.Default); } public int LastIndexOf(T item, int startIndex) { if (Count == 0 && startIndex == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < Count, "startIndex"); return LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default); } public int LastIndexOf(T item, int startIndex, int count) { return LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default); } public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer) { if (count == 0 && startIndex == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < Count, "startIndex"); Requires.Range(count >= 0 && startIndex - count + 1 >= 0, "count"); if (equalityComparer == null) { equalityComparer = EqualityComparer<T>.Default; } if (equalityComparer == EqualityComparer<T>.Default) { return Array.LastIndexOf(_elements, item, startIndex, count); } for (int num = startIndex; num >= startIndex - count + 1; num--) { if (equalityComparer.Equals(item, _elements[num])) { return num; } } return -1; } public void Reverse() { int num = 0; int num2 = _count - 1; T[] elements = _elements; while (num < num2) { T val = elements[num]; elements[num] = elements[num2]; elements[num2] = val; num++; num2--; } } public void Sort() { if (Count > 1) { Array.Sort(_elements, 0, Count, Comparer<T>.Default); } } public void Sort(Comparison<T> comparison) { Requires.NotNull(comparison, "comparison"); if (Count > 1) { Array.Sort(_elements, 0, _count, Comparer<T>.Create(comparison)); } } public void Sort(IComparer<T>? comparer) { if (Count > 1) { Array.Sort(_elements, 0, _count, comparer); } } public void Sort(int index, int count, IComparer<T>? comparer) { Requires.Range(index >= 0, "index"); Requires.Range(count >= 0 && index + count <= Count, "count"); if (count > 1) { Array.Sort(_elements, index, count, comparer); } } public void CopyTo(Span<T> destination) { Requires.Range(Count <= destination.Length, "destination"); new ReadOnlySpan<T>(_elements, 0, Count).CopyTo(destination); } public IEnumerator<T> GetEnumerator() { for (int i = 0; i < Count; i++) { yield return this[i]; } } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private void AddRange<TDerived>(TDerived[] items, int length) where TDerived : T { EnsureCapacity(Count + length); int count = Count; Count += length; T[] elements = _elements; for (int i = 0; i < length; i++) { elements[count + i] = (T)(object)items[i]; } } private void RemoveAtRange(ICollection<int> indicesToRemove) { Requires.NotNull(indicesToRemove, "indicesToRemove"); if (indicesToRemove.Count == 0) { return; } int num = 0; int num2 = 0; int num3 = -1; foreach (int item in indicesToRemove) { int num4 = ((num3 == -1) ? item : (item - num3 - 1)); Array.Copy(_elements, num + num2, _elements, num, num4); num2++; num += num4; num3 = item; } Array.Copy(_elements, num + num2, _elements, num, _elements.Length - (num + num2)); _count -= indicesToRemove.Count; } } public struct Enumerator { private readonly T[] _array; private int _index; public T Current => _array[_index]; internal Enumerator(T[] array) { _array = array; _index = -1; } public bool MoveNext() { return ++_index < _array.Length; } } private sealed class EnumeratorObject : IEnumerator<T>, IEnumerator, IDisposable { private static readonly IEnumerator<T> s_EmptyEnumerator = new EnumeratorObject(ImmutableArray<T>.Empty.array); private readonly T[] _array; private int _index; public T Current { get { if ((uint)_index < (uint)_array.Length) { return _array[_index]; } throw new InvalidOperationException(); } } object IEnumerator.Current => Current; private EnumeratorObject(T[] array) { _index = -1; _array = array; } public bool MoveNext() { int num = _index + 1; int num2 = _array.Length; if ((uint)num <= (uint)num2) { _index = num; return (uint)num < (uint)num2; } return false; } void IEnumerator.Reset() { _index = -1; } public void Dispose() { } internal static IEnumerator<T> Create(T[] array) { if (array.Length != 0) { return new EnumeratorObject(array); } return s_EmptyEnumerator; } } public static readonly ImmutableArray<T> Empty = new ImmutableArray<T>(new T[0]); [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly T[]? array; T IList<T>.this[int index] { get { ImmutableArray<T> immutableArray = this; immutableArray.ThrowInvalidOperationIfNotInitialized(); return immutableArray[index]; } set { throw new NotSupportedException(); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection<T>.IsReadOnly => true; [DebuggerBrowsable(DebuggerBrowsableState.Never)] int ICollection<T>.Count { get { ImmutableArray<T> immutableArray = this; immutableArray.ThrowInvalidOperationIfNotInitialized(); return immutableArray.Length; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] int IReadOnlyCollection<T>.Count { get { ImmutableArray<T> immutableArray = this; immutableArray.ThrowInvalidOperationIfNotInitialized(); return immutableArray.Length; } } T IReadOnlyList<T>.this[int index] { get { ImmutableArray<T> immutableArray = this; immutableArray.ThrowInvalidOperationIfNotInitialized(); return immutableArray[index]; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool IList.IsFixedSize => true; [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool IList.IsReadOnly => true; [DebuggerBrowsable(DebuggerBrowsableState.Never)] int ICollection.Count { get { ImmutableArray<T> immutableArray = this; immutableArray.ThrowInvalidOperationIfNotInitialized(); return immutableArray.Length; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized => true; [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { throw new NotSupportedException(); } } object? IList.this[int index] { get { ImmutableArray<T> immutableArray = this; immutableArray.ThrowInvalidOperationIfNotInitialized(); return immutableArray[index]; } set { throw new NotSupportedException(); } } public T this[int index] { [System.Runtime.Versioning.NonVersionable] get { return array[index]; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public bool IsEmpty { [System.Runtime.Versioning.NonVersionable] get { return array.Length == 0; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public int Length { [System.Runtime.Versioning.NonVersionable] get { return array.Length; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public bool IsDefault => array == null; [DebuggerBrowsable(DebuggerBrowsableState.Never)] public bool IsDefaultOrEmpty { get { ImmutableArray<T> immutableArray = this; if (immutableArray.array != null) { return immutableArray.array.Length == 0; } return true; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] Array? IImmutableArray.Array => array; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay { get { ImmutableArray<T> immutableArray = this; if (!immutableArray.IsDefault) { return $"Length = {immutableArray.Length}"; } return "Uninitialized"; } } public ReadOnlySpan<T> AsSpan() { return new ReadOnlySpan<T>(array); } public ReadOnlyMemory<T> AsMemory() { return new ReadOnlyMemory<T>(array); } public int IndexOf(T item) { ImmutableArray<T> immutableArray = this; return immutableArray.IndexOf(item, 0, immutableArray.Length, EqualityComparer<T>.Default); } public int IndexOf(T item, int startIndex, IEqualityComparer<T>? equalityComparer) { ImmutableArray<T> immutableArray = this; return immutableArray.IndexOf(item, startIndex, immutableArray.Length - startIndex, equalityComparer); } public int IndexOf(T item, int startIndex) { ImmutableArray<T> immutableArray = this; return immutableArray.IndexOf(item, startIndex, immutableArray.Length - startIndex, EqualityComparer<T>.Default); } public int IndexOf(T item, int startIndex, int count) { return IndexOf(item, startIndex, count, EqualityComparer<T>.Default); } public int IndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer) { ImmutableArray<T> immutableArray = this; immutableArray.ThrowNullRefIfNotInitialized(); if (count == 0 && startIndex == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < immutableArray.Length, "startIndex"); Requires.Range(count >= 0 && startIndex + count <= immutableArray.Length, "count"); if (equalityComparer == null) { equalityComparer = EqualityComparer<T>.Default; } if (equalityComparer == EqualityComparer<T>.Default) { return Array.IndexOf(immutableArray.array, item, startIndex, count); } for (int i = startIndex; i < startIndex + count; i++) { if (equalityComparer.Equals(immutableArray.array[i], item)) { return i; } } return -1; } public int LastIndexOf(T item) { ImmutableArray<T> immutableArray = this; if (immutableArray.IsEmpty) { return -1; } return immutableArray.LastIndexOf(item, immutableArray.Length - 1, immutableArray.Length, EqualityComparer<T>.Default); } public int LastIndexOf(T item, int startIndex) { ImmutableArray<T> immutableArray = this; if (immutableArray.IsEmpty && startIndex == 0) { return -1; } return immutableArray.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default); } public int LastIndexOf(T item, int startIndex, int count) { return LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default); } public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer) { ImmutableArray<T> immutableArray = this; immutableArray.ThrowNullRefIfNotInitialized(); if (startIndex == 0 && count == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < immutableArray.Length, "startIndex"); Requires.Range(count >= 0 && startIndex - count + 1 >= 0, "count"); if (equalityComparer == null) { equalityComparer = EqualityComparer<T>.Default; } if (equalityComparer == EqualityComparer<T>.Default) { return Array.LastIndexOf(immutableArray.array, item, startIndex, count); } for (int num = startIndex; num >= startIndex - count + 1; num--) { if (equalityComparer.Equals(item, immutableArray.array[num])) { return num; } } return -1; } public bool Contains(T item) { return IndexOf(item) >= 0; } public ImmutableArray<T> Insert(int index, T item) { ImmutableArray<T> immutableArray = this; immutableArray.ThrowNullRefIfNotInitialized(); Requires.Range(index >= 0 && index <= immutableArray.Length, "index"); if (immutableArray.IsEmpty) { return ImmutableArray.Create(item); } T[] array = new T[immutableArray.Length + 1]; array[index] = item; if (index != 0) { Array.Copy(immutableArray.array, array, index); } if (index != immutableArray.Length) { Array.Copy(immutableArray.array, index, array, index + 1, immutableArray.Length - index); } return new ImmutableArray<T>(array); } public ImmutableArray<T> InsertRange(int index, IEnumerable<T> items) { ImmutableArray<T> result = this; result.ThrowNullRefIfNotInitialized(); Requires.Range(index >= 0 && index <= result.Length, "index"); Requires.NotNull(items, "items"); if (result.IsEmpty) { return ImmutableArray.CreateRange(items); } int count = ImmutableExtensions.GetCount(ref items); if (count == 0) { return result; } T[] array = new T[result.Length + count]; if (index != 0) { Array.Copy(result.array, array, index); } if (index != result.Length) { Array.Copy(result.array, index, array, index + count, result.Length - index); } if (!items.TryCopyTo(array, index)) { int num = index; foreach (T item in items) { array[num++] = item; } } return new ImmutableArray<T>(array); } public ImmutableArray<T> InsertRange(int index, ImmutableArray<T> items) { ImmutableArray<T> result = this; result.ThrowNullRefIfNotInitialized(); items.ThrowNullRefIfNotInitialized(); Requires.Range(index >= 0 && index <= result.Length, "index"); if (result.IsEmpty) { return items; } if (items.IsEmpty) { return result; } return result.InsertSpanRangeInternal(index, items.AsSpan()); } public ImmutableArray<T> Add(T item) { ImmutableArray<T> immutableArray = this; if (immutableArray.IsEmpty) { return ImmutableArray.Create(item); } return immutableArray.Insert(immutableArray.Length, item); } public ImmutableArray<T> AddRange(IEnumerable<T> items) { ImmutableArray<T> immutableArray = this; return immutableArray.InsertRange(immutableArray.Length, items); } public ImmutableArray<T> AddRange(T[] items, int length) { ImmutableArray<T> result = this; result.ThrowNullRefIfNotInitialized(); Requires.NotNull(items, "items"); Requires.Range(length >= 0 && length <= items.Length, "length"); if (items.Length == 0 || length == 0) { return result; } if (result.IsEmpty) { return ImmutableArray.Create(items, 0, length); } T[] array = new T[result.Length + length]; Array.Copy(result.array, array, result.Length); Array.Copy(items, 0, array, result.Length, length); return new ImmutableArray<T>(array); } public ImmutableArray<T> AddRange<TDerived>(TDerived[] items) where TDerived : T { ImmutableArray<T> result = this; result.ThrowNullRefIfNotInitialized(); Requires.NotNull(items, "items"); if (items.Length == 0) { return result; } T[] array = new T[result.Length + items.Length]; Array.Copy(result.array, array, result.Length); Array.Copy(items, 0, array, result.Length, items.Length); return new ImmutableArray<T>(array); } public ImmutableArray<T> AddRange(ImmutableArray<T> items, int length) { ImmutableArray<T> result = this; Requires.Range(length >= 0, "length"); if (items.array != null) { return result.AddRange(items.array, length); } return result; } public ImmutableArray<T> AddRange<TDerived>(ImmutableArray<TDerived> items) where TDerived : T { ImmutableArray<T> result = this; if (items.array != null) { return result.AddRange<TDerived>(items.array); } return result; } public ImmutableArray<T> AddRange(ImmutableArray<T> items) { ImmutableArray<T> immutableArray = this; return immutableArray.InsertRange(immutableArray.Length, items); } public ImmutableArray<T> SetItem(int index, T item) { ImmutableArray<T> immutableArray = this; immutableArray.ThrowNullRefIfNotInitialized(); Requires.Range(index >= 0 && index < immutableArray.Length, "index"); T[] array = new T[immutableArray.Length]; Array.Copy(immutableArray.array, array, immutableArray.Length); array[index] = item; return new ImmutableArray<T>(array); } public ImmutableArray<T> Replace(T oldValue, T newValue) { return Replace(oldValue, newValue, EqualityComparer<T>.Default); } public ImmutableArray<T> Replace(T oldValue, T newValue, IEqualityComparer<T>? equalityComparer) { ImmutableArray<T> immutableArray = this; int num = immutableArray.IndexOf(oldValue, 0, immutableArray.Length, equalityComparer); if (num < 0) { throw new ArgumentException(System.SR.CannotFindOldValue, "oldValue"); } return immutableArray.SetItem(num, newValue); } public ImmutableArray<T> Remove(T item) { return Remove(item, EqualityComparer<T>.Default); } public ImmutableArray<T> Remove(T item, IEqualityComparer<T>? equalityComparer) { ImmutableArray<T> result = this; result.ThrowNullRefIfNotInitialized(); int num = result.IndexOf(item, 0, result.Length, equalityComparer); if (num >= 0) { return result.RemoveAt(num); } return result; } public ImmutableArray<T> RemoveAt(int index) { return RemoveRange(index, 1); } public ImmutableArray<T> RemoveRange(int index, int length) { ImmutableArray<T> result = this; result.ThrowNullRefIfNotInitialized(); Requires.Range(index >= 0 && index <= result.Length, "index"); Requires.Range(length >= 0 && index + length <= result.Length, "length"); if (length == 0) { return result; } T[] array = new T[result.Length - length]; Array.Copy(result.array, array, index); Array.Copy(result.array, index + length, array, index, result.Length - index - length); return new ImmutableArray<T>(array); } public ImmutableArray<T> RemoveRange(IEnumerable<T> items) { return RemoveRange(items, EqualityComparer<T>.Default); } public ImmutableArray<T> RemoveRange(IEnumerable<T> items, IEqualityComparer<T>? equalityComparer) { ImmutableArray<T> immutableArray = this; immutableArray.ThrowNullRefIfNotInitialized(); Requires.NotNull(items, "items"); SortedSet<int> sortedSet = new SortedSet<int>(); foreach (T item in items) { int num = -1; do { num = immutableArray.IndexOf(item, num + 1, equalityComparer); } while (num >= 0